three-render-objects 1.42.0 → 1.43.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.
- package/README.md +2 -2
- package/dist/three-render-objects.d.ts +2 -2
- package/dist/three-render-objects.js +18414 -12825
- package/dist/three-render-objects.js.map +1 -1
- package/dist/three-render-objects.min.js +2 -2
- package/dist/three-render-objects.mjs +191 -327
- package/package.json +12 -11
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
// Version 1.
|
|
2
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("three")):"function"==typeof define&&define.amd?define(["three"],t):(e="undefined"!=typeof globalThis?globalThis:e||self).ThreeRenderObjects=t(e.THREE)}(this,function(e){"use strict";function t(e,t){(null==t||t>e.length)&&(t=e.length);for(var s=0,i=Array(t);s<t;s++)i[s]=e[s];return i}function s(e,t,s){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var s=e[Symbol.toPrimitive];if(void 0!==s){var i=s.call(e,t);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function i(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var s=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=s){var i,r,n,a,o=[],h=!0,l=!1;try{if(n=(s=s.call(e)).next,0===t);else for(;!(h=(i=n.call(s)).done)&&(o.push(i.value),o.length!==t);h=!0);}catch(e){l=!0,r=e}finally{try{if(!h&&null!=s.return&&(a=s.return(),Object(a)!==a))return}finally{if(l)throw r}}return o}}(e,t)||n(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function r(e){return function(e){if(Array.isArray(e))return t(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||n(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function n(e,s){if(e){if("string"==typeof e)return t(e,s);var i={}.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?t(e,s):void 0}}!function(e,t){void 0===t&&(t={});var s=t.insertAt;if("undefined"!=typeof document){var i=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css","top"===s&&i.firstChild?i.insertBefore(r,i.firstChild):i.appendChild(r),r.styleSheet?r.styleSheet.cssText=e:r.appendChild(document.createTextNode(e))}}(".scene-nav-info {\n position: absolute;\n bottom: 5px;\n width: 100%;\n text-align: center;\n color: slategrey;\n opacity: 0.7;\n font-size: 10px;\n font-family: sans-serif;\n pointer-events: none;\n user-select: none;\n}\n\n.scene-container canvas:focus {\n outline: none;\n}");const a="184",o=0,h=1,l=2,u=100,c=101,d=102,p=200,m=201,g=202,f=203,y=204,b=205,_=206,x=207,v=208,T=209,S=210,w=0,M=1,N=2,A=3,E=4,R=5,C=6,P=7,B=301,F=302,L=1e3,D=1001,I=1002,O=1003,U=1004,k=1005,z=1006,V=1007,G=1008,j=1009,$=1010,W=1011,H=1012,q=1013,X=1014,Y=1015,K=1016,Q=1017,Z=1018,J=1020,ee=35902,te=35899,se=1021,ie=1022,re=1023,ne=1026,ae=1027,oe=1028,he=1029,le=1030,ue=1031,ce=1033,de=33776,pe=33777,me=33778,ge=33779,fe=35840,ye=35841,be=35842,_e=35843,xe=36196,ve=37492,Te=37496,Se=37488,we=37489,Me=37490,Ne=37491,Ae=37808,Ee=37809,Re=37810,Ce=37811,Pe=37812,Be=37813,Fe=37814,Le=37815,De=37816,Ie=37817,Oe=37818,Ue=37819,ke=37820,ze=37821,Ve=36492,Ge=36283,je=36284,$e=36285,We=36286,He="",qe="srgb",Xe="srgb-linear",Ye="linear",Ke="srgb",Qe=7680,Ze=512,Je=513,et=514,tt=515,st=516,it=517,rt=518,nt=519,at=35044,ot=35048,ht=2e3,lt=2001,ut="compute",ct="render",dt="depthTextureCompare";function pt(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function mt(e){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}const gt={};function ft(...e){const t="THREE."+e.shift();console.log(t,...e)}function yt(e){const t=e[0];if("string"==typeof t&&t.startsWith("TSL:")){const t=e[1];t&&t.isStackTrace?e[0]+=" "+t.getLocation():e[1]='Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'}return e}function bt(...e){const t="THREE."+(e=yt(e)).shift();{const s=e[0];s&&s.isStackTrace?console.warn(s.getError(t)):console.warn(t,...e)}}function _t(...e){const t="THREE."+(e=yt(e)).shift();{const s=e[0];s&&s.isStackTrace?console.error(s.getError(t)):console.error(t,...e)}}function xt(...e){const t=e.join(" ");t in gt||(gt[t]=!0,bt(...e))}function vt(){return"undefined"!=typeof self&&void 0!==self.scheduler&&void 0!==self.scheduler.yield?self.scheduler.yield():new Promise(e=>{requestAnimationFrame(e)})}const Tt={[w]:1,[N]:6,[E]:7,[A]:5,[M]:0,[C]:2,[P]:4,[R]:3};class St{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 wt=["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 Mt=1234567;const Nt=Math.PI/180,At=180/Math.PI;function Et(){const e=4294967295*Math.random()|0,t=4294967295*Math.random()|0,s=4294967295*Math.random()|0,i=4294967295*Math.random()|0;return(wt[255&e]+wt[e>>8&255]+wt[e>>16&255]+wt[e>>24&255]+"-"+wt[255&t]+wt[t>>8&255]+"-"+wt[t>>16&15|64]+wt[t>>24&255]+"-"+wt[63&s|128]+wt[s>>8&255]+"-"+wt[s>>16&255]+wt[s>>24&255]+wt[255&i]+wt[i>>8&255]+wt[i>>16&255]+wt[i>>24&255]).toLowerCase()}function Rt(e,t,s){return Math.max(t,Math.min(s,e))}function Ct(e,t){return(e%t+t)%t}function Pt(e,t,s){return(1-s)*e+s*t}function Bt(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 Ft(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 Lt={DEG2RAD:Nt,RAD2DEG:At,generateUUID:Et,clamp:Rt,euclideanModulo:Ct,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:Pt,damp:function(e,t,s,i){return Pt(e,t,1-Math.exp(-s*i))},pingpong:function(e,t=1){return t-Math.abs(Ct(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&&(Mt=e);let t=Mt+=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*Nt},radToDeg:function(e){return e*At},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,a=Math.sin,o=n(s/2),h=a(s/2),l=n((t+i)/2),u=a((t+i)/2),c=n((t-i)/2),d=a((t-i)/2),p=n((i-t)/2),m=a((i-t)/2);switch(r){case"XYX":e.set(o*u,h*c,h*d,o*l);break;case"YZY":e.set(h*d,o*u,h*c,o*l);break;case"ZXZ":e.set(h*c,h*d,o*u,o*l);break;case"XZX":e.set(o*u,h*m,h*p,o*l);break;case"YXY":e.set(h*p,o*u,h*m,o*l);break;case"ZYZ":e.set(h*m,h*p,o*u,o*l);break;default:bt("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}},normalize:Ft,denormalize:Bt};class Dt{static{Dt.prototype.isVector2=!0}constructor(e=0,t=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=Rt(this.x,e.x,t.x),this.y=Rt(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=Rt(this.x,e,t),this.y=Rt(this.y,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(Rt(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(Rt(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 It{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,a){let o=s[i+0],h=s[i+1],l=s[i+2],u=s[i+3],c=r[n+0],d=r[n+1],p=r[n+2],m=r[n+3];if(u!==m||o!==c||h!==d||l!==p){let e=o*c+h*d+l*p+u*m;e<0&&(c=-c,d=-d,p=-p,m=-m,e=-e);let t=1-a;if(e<.9995){const s=Math.acos(e),i=Math.sin(s);t=Math.sin(t*s)/i,o=o*t+c*(a=Math.sin(a*s)/i),h=h*t+d*a,l=l*t+p*a,u=u*t+m*a}else{o=o*t+c*a,h=h*t+d*a,l=l*t+p*a,u=u*t+m*a;const e=1/Math.sqrt(o*o+h*h+l*l+u*u);o*=e,h*=e,l*=e,u*=e}}e[t]=o,e[t+1]=h,e[t+2]=l,e[t+3]=u}static multiplyQuaternionsFlat(e,t,s,i,r,n){const a=s[i],o=s[i+1],h=s[i+2],l=s[i+3],u=r[n],c=r[n+1],d=r[n+2],p=r[n+3];return e[t]=a*p+l*u+o*d-h*c,e[t+1]=o*p+l*c+h*u-a*d,e[t+2]=h*p+l*d+a*c-o*u,e[t+3]=l*p-a*u-o*c-h*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,a=Math.cos,o=Math.sin,h=a(s/2),l=a(i/2),u=a(r/2),c=o(s/2),d=o(i/2),p=o(r/2);switch(n){case"XYZ":this._x=c*l*u+h*d*p,this._y=h*d*u-c*l*p,this._z=h*l*p+c*d*u,this._w=h*l*u-c*d*p;break;case"YXZ":this._x=c*l*u+h*d*p,this._y=h*d*u-c*l*p,this._z=h*l*p-c*d*u,this._w=h*l*u+c*d*p;break;case"ZXY":this._x=c*l*u-h*d*p,this._y=h*d*u+c*l*p,this._z=h*l*p+c*d*u,this._w=h*l*u-c*d*p;break;case"ZYX":this._x=c*l*u-h*d*p,this._y=h*d*u+c*l*p,this._z=h*l*p-c*d*u,this._w=h*l*u+c*d*p;break;case"YZX":this._x=c*l*u+h*d*p,this._y=h*d*u+c*l*p,this._z=h*l*p-c*d*u,this._w=h*l*u-c*d*p;break;case"XZY":this._x=c*l*u-h*d*p,this._y=h*d*u-c*l*p,this._z=h*l*p+c*d*u,this._w=h*l*u+c*d*p;break;default:bt("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],a=t[5],o=t[9],h=t[2],l=t[6],u=t[10],c=s+a+u;if(c>0){const e=.5/Math.sqrt(c+1);this._w=.25/e,this._x=(l-o)*e,this._y=(r-h)*e,this._z=(n-i)*e}else if(s>a&&s>u){const e=2*Math.sqrt(1+s-a-u);this._w=(l-o)/e,this._x=.25*e,this._y=(i+n)/e,this._z=(r+h)/e}else if(a>u){const e=2*Math.sqrt(1+a-s-u);this._w=(r-h)/e,this._x=(i+n)/e,this._y=.25*e,this._z=(o+l)/e}else{const e=2*Math.sqrt(1+u-s-a);this._w=(n-i)/e,this._x=(r+h)/e,this._y=(o+l)/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(Rt(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,a=t._x,o=t._y,h=t._z,l=t._w;return this._x=s*l+n*a+i*h-r*o,this._y=i*l+n*o+r*a-s*h,this._z=r*l+n*h+s*o-i*a,this._w=n*l-s*a-i*o-r*h,this._onChangeCallback(),this}slerp(e,t){let s=e._x,i=e._y,r=e._z,n=e._w,a=this.dot(e);a<0&&(s=-s,i=-i,r=-r,n=-n,a=-a);let o=1-t;if(a<.9995){const e=Math.acos(a),h=Math.sin(e);o=Math.sin(o*e)/h,t=Math.sin(t*e)/h,this._x=this._x*o+s*t,this._y=this._y*o+i*t,this._z=this._z*o+r*t,this._w=this._w*o+n*t,this._onChangeCallback()}else this._x=this._x*o+s*t,this._y=this._y*o+i*t,this._z=this._z*o+r*t,this._w=this._w*o+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 Ot{static{Ot.prototype.isVector3=!0}constructor(e=0,t=0,s=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(kt.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(kt.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,a=e.z,o=e.w,h=2*(n*i-a*s),l=2*(a*t-r*i),u=2*(r*s-n*t);return this.x=t+o*h+n*u-a*l,this.y=s+o*l+a*h-r*u,this.z=i+o*u+r*l-n*h,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=Rt(this.x,e.x,t.x),this.y=Rt(this.y,e.y,t.y),this.z=Rt(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=Rt(this.x,e,t),this.y=Rt(this.y,e,t),this.z=Rt(this.z,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(Rt(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,a=t.y,o=t.z;return this.x=i*o-r*a,this.y=r*n-s*o,this.z=s*a-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 Ut.copy(this).projectOnVector(e),this.sub(Ut)}reflect(e){return this.sub(Ut.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(Rt(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 Ut=new Ot,kt=new It;class zt{static{zt.prototype.isMatrix3=!0}constructor(e,t,s,i,r,n,a,o,h){this.elements=[1,0,0,0,1,0,0,0,1],void 0!==e&&this.set(e,t,s,i,r,n,a,o,h)}set(e,t,s,i,r,n,a,o,h){const l=this.elements;return l[0]=e,l[1]=i,l[2]=a,l[3]=t,l[4]=r,l[5]=o,l[6]=s,l[7]=n,l[8]=h,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],a=s[3],o=s[6],h=s[1],l=s[4],u=s[7],c=s[2],d=s[5],p=s[8],m=i[0],g=i[3],f=i[6],y=i[1],b=i[4],_=i[7],x=i[2],v=i[5],T=i[8];return r[0]=n*m+a*y+o*x,r[3]=n*g+a*b+o*v,r[6]=n*f+a*_+o*T,r[1]=h*m+l*y+u*x,r[4]=h*g+l*b+u*v,r[7]=h*f+l*_+u*T,r[2]=c*m+d*y+p*x,r[5]=c*g+d*b+p*v,r[8]=c*f+d*_+p*T,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],a=e[5],o=e[6],h=e[7],l=e[8];return t*n*l-t*a*h-s*r*l+s*a*o+i*r*h-i*n*o}invert(){const e=this.elements,t=e[0],s=e[1],i=e[2],r=e[3],n=e[4],a=e[5],o=e[6],h=e[7],l=e[8],u=l*n-a*h,c=a*o-l*r,d=h*r-n*o,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*h-l*s)*m,e[2]=(a*s-i*n)*m,e[3]=c*m,e[4]=(l*t-i*o)*m,e[5]=(i*r-a*t)*m,e[6]=d*m,e[7]=(s*o-h*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,a){const o=Math.cos(r),h=Math.sin(r);return this.set(s*o,s*h,-s*(o*n+h*a)+n+e,-i*h,i*o,-i*(-h*n+o*a)+a+t,0,0,1),this}scale(e,t){return this.premultiply(Vt.makeScale(e,t)),this}rotate(e){return this.premultiply(Vt.makeRotation(-e)),this}translate(e,t){return this.premultiply(Vt.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 Vt=new zt,Gt=(new zt).set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),jt=(new zt).set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function $t(){const e={enabled:!0,workingColorSpace:Xe,spaces:{},convert:function(e,t,s){return!1!==this.enabled&&t!==s&&t&&s?(this.spaces[t].transfer===Ke&&(e.r=Ht(e.r),e.g=Ht(e.g),e.b=Ht(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===Ke&&(e.r=qt(e.r),e.g=qt(e.g),e.b=qt(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===He?Ye: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 xt("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),e.workingToColorSpace(t,s)},toWorkingColorSpace:function(t,s){return xt("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({[Xe]:{primaries:t,whitePoint:i,transfer:Ye,toXYZ:Gt,fromXYZ:jt,luminanceCoefficients:s,workingColorSpaceConfig:{unpackColorSpace:qe},outputColorSpaceConfig:{drawingBufferColorSpace:qe}},[qe]:{primaries:t,whitePoint:i,transfer:Ke,toXYZ:Gt,fromXYZ:jt,luminanceCoefficients:s,outputColorSpaceConfig:{drawingBufferColorSpace:qe}}}),e}const Wt=$t();function Ht(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}function qt(e){return e<.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}let Xt;class Yt{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===Xt&&(Xt=mt("canvas")),Xt.width=e.width,Xt.height=e.height;const t=Xt.getContext("2d");e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),s=Xt}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=mt("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*Ht(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*Ht(t[e]/255)):t[e]=Ht(t[e]);return{data:t,width:e.width,height:e.height}}return bt("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let Kt=0;class Qt{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:Kt++}),this.uuid=Et(),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.displayWidth,t.displayHeight,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(Zt(i[t].image)):e.push(Zt(i[t]))}else e=Zt(i);s.url=e}return t||(e.images[this.uuid]=s),s}}function Zt(e){return"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?Yt.getDataURL(e):e.data?{data:Array.from(e.data),width:e.width,height:e.height,type:e.data.constructor.name}:(bt("Texture: Unable to serialize Texture."),{})}let Jt=0;const es=new Ot;class ts extends St{constructor(e=ts.DEFAULT_IMAGE,t=ts.DEFAULT_MAPPING,s=1001,i=1001,r=1006,n=1008,a=1023,o=1009,h=ts.DEFAULT_ANISOTROPY,l=""){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:Jt++}),this.uuid=Et(),this.name="",this.source=new Qt(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=s,this.wrapT=i,this.magFilter=r,this.minFilter=n,this.anisotropy=h,this.format=a,this.internalFormat=null,this.type=o,this.offset=new Dt(0,0),this.repeat=new Dt(1,1),this.center=new Dt(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new zt,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=l,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,this.normalized=!1}get width(){return this.source.getSize(es).x}get height(){return this.source.getSize(es).y}get depth(){return this.source.getSize(es).z}get image(){return this.source.data}set image(e){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.normalized=e.normalized,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){bt(`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:bt(`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,normalized:this.normalized,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 L:e.x=e.x-Math.floor(e.x);break;case D:e.x=e.x<0?0:1;break;case I: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 L:e.y=e.y-Math.floor(e.y);break;case D:e.y=e.y<0?0:1;break;case I: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++}}ts.DEFAULT_IMAGE=null,ts.DEFAULT_MAPPING=300,ts.DEFAULT_ANISOTROPY=1;class ss{static{ss.prototype.isVector4=!0}constructor(e=0,t=0,s=0,i=1){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,a=.1,o=e.elements,h=o[0],l=o[4],u=o[8],c=o[1],d=o[5],p=o[9],m=o[2],g=o[6],f=o[10];if(Math.abs(l-c)<n&&Math.abs(u-m)<n&&Math.abs(p-g)<n){if(Math.abs(l+c)<a&&Math.abs(u+m)<a&&Math.abs(p+g)<a&&Math.abs(h+d+f-3)<a)return this.set(1,0,0,0),this;t=Math.PI;const e=(h+1)/2,o=(d+1)/2,y=(f+1)/2,b=(l+c)/4,_=(u+m)/4,x=(p+g)/4;return e>o&&e>y?e<n?(s=0,i=.707106781,r=.707106781):(s=Math.sqrt(e),i=b/s,r=_/s):o>y?o<n?(s=.707106781,i=0,r=.707106781):(i=Math.sqrt(o),s=b/i,r=x/i):y<n?(s=.707106781,i=.707106781,r=0):(r=Math.sqrt(y),s=_/r,i=x/r),this.set(s,i,r,t),this}let y=Math.sqrt((g-p)*(g-p)+(u-m)*(u-m)+(c-l)*(c-l));return Math.abs(y)<.001&&(y=1),this.x=(g-p)/y,this.y=(u-m)/y,this.z=(c-l)/y,this.w=Math.acos((h+d+f-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=Rt(this.x,e.x,t.x),this.y=Rt(this.y,e.y,t.y),this.z=Rt(this.z,e.z,t.z),this.w=Rt(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=Rt(this.x,e,t),this.y=Rt(this.y,e,t),this.z=Rt(this.z,e,t),this.w=Rt(this.w,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(Rt(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 is extends St{constructor(e=1,t=1,s={}){super(),s=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:z,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 ss(0,0,e,t),this.scissorTest=!1,this.viewport=new ss(0,0,e,t),this.textures=[];const i={width:e,height:t,depth:s.depth},r=new ts(i),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:z,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 Qt(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.multiview=e.multiview,this}dispose(){this.dispatchEvent({type:"dispose"})}}class rs extends ts{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=O,this.minFilter=O,this.wrapR=D,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class ns{static{ns.prototype.isMatrix4=!0}constructor(e,t,s,i,r,n,a,o,h,l,u,c,d,p,m,g){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,a,o,h,l,u,c,d,p,m,g)}set(e,t,s,i,r,n,a,o,h,l,u,c,d,p,m,g){const f=this.elements;return f[0]=e,f[4]=t,f[8]=s,f[12]=i,f[1]=r,f[5]=n,f[9]=a,f[13]=o,f[2]=h,f[6]=l,f[10]=u,f[14]=c,f[3]=d,f[7]=p,f[11]=m,f[15]=g,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 ns).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/as.setFromMatrixColumn(e,0).length(),r=1/as.setFromMatrixColumn(e,1).length(),n=1/as.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),a=Math.sin(s),o=Math.cos(i),h=Math.sin(i),l=Math.cos(r),u=Math.sin(r);if("XYZ"===e.order){const e=n*l,s=n*u,i=a*l,r=a*u;t[0]=o*l,t[4]=-o*u,t[8]=h,t[1]=s+i*h,t[5]=e-r*h,t[9]=-a*o,t[2]=r-e*h,t[6]=i+s*h,t[10]=n*o}else if("YXZ"===e.order){const e=o*l,s=o*u,i=h*l,r=h*u;t[0]=e+r*a,t[4]=i*a-s,t[8]=n*h,t[1]=n*u,t[5]=n*l,t[9]=-a,t[2]=s*a-i,t[6]=r+e*a,t[10]=n*o}else if("ZXY"===e.order){const e=o*l,s=o*u,i=h*l,r=h*u;t[0]=e-r*a,t[4]=-n*u,t[8]=i+s*a,t[1]=s+i*a,t[5]=n*l,t[9]=r-e*a,t[2]=-n*h,t[6]=a,t[10]=n*o}else if("ZYX"===e.order){const e=n*l,s=n*u,i=a*l,r=a*u;t[0]=o*l,t[4]=i*h-s,t[8]=e*h+r,t[1]=o*u,t[5]=r*h+e,t[9]=s*h-i,t[2]=-h,t[6]=a*o,t[10]=n*o}else if("YZX"===e.order){const e=n*o,s=n*h,i=a*o,r=a*h;t[0]=o*l,t[4]=r-e*u,t[8]=i*u+s,t[1]=u,t[5]=n*l,t[9]=-a*l,t[2]=-h*l,t[6]=s*u+i,t[10]=e-r*u}else if("XZY"===e.order){const e=n*o,s=n*h,i=a*o,r=a*h;t[0]=o*l,t[4]=-u,t[8]=h*l,t[1]=e*u+r,t[5]=n*l,t[9]=s*u-i,t[2]=i*u-s,t[6]=a*l,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(hs,e,ls)}lookAt(e,t,s){const i=this.elements;return ds.subVectors(e,t),0===ds.lengthSq()&&(ds.z=1),ds.normalize(),us.crossVectors(s,ds),0===us.lengthSq()&&(1===Math.abs(s.z)?ds.x+=1e-4:ds.z+=1e-4,ds.normalize(),us.crossVectors(s,ds)),us.normalize(),cs.crossVectors(ds,us),i[0]=us.x,i[4]=cs.x,i[8]=ds.x,i[1]=us.y,i[5]=cs.y,i[9]=ds.y,i[2]=us.z,i[6]=cs.z,i[10]=ds.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],a=s[4],o=s[8],h=s[12],l=s[1],u=s[5],c=s[9],d=s[13],p=s[2],m=s[6],g=s[10],f=s[14],y=s[3],b=s[7],_=s[11],x=s[15],v=i[0],T=i[4],S=i[8],w=i[12],M=i[1],N=i[5],A=i[9],E=i[13],R=i[2],C=i[6],P=i[10],B=i[14],F=i[3],L=i[7],D=i[11],I=i[15];return r[0]=n*v+a*M+o*R+h*F,r[4]=n*T+a*N+o*C+h*L,r[8]=n*S+a*A+o*P+h*D,r[12]=n*w+a*E+o*B+h*I,r[1]=l*v+u*M+c*R+d*F,r[5]=l*T+u*N+c*C+d*L,r[9]=l*S+u*A+c*P+d*D,r[13]=l*w+u*E+c*B+d*I,r[2]=p*v+m*M+g*R+f*F,r[6]=p*T+m*N+g*C+f*L,r[10]=p*S+m*A+g*P+f*D,r[14]=p*w+m*E+g*B+f*I,r[3]=y*v+b*M+_*R+x*F,r[7]=y*T+b*N+_*C+x*L,r[11]=y*S+b*A+_*P+x*D,r[15]=y*w+b*E+_*B+x*I,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],a=e[5],o=e[9],h=e[13],l=e[2],u=e[6],c=e[10],d=e[14],p=e[3],m=e[7],g=e[11],f=e[15],y=o*d-h*c,b=a*d-h*u,_=a*c-o*u,x=n*d-h*l,v=n*c-o*l,T=n*u-a*l;return t*(m*y-g*b+f*_)-s*(p*y-g*x+f*v)+i*(p*b-m*x+f*T)-r*(p*_-m*v+g*T)}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],a=e[5],o=e[6],h=e[7],l=e[8],u=e[9],c=e[10],d=e[11],p=e[12],m=e[13],g=e[14],f=e[15],y=t*a-s*n,b=t*o-i*n,_=t*h-r*n,x=s*o-i*a,v=s*h-r*a,T=i*h-r*o,S=l*m-u*p,w=l*g-c*p,M=l*f-d*p,N=u*g-c*m,A=u*f-d*m,E=c*f-d*g,R=y*E-b*A+_*N+x*M-v*w+T*S;if(0===R)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const C=1/R;return e[0]=(a*E-o*A+h*N)*C,e[1]=(i*A-s*E-r*N)*C,e[2]=(m*T-g*v+f*x)*C,e[3]=(c*v-u*T-d*x)*C,e[4]=(o*M-n*E-h*w)*C,e[5]=(t*E-i*M+r*w)*C,e[6]=(g*_-p*T-f*b)*C,e[7]=(l*T-c*_+d*b)*C,e[8]=(n*A-a*M+h*S)*C,e[9]=(s*M-t*A-r*S)*C,e[10]=(p*v-m*_+f*y)*C,e[11]=(u*_-l*v-d*y)*C,e[12]=(a*w-n*N-o*S)*C,e[13]=(t*N-s*w+i*S)*C,e[14]=(m*b-p*x-g*y)*C,e[15]=(l*x-u*b+c*y)*C,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,a=e.y,o=e.z,h=r*n,l=r*a;return this.set(h*n+s,h*a-i*o,h*o+i*a,0,h*a+i*o,l*a+s,l*o-i*n,0,h*o-i*a,l*o+i*n,r*o*o+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,a=t._z,o=t._w,h=r+r,l=n+n,u=a+a,c=r*h,d=r*l,p=r*u,m=n*l,g=n*u,f=a*u,y=o*h,b=o*l,_=o*u,x=s.x,v=s.y,T=s.z;return i[0]=(1-(m+f))*x,i[1]=(d+_)*x,i[2]=(p-b)*x,i[3]=0,i[4]=(d-_)*v,i[5]=(1-(c+f))*v,i[6]=(g+y)*v,i[7]=0,i[8]=(p+b)*T,i[9]=(g-y)*T,i[10]=(1-(c+m))*T,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;e.x=i[12],e.y=i[13],e.z=i[14];const r=this.determinant();if(0===r)return s.set(1,1,1),t.identity(),this;let n=as.set(i[0],i[1],i[2]).length();const a=as.set(i[4],i[5],i[6]).length(),o=as.set(i[8],i[9],i[10]).length();r<0&&(n=-n),os.copy(this);const h=1/n,l=1/a,u=1/o;return os.elements[0]*=h,os.elements[1]*=h,os.elements[2]*=h,os.elements[4]*=l,os.elements[5]*=l,os.elements[6]*=l,os.elements[8]*=u,os.elements[9]*=u,os.elements[10]*=u,t.setFromRotationMatrix(os),s.x=n,s.y=a,s.z=o,this}makePerspective(e,t,s,i,r,n,a=2e3,o=!1){const h=this.elements,l=2*r/(t-e),u=2*r/(s-i),c=(t+e)/(t-e),d=(s+i)/(s-i);let p,m;if(o)p=r/(n-r),m=n*r/(n-r);else if(a===ht)p=-(n+r)/(n-r),m=-2*n*r/(n-r);else{if(a!==lt)throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);p=-n/(n-r),m=-n*r/(n-r)}return h[0]=l,h[4]=0,h[8]=c,h[12]=0,h[1]=0,h[5]=u,h[9]=d,h[13]=0,h[2]=0,h[6]=0,h[10]=p,h[14]=m,h[3]=0,h[7]=0,h[11]=-1,h[15]=0,this}makeOrthographic(e,t,s,i,r,n,a=2e3,o=!1){const h=this.elements,l=2/(t-e),u=2/(s-i),c=-(t+e)/(t-e),d=-(s+i)/(s-i);let p,m;if(o)p=1/(n-r),m=n/(n-r);else if(a===ht)p=-2/(n-r),m=-(n+r)/(n-r);else{if(a!==lt)throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);p=-1/(n-r),m=-r/(n-r)}return h[0]=l,h[4]=0,h[8]=0,h[12]=c,h[1]=0,h[5]=u,h[9]=0,h[13]=d,h[2]=0,h[6]=0,h[10]=p,h[14]=m,h[3]=0,h[7]=0,h[11]=0,h[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 as=new Ot,os=new ns,hs=new Ot(0,0,0),ls=new Ot(1,1,1),us=new Ot,cs=new Ot,ds=new Ot,ps=new ns,ms=new It;class gs{constructor(e=0,t=0,s=0,i=gs.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],a=i[8],o=i[1],h=i[5],l=i[9],u=i[2],c=i[6],d=i[10];switch(t){case"XYZ":this._y=Math.asin(Rt(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-l,d),this._z=Math.atan2(-n,r)):(this._x=Math.atan2(c,h),this._z=0);break;case"YXZ":this._x=Math.asin(-Rt(l,-1,1)),Math.abs(l)<.9999999?(this._y=Math.atan2(a,d),this._z=Math.atan2(o,h)):(this._y=Math.atan2(-u,r),this._z=0);break;case"ZXY":this._x=Math.asin(Rt(c,-1,1)),Math.abs(c)<.9999999?(this._y=Math.atan2(-u,d),this._z=Math.atan2(-n,h)):(this._y=0,this._z=Math.atan2(o,r));break;case"ZYX":this._y=Math.asin(-Rt(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(c,d),this._z=Math.atan2(o,r)):(this._x=0,this._z=Math.atan2(-n,h));break;case"YZX":this._z=Math.asin(Rt(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-l,h),this._y=Math.atan2(-u,r)):(this._x=0,this._y=Math.atan2(a,d));break;case"XZY":this._z=Math.asin(-Rt(n,-1,1)),Math.abs(n)<.9999999?(this._x=Math.atan2(c,h),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-l,d),this._y=0);break;default:bt("Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,!0===s&&this._onChangeCallback(),this}setFromQuaternion(e,t,s){return ps.makeRotationFromQuaternion(e),this.setFromRotationMatrix(ps,t,s)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return ms.setFromEuler(this),this.setFromQuaternion(ms,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}}gs.DEFAULT_ORDER="XYZ";class fs{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 ys=0;const bs=new Ot,_s=new It,xs=new ns,vs=new Ot,Ts=new Ot,Ss=new Ot,ws=new It,Ms=new Ot(1,0,0),Ns=new Ot(0,1,0),As=new Ot(0,0,1),Es={type:"added"},Rs={type:"removed"},Cs={type:"childadded",child:null},Ps={type:"childremoved",child:null};class Bs extends St{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:ys++}),this.uuid=Et(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Bs.DEFAULT_UP.clone();const e=new Ot,t=new gs,s=new It,i=new Ot(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 ns},normalMatrix:{value:new zt}}),this.matrix=new ns,this.matrixWorld=new ns,this.matrixAutoUpdate=Bs.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=Bs.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new fs,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.static=!1,this.userData={},this.pivot=null}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 _s.setFromAxisAngle(e,t),this.quaternion.multiply(_s),this}rotateOnWorldAxis(e,t){return _s.setFromAxisAngle(e,t),this.quaternion.premultiply(_s),this}rotateX(e){return this.rotateOnAxis(Ms,e)}rotateY(e){return this.rotateOnAxis(Ns,e)}rotateZ(e){return this.rotateOnAxis(As,e)}translateOnAxis(e,t){return bs.copy(e).applyQuaternion(this.quaternion),this.position.add(bs.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(Ms,e)}translateY(e){return this.translateOnAxis(Ns,e)}translateZ(e){return this.translateOnAxis(As,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(xs.copy(this.matrixWorld).invert())}lookAt(e,t,s){e.isVector3?vs.copy(e):vs.set(e,t,s);const i=this.parent;this.updateWorldMatrix(!0,!1),Ts.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?xs.lookAt(Ts,vs,this.up):xs.lookAt(vs,Ts,this.up),this.quaternion.setFromRotationMatrix(xs),i&&(xs.extractRotation(i.matrixWorld),_s.setFromRotationMatrix(xs),this.quaternion.premultiply(_s.invert()))}add(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return e===this?(_t("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(Es),Cs.child=e,this.dispatchEvent(Cs),Cs.child=null):_t("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(Rs),Ps.child=e,this.dispatchEvent(Ps),Ps.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),xs.copy(this.matrixWorld).invert(),null!==e.parent&&(e.parent.updateWorldMatrix(!0,!1),xs.multiply(e.parent.matrixWorld)),e.applyMatrix4(xs),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(Es),Cs.child=e,this.dispatchEvent(Cs),Cs.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(Ts,e,Ss),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Ts,ws,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);const e=this.pivot;if(null!==e){const t=e.x,s=e.y,i=e.z,r=this.matrix.elements;r[12]+=t-r[0]*t-r[4]*s-r[8]*i,r[13]+=s-r[1]*t-r[5]*s-r[9]*i,r[14]+=i-r[2]*t-r[6]*s-r[10]*i}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),!1!==this.static&&(i.static=this.static),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(),null!==this.pivot&&(i.pivot=this.pivot.toArray()),!1===this.matrixAutoUpdate&&(i.matrixAutoUpdate=!1),void 0!==this.morphTargetDictionary&&(i.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),void 0!==this.morphTargetInfluences&&(i.morphTargetInfluences=this.morphTargetInfluences.slice()),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),a=n(e.images),o=n(e.shapes),h=n(e.skeletons),l=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),a.length>0&&(s.images=a),o.length>0&&(s.shapes=o),h.length>0&&(s.skeletons=h),l.length>0&&(s.animations=l),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.pivot=null!==e.pivot?e.pivot.clone():null,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.static=e.static,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}}Bs.DEFAULT_UP=new Ot(0,1,0),Bs.DEFAULT_MATRIX_AUTO_UPDATE=!0,Bs.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;let Fs=class extends Bs{constructor(){super(),this.isGroup=!0,this.type="Group"}};const Ls={type:"move"};class Ds{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return null===this._hand&&(this._hand=new Fs,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 Fs,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new Ot,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new Ot),this._targetRay}getGripSpace(){return null===this._grip&&(this._grip=new Fs,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new Ot,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new Ot,this._grip.eventsEnabled=!1),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 a=this._targetRay,o=this._grip,h=this._hand;if(e&&"visible-blurred"!==t.session.visibilityState){if(h&&e.hand){n=!0;for(const i of e.hand.values()){const e=t.getJointPose(i,s),r=this._getHandJoint(h,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=h.joints["index-finger-tip"],r=h.joints["thumb-tip"],a=i.position.distanceTo(r.position),o=.02,l=.005;h.inputState.pinching&&a>o+l?(h.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!h.inputState.pinching&&a<=o-l&&(h.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else null!==o&&e.gripSpace&&(r=t.getPose(e.gripSpace,s),null!==r&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1,o.eventsEnabled&&o.dispatchEvent({type:"gripUpdated",data:e,target:this})));null!==a&&(i=t.getPose(e.targetRaySpace,s),null===i&&null!==r&&(i=r),null!==i&&(a.matrix.fromArray(i.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,i.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(i.linearVelocity)):a.hasLinearVelocity=!1,i.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(i.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(Ls)))}return null!==a&&(a.visible=null!==i),null!==o&&(o.visible=null!==r),null!==h&&(h.visible=null!==n),this}_getHandJoint(e,t){if(void 0===e.joints[t.jointName]){const s=new Fs;s.matrixAutoUpdate=!1,s.visible=!1,e.joints[t.jointName]=s,e.add(s)}return e.joints[t.jointName]}}const Is={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},Os={h:0,s:0,l:0},Us={h:0,s:0,l:0};function ks(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 zs{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=qe){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(255&e)/255,Wt.colorSpaceToWorking(this,t),this}setRGB(e,t,s,i=Wt.workingColorSpace){return this.r=e,this.g=t,this.b=s,Wt.colorSpaceToWorking(this,i),this}setHSL(e,t,s,i=Wt.workingColorSpace){if(e=Ct(e,1),t=Rt(t,0,1),s=Rt(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=ks(r,i,e+1/3),this.g=ks(r,i,e),this.b=ks(r,i,e-1/3)}return Wt.colorSpaceToWorking(this,i),this}setStyle(e,t=qe){function s(t){void 0!==t&&parseFloat(t)<1&&bt("Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const n=i[1],a=i[2];switch(n){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))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(a))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(a))return s(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:bt("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);bt("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=qe){const s=Is[e.toLowerCase()];return void 0!==s?this.setHex(s,t):bt("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=Ht(e.r),this.g=Ht(e.g),this.b=Ht(e.b),this}copyLinearToSRGB(e){return this.r=qt(e.r),this.g=qt(e.g),this.b=qt(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=qe){return Wt.workingToColorSpace(Vs.copy(this),e),65536*Math.round(Rt(255*Vs.r,0,255))+256*Math.round(Rt(255*Vs.g,0,255))+Math.round(Rt(255*Vs.b,0,255))}getHexString(e=qe){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Wt.workingColorSpace){Wt.workingToColorSpace(Vs.copy(this),t);const s=Vs.r,i=Vs.g,r=Vs.b,n=Math.max(s,i,r),a=Math.min(s,i,r);let o,h;const l=(a+n)/2;if(a===n)o=0,h=0;else{const e=n-a;switch(h=l<=.5?e/(n+a):e/(2-n-a),n){case s:o=(i-r)/e+(i<r?6:0);break;case i:o=(r-s)/e+2;break;case r:o=(s-i)/e+4}o/=6}return e.h=o,e.s=h,e.l=l,e}getRGB(e,t=Wt.workingColorSpace){return Wt.workingToColorSpace(Vs.copy(this),t),e.r=Vs.r,e.g=Vs.g,e.b=Vs.b,e}getStyle(e=qe){Wt.workingToColorSpace(Vs.copy(this),e);const t=Vs.r,s=Vs.g,i=Vs.b;return e!==qe?`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(Os),this.setHSL(Os.h+e,Os.s+t,Os.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(Os),e.getHSL(Us);const s=Pt(Os.h,Us.h,t),i=Pt(Os.s,Us.s,t),r=Pt(Os.l,Us.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 Vs=new zs;zs.NAMES=Is;class Gs extends Bs{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 gs,this.environmentIntensity=1,this.environmentRotation=new gs,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}}const js=new Ot,$s=new Ot,Ws=new Ot,Hs=new Ot,qs=new Ot,Xs=new Ot,Ys=new Ot,Ks=new Ot,Qs=new Ot,Zs=new Ot,Js=new ss,ei=new ss,ti=new ss;class si{constructor(e=new Ot,t=new Ot,s=new Ot){this.a=e,this.b=t,this.c=s}static getNormal(e,t,s,i){i.subVectors(s,t),js.subVectors(e,t),i.cross(js);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){js.subVectors(i,t),$s.subVectors(s,t),Ws.subVectors(e,t);const n=js.dot(js),a=js.dot($s),o=js.dot(Ws),h=$s.dot($s),l=$s.dot(Ws),u=n*h-a*a;if(0===u)return r.set(0,0,0),null;const c=1/u,d=(h*o-a*l)*c,p=(n*l-a*o)*c;return r.set(1-d-p,p,d)}static containsPoint(e,t,s,i){return null!==this.getBarycoord(e,t,s,i,Hs)&&(Hs.x>=0&&Hs.y>=0&&Hs.x+Hs.y<=1)}static getInterpolation(e,t,s,i,r,n,a,o){return null===this.getBarycoord(e,t,s,i,Hs)?(o.x=0,o.y=0,"z"in o&&(o.z=0),"w"in o&&(o.w=0),null):(o.setScalar(0),o.addScaledVector(r,Hs.x),o.addScaledVector(n,Hs.y),o.addScaledVector(a,Hs.z),o)}static getInterpolatedAttribute(e,t,s,i,r,n){return Js.setScalar(0),ei.setScalar(0),ti.setScalar(0),Js.fromBufferAttribute(e,t),ei.fromBufferAttribute(e,s),ti.fromBufferAttribute(e,i),n.setScalar(0),n.addScaledVector(Js,r.x),n.addScaledVector(ei,r.y),n.addScaledVector(ti,r.z),n}static isFrontFacing(e,t,s,i){return js.subVectors(s,t),$s.subVectors(e,t),js.cross($s).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 js.subVectors(this.c,this.b),$s.subVectors(this.a,this.b),.5*js.cross($s).length()}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return si.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return si.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,s,i,r){return si.getInterpolation(e,this.a,this.b,this.c,t,s,i,r)}containsPoint(e){return si.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return si.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,a;qs.subVectors(i,s),Xs.subVectors(r,s),Ks.subVectors(e,s);const o=qs.dot(Ks),h=Xs.dot(Ks);if(o<=0&&h<=0)return t.copy(s);Qs.subVectors(e,i);const l=qs.dot(Qs),u=Xs.dot(Qs);if(l>=0&&u<=l)return t.copy(i);const c=o*u-l*h;if(c<=0&&o>=0&&l<=0)return n=o/(o-l),t.copy(s).addScaledVector(qs,n);Zs.subVectors(e,r);const d=qs.dot(Zs),p=Xs.dot(Zs);if(p>=0&&d<=p)return t.copy(r);const m=d*h-o*p;if(m<=0&&h>=0&&p<=0)return a=h/(h-p),t.copy(s).addScaledVector(Xs,a);const g=l*p-d*u;if(g<=0&&u-l>=0&&d-p>=0)return Ys.subVectors(r,i),a=(u-l)/(u-l+(d-p)),t.copy(i).addScaledVector(Ys,a);const f=1/(g+m+c);return n=m*f,a=c*f,t.copy(s).addScaledVector(qs,n).addScaledVector(Xs,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}class ii{constructor(e=new Ot(1/0,1/0,1/0),t=new Ot(-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(ni.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,s=e.count;t<s;t++)this.expandByPoint(ni.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=ni.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,ni):ni.fromBufferAttribute(i,t),ni.applyMatrix4(e.matrixWorld),this.expandByPoint(ni);else void 0!==e.boundingBox?(null===e.boundingBox&&e.computeBoundingBox(),ai.copy(e.boundingBox)):(null===s.boundingBox&&s.computeBoundingBox(),ai.copy(s.boundingBox)),ai.applyMatrix4(e.matrixWorld),this.union(ai)}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,ni),ni.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(pi),mi.subVectors(this.max,pi),oi.subVectors(e.a,pi),hi.subVectors(e.b,pi),li.subVectors(e.c,pi),ui.subVectors(hi,oi),ci.subVectors(li,hi),di.subVectors(oi,li);let t=[0,-ui.z,ui.y,0,-ci.z,ci.y,0,-di.z,di.y,ui.z,0,-ui.x,ci.z,0,-ci.x,di.z,0,-di.x,-ui.y,ui.x,0,-ci.y,ci.x,0,-di.y,di.x,0];return!!yi(t,oi,hi,li,mi)&&(t=[1,0,0,0,1,0,0,0,1],!!yi(t,oi,hi,li,mi)&&(gi.crossVectors(ui,ci),t=[gi.x,gi.y,gi.z],yi(t,oi,hi,li,mi)))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,ni).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=.5*this.getSize(ni).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()||(ri[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),ri[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),ri[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),ri[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),ri[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),ri[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),ri[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),ri[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(ri)),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 ri=[new Ot,new Ot,new Ot,new Ot,new Ot,new Ot,new Ot,new Ot],ni=new Ot,ai=new ii,oi=new Ot,hi=new Ot,li=new Ot,ui=new Ot,ci=new Ot,di=new Ot,pi=new Ot,mi=new Ot,gi=new Ot,fi=new Ot;function yi(e,t,s,i,r){for(let n=0,a=e.length-3;n<=a;n+=3){fi.fromArray(e,n);const a=r.x*Math.abs(fi.x)+r.y*Math.abs(fi.y)+r.z*Math.abs(fi.z),o=t.dot(fi),h=s.dot(fi),l=i.dot(fi);if(Math.max(-Math.max(o,h,l),Math.min(o,h,l))>a)return!1}return!0}const bi=_i();function _i(){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),a=new Uint32Array(64),o=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)a[e]=e<<23;a[31]=1199570944,a[32]=2147483648;for(let e=33;e<63;++e)a[e]=2147483648+(e-32<<23);a[63]=3347054592;for(let e=1;e<64;++e)32!==e&&(o[e]=1024);return{floatView:t,uint32View:s,baseTable:i,shiftTable:r,mantissaTable:n,exponentTable:a,offsetTable:o}}function xi(e){Math.abs(e)>65504&&bt("DataUtils.toHalfFloat(): Value out of range."),e=Rt(e,-65504,65504),bi.floatView[0]=e;const t=bi.uint32View[0],s=t>>23&511;return bi.baseTable[s]+((8388607&t)>>bi.shiftTable[s])}function vi(e){const t=e>>10;return bi.uint32View[0]=bi.mantissaTable[bi.offsetTable[t]+(1023&e)]+bi.exponentTable[t],bi.floatView[0]}const Ti=new Ot,Si=new Dt;let wi=0;class Mi extends St{constructor(e,t,s=!1){if(super(),Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:wi++}),this.name="",this.array=e,this.itemSize=t,this.count=void 0!==e?e.length/t:0,this.normalized=s,this.usage=at,this.updateRanges=[],this.gpuType=Y,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++)Si.fromBufferAttribute(this,t),Si.applyMatrix3(e),this.setXY(t,Si.x,Si.y);else if(3===this.itemSize)for(let t=0,s=this.count;t<s;t++)Ti.fromBufferAttribute(this,t),Ti.applyMatrix3(e),this.setXYZ(t,Ti.x,Ti.y,Ti.z);return this}applyMatrix4(e){for(let t=0,s=this.count;t<s;t++)Ti.fromBufferAttribute(this,t),Ti.applyMatrix4(e),this.setXYZ(t,Ti.x,Ti.y,Ti.z);return this}applyNormalMatrix(e){for(let t=0,s=this.count;t<s;t++)Ti.fromBufferAttribute(this,t),Ti.applyNormalMatrix(e),this.setXYZ(t,Ti.x,Ti.y,Ti.z);return this}transformDirection(e){for(let t=0,s=this.count;t<s;t++)Ti.fromBufferAttribute(this,t),Ti.transformDirection(e),this.setXYZ(t,Ti.x,Ti.y,Ti.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=Bt(s,this.array)),s}setComponent(e,t,s){return this.normalized&&(s=Ft(s,this.array)),this.array[e*this.itemSize+t]=s,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=Bt(t,this.array)),t}setX(e,t){return this.normalized&&(t=Ft(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=Bt(t,this.array)),t}setY(e,t){return this.normalized&&(t=Ft(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=Bt(t,this.array)),t}setZ(e,t){return this.normalized&&(t=Ft(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=Bt(t,this.array)),t}setW(e,t){return this.normalized&&(t=Ft(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,s){return e*=this.itemSize,this.normalized&&(t=Ft(t,this.array),s=Ft(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=Ft(t,this.array),s=Ft(s,this.array),i=Ft(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=Ft(t,this.array),s=Ft(s,this.array),i=Ft(i,this.array),r=Ft(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!==at&&(e.usage=this.usage),e}dispose(){this.dispatchEvent({type:"dispose"})}}class Ni extends Mi{constructor(e,t,s){super(new Uint16Array(e),t,s)}}class Ai extends Mi{constructor(e,t,s){super(new Uint32Array(e),t,s)}}class Ei extends Mi{constructor(e,t,s){super(new Uint16Array(e),t,s),this.isFloat16BufferAttribute=!0}getX(e){let t=vi(this.array[e*this.itemSize]);return this.normalized&&(t=Bt(t,this.array)),t}setX(e,t){return this.normalized&&(t=Ft(t,this.array)),this.array[e*this.itemSize]=xi(t),this}getY(e){let t=vi(this.array[e*this.itemSize+1]);return this.normalized&&(t=Bt(t,this.array)),t}setY(e,t){return this.normalized&&(t=Ft(t,this.array)),this.array[e*this.itemSize+1]=xi(t),this}getZ(e){let t=vi(this.array[e*this.itemSize+2]);return this.normalized&&(t=Bt(t,this.array)),t}setZ(e,t){return this.normalized&&(t=Ft(t,this.array)),this.array[e*this.itemSize+2]=xi(t),this}getW(e){let t=vi(this.array[e*this.itemSize+3]);return this.normalized&&(t=Bt(t,this.array)),t}setW(e,t){return this.normalized&&(t=Ft(t,this.array)),this.array[e*this.itemSize+3]=xi(t),this}setXY(e,t,s){return e*=this.itemSize,this.normalized&&(t=Ft(t,this.array),s=Ft(s,this.array)),this.array[e+0]=xi(t),this.array[e+1]=xi(s),this}setXYZ(e,t,s,i){return e*=this.itemSize,this.normalized&&(t=Ft(t,this.array),s=Ft(s,this.array),i=Ft(i,this.array)),this.array[e+0]=xi(t),this.array[e+1]=xi(s),this.array[e+2]=xi(i),this}setXYZW(e,t,s,i,r){return e*=this.itemSize,this.normalized&&(t=Ft(t,this.array),s=Ft(s,this.array),i=Ft(i,this.array),r=Ft(r,this.array)),this.array[e+0]=xi(t),this.array[e+1]=xi(s),this.array[e+2]=xi(i),this.array[e+3]=xi(r),this}}class Ri extends Mi{constructor(e,t,s){super(new Float32Array(e),t,s)}}const Ci=new ii,Pi=new Ot,Bi=new Ot;class Fi{constructor(e=new Ot,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):Ci.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;Pi.subVectors(e,this.center);const t=Pi.lengthSq();if(t>this.radius*this.radius){const e=Math.sqrt(t),s=.5*(e-this.radius);this.center.addScaledVector(Pi,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):(Bi.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Pi.copy(e.center).add(Bi)),this.expandByPoint(Pi.copy(e.center).sub(Bi))),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}}let Li=0;const Di=new ns,Ii=new Bs,Oi=new Ot,Ui=new ii,ki=new ii,zi=new Ot;class Vi extends St{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:Li++}),this.uuid=Et(),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(function(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}(e)?Ai:Ni)(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 zt).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 Di.makeRotationFromQuaternion(e),this.applyMatrix4(Di),this}rotateX(e){return Di.makeRotationX(e),this.applyMatrix4(Di),this}rotateY(e){return Di.makeRotationY(e),this.applyMatrix4(Di),this}rotateZ(e){return Di.makeRotationZ(e),this.applyMatrix4(Di),this}translate(e,t,s){return Di.makeTranslation(e,t,s),this.applyMatrix4(Di),this}scale(e,t,s){return Di.makeScale(e,t,s),this.applyMatrix4(Di),this}lookAt(e){return Ii.lookAt(e),Ii.updateMatrix(),this.applyMatrix4(Ii.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Oi).negate(),this.translate(Oi.x,Oi.y,Oi.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 Ri(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&&bt("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 ii);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return _t("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),void this.boundingBox.set(new Ot(-1/0,-1/0,-1/0),new Ot(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];Ui.setFromBufferAttribute(s),this.morphTargetsRelative?(zi.addVectors(this.boundingBox.min,Ui.min),this.boundingBox.expandByPoint(zi),zi.addVectors(this.boundingBox.max,Ui.max),this.boundingBox.expandByPoint(zi)):(this.boundingBox.expandByPoint(Ui.min),this.boundingBox.expandByPoint(Ui.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&_t('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 Fi);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return _t("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),void this.boundingSphere.set(new Ot,1/0);if(e){const s=this.boundingSphere.center;if(Ui.setFromBufferAttribute(e),t)for(let e=0,s=t.length;e<s;e++){const s=t[e];ki.setFromBufferAttribute(s),this.morphTargetsRelative?(zi.addVectors(Ui.min,ki.min),Ui.expandByPoint(zi),zi.addVectors(Ui.max,ki.max),Ui.expandByPoint(zi)):(Ui.expandByPoint(ki.min),Ui.expandByPoint(ki.max))}Ui.getCenter(s);let i=0;for(let t=0,r=e.count;t<r;t++)zi.fromBufferAttribute(e,t),i=Math.max(i,s.distanceToSquared(zi));if(t)for(let r=0,n=t.length;r<n;r++){const n=t[r],a=this.morphTargetsRelative;for(let t=0,r=n.count;t<r;t++)zi.fromBufferAttribute(n,t),a&&(Oi.fromBufferAttribute(e,t),zi.add(Oi)),i=Math.max(i,s.distanceToSquared(zi))}this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius)&&_t('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 _t("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 Mi(new Float32Array(4*s.count),4));const n=this.getAttribute("tangent"),a=[],o=[];for(let e=0;e<s.count;e++)a[e]=new Ot,o[e]=new Ot;const h=new Ot,l=new Ot,u=new Ot,c=new Dt,d=new Dt,p=new Dt,m=new Ot,g=new Ot;function f(e,t,i){h.fromBufferAttribute(s,e),l.fromBufferAttribute(s,t),u.fromBufferAttribute(s,i),c.fromBufferAttribute(r,e),d.fromBufferAttribute(r,t),p.fromBufferAttribute(r,i),l.sub(h),u.sub(h),d.sub(c),p.sub(c);const n=1/(d.x*p.y-p.x*d.y);isFinite(n)&&(m.copy(l).multiplyScalar(p.y).addScaledVector(u,-d.y).multiplyScalar(n),g.copy(u).multiplyScalar(d.x).addScaledVector(l,-p.x).multiplyScalar(n),a[e].add(m),a[t].add(m),a[i].add(m),o[e].add(g),o[t].add(g),o[i].add(g))}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)f(e.getX(t+0),e.getX(t+1),e.getX(t+2))}const b=new Ot,_=new Ot,x=new Ot,v=new Ot;function T(e){x.fromBufferAttribute(i,e),v.copy(x);const t=a[e];b.copy(t),b.sub(x.multiplyScalar(x.dot(t))).normalize(),_.crossVectors(v,t);const s=_.dot(o[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)T(e.getX(t+0)),T(e.getX(t+1)),T(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 Mi(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 Ot,r=new Ot,n=new Ot,a=new Ot,o=new Ot,h=new Ot,l=new Ot,u=new Ot;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),l.subVectors(n,r),u.subVectors(i,r),l.cross(u),a.fromBufferAttribute(s,d),o.fromBufferAttribute(s,p),h.fromBufferAttribute(s,m),a.add(l),o.add(l),h.add(l),s.setXYZ(d,a.x,a.y,a.z),s.setXYZ(p,o.x,o.y,o.z),s.setXYZ(m,h.x,h.y,h.z)}else for(let e=0,a=t.count;e<a;e+=3)i.fromBufferAttribute(t,e+0),r.fromBufferAttribute(t,e+1),n.fromBufferAttribute(t,e+2),l.subVectors(n,r),u.subVectors(i,r),l.cross(u),s.setXYZ(e+0,l.x,l.y,l.z),s.setXYZ(e+1,l.x,l.y,l.z),s.setXYZ(e+2,l.x,l.y,l.z);this.normalizeNormals(),s.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let t=0,s=e.count;t<s;t++)zi.fromBufferAttribute(e,t),zi.normalize(),e.setXYZ(t,zi.x,zi.y,zi.z)}toNonIndexed(){function e(e,t){const s=e.array,i=e.itemSize,r=e.normalized,n=new s.constructor(t.length*i);let a=0,o=0;for(let r=0,h=t.length;r<h;r++){a=e.isInterleavedBufferAttribute?t[r]*e.data.stride+e.offset:t[r]*i;for(let e=0;e<i;e++)n[o++]=s[a++]}return new Mi(n,i,r)}if(null===this.index)return bt("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new Vi,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=[],a=r[i];for(let t=0,i=a.length;t<i;t++){const i=e(a[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 a=this.boundingSphere;return null!==a&&(e.data.boundingSphere=a.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 a=e.boundingBox;null!==a&&(this.boundingBox=a.clone());const o=e.boundingSphere;return null!==o&&(this.boundingSphere=o.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}}class Gi{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=void 0!==e?e.length/t:0,this.usage=at,this.updateRanges=[],this.version=0,this.uuid=Et()}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=Et()),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=Et()),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 ji=new Ot;class $i{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++)ji.fromBufferAttribute(this,t),ji.applyMatrix4(e),this.setXYZ(t,ji.x,ji.y,ji.z);return this}applyNormalMatrix(e){for(let t=0,s=this.count;t<s;t++)ji.fromBufferAttribute(this,t),ji.applyNormalMatrix(e),this.setXYZ(t,ji.x,ji.y,ji.z);return this}transformDirection(e){for(let t=0,s=this.count;t<s;t++)ji.fromBufferAttribute(this,t),ji.transformDirection(e),this.setXYZ(t,ji.x,ji.y,ji.z);return this}getComponent(e,t){let s=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(s=Bt(s,this.array)),s}setComponent(e,t,s){return this.normalized&&(s=Ft(s,this.array)),this.data.array[e*this.data.stride+this.offset+t]=s,this}setX(e,t){return this.normalized&&(t=Ft(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=Ft(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=Ft(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=Ft(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=Bt(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=Bt(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=Bt(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=Bt(t,this.array)),t}setXY(e,t,s){return e=e*this.data.stride+this.offset,this.normalized&&(t=Ft(t,this.array),s=Ft(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=Ft(t,this.array),s=Ft(s,this.array),i=Ft(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=Ft(t,this.array),s=Ft(s,this.array),i=Ft(i,this.array),r=Ft(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){ft("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 Mi(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 $i(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(void 0===e){ft("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}}}let Wi=0;class Hi extends St{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:Wi++}),this.uuid=Et(),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=y,this.blendDst=b,this.blendEquation=u,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new zs(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=Qe,this.stencilZFail=Qe,this.stencilZPass=Qe,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){bt(`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:bt(`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!==y&&(s.blendSrc=this.blendSrc),this.blendDst!==b&&(s.blendDst=this.blendDst),this.blendEquation!==u&&(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!==Qe&&(s.stencilFail=this.stencilFail),this.stencilZFail!==Qe&&(s.stencilZFail=this.stencilZFail),this.stencilZPass!==Qe&&(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 qi extends Hi{constructor(e){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new zs(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}}const Xi=new Ot,Yi=new Ot,Ki=new Ot,Qi=new Ot,Zi=new Ot,Ji=new Ot,er=new Ot;class tr{constructor(e=new Ot,t=new Ot(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,Xi)),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=Xi.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Xi.copy(this.origin).addScaledVector(this.direction,t),Xi.distanceToSquared(e))}distanceSqToSegment(e,t,s,i){Yi.copy(e).add(t).multiplyScalar(.5),Ki.copy(t).sub(e).normalize(),Qi.copy(this.origin).sub(Yi);const r=.5*e.distanceTo(t),n=-this.direction.dot(Ki),a=Qi.dot(this.direction),o=-Qi.dot(Ki),h=Qi.lengthSq(),l=Math.abs(1-n*n);let u,c,d,p;if(l>0)if(u=n*o-a,c=n*a-o,p=r*l,u>=0)if(c>=-p)if(c<=p){const e=1/l;u*=e,c*=e,d=u*(u+n*c+2*a)+c*(n*u+c+2*o)+h}else c=r,u=Math.max(0,-(n*c+a)),d=-u*u+c*(c+2*o)+h;else c=-r,u=Math.max(0,-(n*c+a)),d=-u*u+c*(c+2*o)+h;else c<=-p?(u=Math.max(0,-(-n*r+a)),c=u>0?-r:Math.min(Math.max(-r,-o),r),d=-u*u+c*(c+2*o)+h):c<=p?(u=0,c=Math.min(Math.max(-r,-o),r),d=c*(c+2*o)+h):(u=Math.max(0,-(n*r+a)),c=u>0?r:Math.min(Math.max(-r,-o),r),d=-u*u+c*(c+2*o)+h);else c=n>0?-r:r,u=Math.max(0,-(n*c+a)),d=-u*u+c*(c+2*o)+h;return s&&s.copy(this.origin).addScaledVector(this.direction,u),i&&i.copy(Yi).addScaledVector(Ki,c),d}intersectSphere(e,t){Xi.subVectors(e.center,this.origin);const s=Xi.dot(this.direction),i=Xi.dot(Xi)-s*s,r=e.radius*e.radius;if(i>r)return null;const n=Math.sqrt(r-i),a=s-n,o=s+n;return o<0?null:a<0?this.at(o,t):this.at(a,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,a,o;const h=1/this.direction.x,l=1/this.direction.y,u=1/this.direction.z,c=this.origin;return h>=0?(s=(e.min.x-c.x)*h,i=(e.max.x-c.x)*h):(s=(e.max.x-c.x)*h,i=(e.min.x-c.x)*h),l>=0?(r=(e.min.y-c.y)*l,n=(e.max.y-c.y)*l):(r=(e.max.y-c.y)*l,n=(e.min.y-c.y)*l),s>n||r>i?null:((r>s||isNaN(s))&&(s=r),(n<i||isNaN(i))&&(i=n),u>=0?(a=(e.min.z-c.z)*u,o=(e.max.z-c.z)*u):(a=(e.max.z-c.z)*u,o=(e.min.z-c.z)*u),s>o||a>i?null:((a>s||s!=s)&&(s=a),(o<i||i!=i)&&(i=o),i<0?null:this.at(s>=0?s:i,t)))}intersectsBox(e){return null!==this.intersectBox(e,Xi)}intersectTriangle(e,t,s,i,r){Zi.subVectors(t,e),Ji.subVectors(s,e),er.crossVectors(Zi,Ji);let n,a=this.direction.dot(er);if(a>0){if(i)return null;n=1}else{if(!(a<0))return null;n=-1,a=-a}Qi.subVectors(this.origin,e);const o=n*this.direction.dot(Ji.crossVectors(Qi,Ji));if(o<0)return null;const h=n*this.direction.dot(Zi.cross(Qi));if(h<0)return null;if(o+h>a)return null;const l=-n*Qi.dot(er);return l<0?null:this.at(l/a,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 sr extends Hi{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new zs(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 gs,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 ir=new ns,rr=new tr,nr=new Fi,ar=new Ot,or=new Ot,hr=new Ot,lr=new Ot,ur=new Ot,cr=new Ot,dr=new Ot,pr=new Ot;class mr extends Bs{constructor(e=new Vi,t=new sr){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 a=this.morphTargetInfluences;if(r&&a){cr.set(0,0,0);for(let s=0,i=r.length;s<i;s++){const i=a[s],o=r[s];0!==i&&(ur.fromBufferAttribute(o,e),n?cr.addScaledVector(ur,i):cr.addScaledVector(ur.sub(t),i))}t.add(cr)}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(),nr.copy(s.boundingSphere),nr.applyMatrix4(r),rr.copy(e.ray).recast(e.near),!1===nr.containsPoint(rr.origin)){if(null===rr.intersectSphere(nr,ar))return;if(rr.origin.distanceToSquared(ar)>(e.far-e.near)**2)return}ir.copy(r).invert(),rr.copy(e.ray).applyMatrix4(ir),null!==s.boundingBox&&!1===rr.intersectsBox(s.boundingBox)||this._computeIntersections(e,t,rr)}}_computeIntersections(e,t,s){let i;const r=this.geometry,n=this.material,a=r.index,o=r.attributes.position,h=r.attributes.uv,l=r.attributes.uv1,u=r.attributes.normal,c=r.groups,d=r.drawRange;if(null!==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=gr(this,p,e,s,h,l,u,a.getX(r),a.getX(r+1),a.getX(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=gr(this,n,e,s,h,l,u,a.getX(r),a.getX(r+1),a.getX(r+2)),i&&(i.faceIndex=Math.floor(r/3),t.push(i))}}else if(void 0!==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=gr(this,p,e,s,h,l,u,r,r+1,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=gr(this,n,e,s,h,l,u,r,r+1,r+2),i&&(i.faceIndex=Math.floor(r/3),t.push(i))}}}}function gr(e,t,s,i,r,n,a,o,h,l){e.getVertexPosition(o,or),e.getVertexPosition(h,hr),e.getVertexPosition(l,lr);const u=function(e,t,s,i,r,n,a,o){let h;if(h=1===t.side?i.intersectTriangle(a,n,r,!0,o):i.intersectTriangle(r,n,a,0===t.side,o),null===h)return null;pr.copy(o),pr.applyMatrix4(e.matrixWorld);const l=s.ray.origin.distanceTo(pr);return l<s.near||l>s.far?null:{distance:l,point:pr.clone(),object:e}}(e,t,s,i,or,hr,lr,dr);if(u){const e=new Ot;si.getBarycoord(dr,or,hr,lr,e),r&&(u.uv=si.getInterpolatedAttribute(r,o,h,l,e,new Dt)),n&&(u.uv1=si.getInterpolatedAttribute(n,o,h,l,e,new Dt)),a&&(u.normal=si.getInterpolatedAttribute(a,o,h,l,e,new Ot),u.normal.dot(i.direction)>0&&u.normal.multiplyScalar(-1));const t={a:o,b:h,c:l,normal:new Ot,materialIndex:0};si.getNormal(or,hr,lr,t.normal),u.face=t,u.barycoord=e}return u}class fr extends ts{constructor(e=null,t=1,s=1,i,r,n,a,o,h=1003,l=1003,u,c){super(null,n,a,o,h,l,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 yr extends Mi{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 br=new Ot,_r=new Ot,xr=new zt;class vr{constructor(e=new Ot(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=br.subVectors(s,t).cross(_r.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,s=!0){const i=e.delta(br),r=this.normal.dot(i);if(0===r)return 0===this.distanceToPoint(e.start)?t.copy(e.start):null;const n=-(e.start.dot(this.normal)+this.constant)/r;return!0===s&&(n<0||n>1)?null:t.copy(e.start).addScaledVector(i,n)}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||xr.getNormalMatrix(e),i=this.coplanarPoint(br).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 Tr=new Fi,Sr=new Dt(.5,.5),wr=new Ot;class Mr{constructor(e=new vr,t=new vr,s=new vr,i=new vr,r=new vr,n=new vr){this.planes=[e,t,s,i,r,n]}set(e,t,s,i,r,n){const a=this.planes;return a[0].copy(e),a[1].copy(t),a[2].copy(s),a[3].copy(i),a[4].copy(r),a[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],a=r[1],o=r[2],h=r[3],l=r[4],u=r[5],c=r[6],d=r[7],p=r[8],m=r[9],g=r[10],f=r[11],y=r[12],b=r[13],_=r[14],x=r[15];if(i[0].setComponents(h-n,d-l,f-p,x-y).normalize(),i[1].setComponents(h+n,d+l,f+p,x+y).normalize(),i[2].setComponents(h+a,d+u,f+m,x+b).normalize(),i[3].setComponents(h-a,d-u,f-m,x-b).normalize(),s)i[4].setComponents(o,c,g,_).normalize(),i[5].setComponents(h-o,d-c,f-g,x-_).normalize();else if(i[4].setComponents(h-o,d-c,f-g,x-_).normalize(),t===ht)i[5].setComponents(h+o,d+c,f+g,x+_).normalize();else{if(t!==lt)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);i[5].setComponents(o,c,g,_).normalize()}return this}intersectsObject(e){if(void 0!==e.boundingSphere)null===e.boundingSphere&&e.computeBoundingSphere(),Tr.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;null===t.boundingSphere&&t.computeBoundingSphere(),Tr.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Tr)}intersectsSprite(e){Tr.center.set(0,0,0);const t=Sr.distanceTo(e.center);return Tr.radius=.7071067811865476+t,Tr.applyMatrix4(e.matrixWorld),this.intersectsSphere(Tr)}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(wr.x=i.normal.x>0?e.max.x:e.min.x,wr.y=i.normal.y>0?e.max.y:e.min.y,wr.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(wr)<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 Nr=new ns,Ar=new Mr;class Er{constructor(){this.coordinateSystem=ht}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(Nr.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Ar.setFromProjectionMatrix(Nr,i.coordinateSystem,i.reversedDepth),Ar.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(Nr.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Ar.setFromProjectionMatrix(Nr,i.coordinateSystem,i.reversedDepth),Ar.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(Nr.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Ar.setFromProjectionMatrix(Nr,i.coordinateSystem,i.reversedDepth),Ar.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(Nr.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Ar.setFromProjectionMatrix(Nr,i.coordinateSystem,i.reversedDepth),Ar.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(Nr.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Ar.setFromProjectionMatrix(Nr,i.coordinateSystem,i.reversedDepth),Ar.containsPoint(e))return!0}return!1}clone(){return new Er}}class Rr extends Hi{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new zs(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 Cr extends Hi{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new zs(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 Pr extends ts{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=O,this.minFilter=O,this.generateMipmaps=!1,this.needsUpdate=!0}}class Br extends ts{constructor(e=[],t=301,s,i,r,n,a,o,h,l){super(e,t,s,i,r,n,a,o,h,l),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class Fr extends ts{constructor(e,t,s=1014,i,r,n,a=1003,o=1003,h,l=1026,u=1){if(l!==ne&&l!==ae)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");super({width:e,height:t,depth:u},i,r,n,a,o,l,s,h),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new Qt(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 Lr extends Fr{constructor(e,t=1014,s=301,i,r,n=1003,a=1003,o,h=1026){const l={width:e,height:e,depth:1},u=[l,l,l,l,l,l];super(e,e,t,s,i,r,n,a,o,h),this.image=u,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}}class Dr extends Vi{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 a=this;i=Math.floor(i),r=Math.floor(r),n=Math.floor(n);const o=[],h=[],l=[],u=[];let c=0,d=0;function p(e,t,s,i,r,n,p,m,g,f,y){const b=n/g,_=p/f,x=n/2,v=p/2,T=m/2,S=g+1,w=f+1;let M=0,N=0;const A=new Ot;for(let n=0;n<w;n++){const a=n*_-v;for(let o=0;o<S;o++){const c=o*b-x;A[e]=c*i,A[t]=a*r,A[s]=T,h.push(A.x,A.y,A.z),A[e]=0,A[t]=0,A[s]=m>0?1:-1,l.push(A.x,A.y,A.z),u.push(o/g),u.push(1-n/f),M+=1}}for(let e=0;e<f;e++)for(let t=0;t<g;t++){const s=c+t+S*e,i=c+t+S*(e+1),r=c+(t+1)+S*(e+1),n=c+(t+1)+S*e;o.push(s,i,n),o.push(i,r,n),N+=6}a.addGroup(d,N,y),d+=N,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(o),this.setAttribute("position",new Ri(h,3)),this.setAttribute("normal",new Ri(l,3)),this.setAttribute("uv",new Ri(u,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Dr(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}class Ir extends Vi{constructor(e=1,t=1,s=1,i=32,r=1,n=!1,a=0,o=2*Math.PI){super(),this.type="CylinderGeometry",this.parameters={radiusTop:e,radiusBottom:t,height:s,radialSegments:i,heightSegments:r,openEnded:n,thetaStart:a,thetaLength:o};const h=this;i=Math.floor(i),r=Math.floor(r);const l=[],u=[],c=[],d=[];let p=0;const m=[],g=s/2;let f=0;function y(s){const r=p,n=new Dt,m=new Ot;let y=0;const b=!0===s?e:t,_=!0===s?1:-1;for(let e=1;e<=i;e++)u.push(0,g*_,0),c.push(0,_,0),d.push(.5,.5),p++;const x=p;for(let e=0;e<=i;e++){const t=e/i*o+a,s=Math.cos(t),r=Math.sin(t);m.x=b*r,m.y=g*_,m.z=b*s,u.push(m.x,m.y,m.z),c.push(0,_,0),n.x=.5*s+.5,n.y=.5*r*_+.5,d.push(n.x,n.y),p++}for(let e=0;e<i;e++){const t=r+e,i=x+e;!0===s?l.push(i,i+1,t):l.push(i+1,i,t),y+=3}h.addGroup(f,y,!0===s?1:2),f+=y}!function(){const n=new Ot,y=new Ot;let b=0;const _=(t-e)/s;for(let h=0;h<=r;h++){const l=[],f=h/r,b=f*(t-e)+e;for(let e=0;e<=i;e++){const t=e/i,r=t*o+a,h=Math.sin(r),m=Math.cos(r);y.x=b*h,y.y=-f*s+g,y.z=b*m,u.push(y.x,y.y,y.z),n.set(h,_,m).normalize(),c.push(n.x,n.y,n.z),d.push(t,1-f),l.push(p++)}m.push(l)}for(let s=0;s<i;s++)for(let i=0;i<r;i++){const n=m[i][s],a=m[i+1][s],o=m[i+1][s+1],h=m[i][s+1];(e>0||0!==i)&&(l.push(n,a,h),b+=3),(t>0||i!==r-1)&&(l.push(a,o,h),b+=3)}h.addGroup(f,b,0),f+=b}(),!1===n&&(e>0&&y(!0),t>0&&y(!1)),this.setIndex(l),this.setAttribute("position",new Ri(u,3)),this.setAttribute("normal",new Ri(c,3)),this.setAttribute("uv",new Ri(d,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Ir(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class Or extends Vi{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,a=Math.floor(s),o=Math.floor(i),h=a+1,l=o+1,u=e/a,c=t/o,d=[],p=[],m=[],g=[];for(let e=0;e<l;e++){const t=e*c-n;for(let s=0;s<h;s++){const i=s*u-r;p.push(i,-t,0),m.push(0,0,1),g.push(s/a),g.push(1-e/o)}}for(let e=0;e<o;e++)for(let t=0;t<a;t++){const s=t+h*e,i=t+h*(e+1),r=t+1+h*(e+1),n=t+1+h*e;d.push(s,i,n),d.push(i,r,n)}this.setIndex(d),this.setAttribute("position",new Ri(p,3)),this.setAttribute("normal",new Ri(m,3)),this.setAttribute("uv",new Ri(g,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Or(e.width,e.height,e.widthSegments,e.heightSegments)}}class Ur extends Vi{constructor(e=1,t=32,s=16,i=0,r=2*Math.PI,n=0,a=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:e,widthSegments:t,heightSegments:s,phiStart:i,phiLength:r,thetaStart:n,thetaLength:a},t=Math.max(3,Math.floor(t)),s=Math.max(2,Math.floor(s));const o=Math.min(n+a,Math.PI);let h=0;const l=[],u=new Ot,c=new Ot,d=[],p=[],m=[],g=[];for(let d=0;d<=s;d++){const f=[],y=d/s;let b=0;0===d&&0===n?b=.5/t:d===s&&o===Math.PI&&(b=-.5/t);for(let s=0;s<=t;s++){const o=s/t;u.x=-e*Math.cos(i+o*r)*Math.sin(n+y*a),u.y=e*Math.cos(n+y*a),u.z=e*Math.sin(i+o*r)*Math.sin(n+y*a),p.push(u.x,u.y,u.z),c.copy(u).normalize(),m.push(c.x,c.y,c.z),g.push(o+b,1-y),f.push(h++)}l.push(f)}for(let e=0;e<s;e++)for(let i=0;i<t;i++){const t=l[e][i+1],r=l[e][i],a=l[e+1][i],h=l[e+1][i+1];(0!==e||n>0)&&d.push(t,r,h),(e!==s-1||o<Math.PI)&&d.push(r,a,h)}this.setIndex(d),this.setAttribute("position",new Ri(p,3)),this.setAttribute("normal",new Ri(m,3)),this.setAttribute("uv",new Ri(g,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Ur(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}}class kr extends Hi{constructor(e){super(),this.isShadowMaterial=!0,this.type="ShadowMaterial",this.color=new zs(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 zr extends Hi{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new zs(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 zs(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Dt(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 gs,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 Vr extends zr{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 Dt(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return Rt(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 zs(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 zs(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new zs(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 Gr extends Hi{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new zs(16777215),this.specular=new zs(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new zs(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Dt(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new gs,this.combine=0,this.reflectivity=1,this.envMapIntensity=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.envMapIntensity=e.envMapIntensity,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 jr extends Hi{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new zs(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new zs(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Dt(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 $r extends Hi{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Dt(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 Wr extends Hi{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new zs(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new zs(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Dt(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new gs,this.combine=0,this.reflectivity=1,this.envMapIntensity=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.envMapIntensity=e.envMapIntensity,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 Hr extends Hi{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new zs(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new Dt(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 qr extends Rr{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 Xr extends Bs{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new zs(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 Yr extends Xr{constructor(e,t,s){super(e,s),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(Bs.DEFAULT_UP),this.updateMatrix(),this.groundColor=new zs(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 Kr=new ns,Qr=new Ot,Zr=new Ot;class Jr{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.biasNode=null,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new Dt(512,512),this.mapType=j,this.map=null,this.mapPass=null,this.matrix=new ns,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new Mr,this._frameExtents=new Dt(1,1),this._viewportCount=1,this._viewports=[new ss(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const t=this.camera,s=this.matrix;Qr.setFromMatrixPosition(e.matrixWorld),t.position.copy(Qr),Zr.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(Zr),t.updateMatrixWorld(),Kr.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(Kr,t.coordinateSystem,t.reversedDepth),t.coordinateSystem===lt||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(Kr)}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.biasNode=e.biasNode,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}}const en=new Ot,tn=new It,sn=new Ot;class rn extends Bs{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new ns,this.projectionMatrix=new ns,this.projectionMatrixInverse=new ns,this.coordinateSystem=ht,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.matrixWorld.decompose(en,tn,sn),1===sn.x&&1===sn.y&&1===sn.z?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(en,tn,sn.set(1,1,1)).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorld.decompose(en,tn,sn),1===sn.x&&1===sn.y&&1===sn.z?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(en,tn,sn.set(1,1,1)).invert()}clone(){return(new this.constructor).copy(this)}}const nn=new Ot,an=new Dt,on=new Dt;class hn extends rn{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*At*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(.5*Nt*this.fov);return.5*this.getFilmHeight()/e}getEffectiveFOV(){return 2*At*Math.atan(Math.tan(.5*Nt*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){nn.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(nn.x,nn.y).multiplyScalar(-e/nn.z),nn.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),s.set(nn.x,nn.y).multiplyScalar(-e/nn.z)}getViewSize(e,t){return this.getViewBounds(e,an,on),t.subVectors(on,an)}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*Nt*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,a=n.fullHeight;r+=n.offsetX*i/e,t-=n.offsetY*s/a,i*=n.width/e,s*=n.height/a}const a=this.filmOffset;0!==a&&(r+=e*a/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}}class ln extends Jr{constructor(){super(new hn(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1,this.aspect=1}updateMatrices(e){const t=this.camera,s=2*At*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 un extends Xr{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(Bs.DEFAULT_UP),this.updateMatrix(),this.target=new Bs,this.distance=s,this.angle=i,this.penumbra=r,this.decay=n,this.map=null,this.shadow=new ln}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 cn extends Jr{constructor(){super(new hn(90,1,.5,500)),this.isPointLightShadow=!0}}class dn extends Xr{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 cn}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 pn extends rn{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,a=i+t,o=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,a-=t*this.view.offsetY,o=a-t*this.view.height}this.projectionMatrix.makeOrthographic(r,n,a,o,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 mn extends Jr{constructor(){super(new pn(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class gn extends Xr{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(Bs.DEFAULT_UP),this.updateMatrix(),this.target=new Bs,this.shadow=new mn}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 fn extends Xr{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type="AmbientLight"}}class yn extends Xr{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 bn{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let e=0;e<9;e++)this.coefficients.push(new Ot)}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 _n extends Xr{constructor(e=new bn,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}}const xn=-90;class vn extends Bs{constructor(e,t,s){super(),this.type="CubeCamera",this.renderTarget=s,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new hn(xn,1,e,t);i.layers=this.layers,this.add(i);const r=new hn(xn,1,e,t);r.layers=this.layers,this.add(r);const n=new hn(xn,1,e,t);n.layers=this.layers,this.add(n);const a=new hn(xn,1,e,t);a.layers=this.layers,this.add(a);const o=new hn(xn,1,e,t);o.layers=this.layers,this.add(o);const h=new hn(xn,1,e,t);h.layers=this.layers,this.add(h)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[s,i,r,n,a,o]=t;for(const e of t)this.remove(e);if(e===ht)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),a.up.set(0,1,0),a.lookAt(0,0,1),o.up.set(0,1,0),o.lookAt(0,0,-1);else{if(e!==lt)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),a.up.set(0,-1,0),a.lookAt(0,0,1),o.up.set(0,-1,0),o.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,a,o,h,l]=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;let g=!1;g=!0===e.isWebGLRenderer?e.state.buffers.depth.getReversed():e.reversedDepthBuffer,e.setRenderTarget(s,0,i),g&&!1===e.autoClear&&e.clearDepth(),e.render(t,r),e.setRenderTarget(s,1,i),g&&!1===e.autoClear&&e.clearDepth(),e.render(t,n),e.setRenderTarget(s,2,i),g&&!1===e.autoClear&&e.clearDepth(),e.render(t,a),e.setRenderTarget(s,3,i),g&&!1===e.autoClear&&e.clearDepth(),e.render(t,o),e.setRenderTarget(s,4,i),g&&!1===e.autoClear&&e.clearDepth(),e.render(t,h),s.texture.generateMipmaps=m,e.setRenderTarget(s,5,i),g&&!1===e.autoClear&&e.clearDepth(),e.render(t,l),e.setRenderTarget(u,c,d),e.xr.enabled=p,s.texture.needsPMREMUpdate=!0}}class Tn extends hn{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class Sn extends Gi{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 wn{static{wn.prototype.isMatrix2=!0}constructor(e,t,s,i){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 Mn(e,t,s,i){const r=function(e){switch(e){case j:case $:return{byteLength:1,components:1};case H:case W:case K:return{byteLength:2,components:1};case Q:case Z:return{byteLength:2,components:4};case X:case q:case Y:return{byteLength:4,components:1};case ee:case te:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${e}.`)}(i);switch(s){case se:return e*t;case oe:case he:return e*t/r.components*r.byteLength;case le:case ue:return e*t*2/r.components*r.byteLength;case ie:return e*t*3/r.components*r.byteLength;case re:case ce:return e*t*4/r.components*r.byteLength;case de:case pe:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case me:case ge:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case ye:case _e:return Math.max(e,16)*Math.max(t,8)/4;case fe:case be:return Math.max(e,8)*Math.max(t,8)/2;case xe:case ve:case Se:case we:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case Te:case Me:case Ne:case Ae:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case Ee:return Math.floor((e+4)/5)*Math.floor((t+3)/4)*16;case Re:return Math.floor((e+4)/5)*Math.floor((t+4)/5)*16;case Ce:return Math.floor((e+5)/6)*Math.floor((t+4)/5)*16;case Pe:return Math.floor((e+5)/6)*Math.floor((t+5)/6)*16;case Be:return Math.floor((e+7)/8)*Math.floor((t+4)/5)*16;case Fe:return Math.floor((e+7)/8)*Math.floor((t+5)/6)*16;case Le:return Math.floor((e+7)/8)*Math.floor((t+7)/8)*16;case De:return Math.floor((e+9)/10)*Math.floor((t+4)/5)*16;case Ie:return Math.floor((e+9)/10)*Math.floor((t+5)/6)*16;case Oe:return Math.floor((e+9)/10)*Math.floor((t+7)/8)*16;case Ue:return Math.floor((e+9)/10)*Math.floor((t+9)/10)*16;case ke:return Math.floor((e+11)/12)*Math.floor((t+9)/10)*16;case ze:return Math.floor((e+11)/12)*Math.floor((t+11)/12)*16;case Ve:case 36494:case 36495:return Math.ceil(e/4)*Math.ceil(t/4)*16;case Ge:case je:return Math.ceil(e/4)*Math.ceil(t/4)*8;case $e:case We: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:a}})),"undefined"!=typeof window&&(window.__THREE__?bt("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=a);const Nn=["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"],An=new WeakMap,En=new WeakMap,Rn=new WeakMap;class Cn{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=!0===e.object.isSkinnedMesh,this.refreshUniforms=Nn,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,object:i}=e;if(t={geometryId:s.id,worldMatrix:i.matrixWorld.clone()},i.center&&(t.center=i.center.clone()),i.morphTargetInfluences&&(t.morphTargetInfluences=i.morphTargetInfluences.slice()),null!==e.bundle&&(t.version=e.bundle.version),e.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]={id:i.id,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)}getGeometryData(e){let t=Rn.get(e);return void 0===t&&(t={_renderId:-1,_equal:!1,attributes:this.getAttributesData(e.attributes),indexId:e.index?e.index.id:null,indexVersion:e.index?e.index.version:null,drawRange:{start:e.drawRange.start,count:e.drawRange.count}},Rn.set(e,t)),t}getMaterialData(e){let t=En.get(e);if(void 0===t){t={_renderId:-1,_equal:!1};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)}En.set(e,t)}return t}equals(e,t,s){const{object:i,material:r,geometry:n}=e,a=this.getRenderObjectData(e);if(!0!==a.worldMatrix.equals(i.matrixWorld))return a.worldMatrix.copy(i.matrixWorld),!1;const o=this.getMaterialData(e.material);if(o._renderId!==s){o._renderId=s;for(const e in o){const t=o[e],s=r[e];if("_renderId"!==e&&"_equal"!==e)if(void 0!==t.equals){if(!1===t.equals(s))return t.copy(s),o._equal=!1,!1}else if(!0===s.isTexture){if(t.id!==s.id||t.version!==s.version)return t.id=s.id,t.version=s.version,o._equal=!1,!1}else if(t!==s)return o[e]=s,o._equal=!1,!1}if(o.transmission>0){const{width:t,height:s}=e.context;if(a.bufferWidth!==t||a.bufferHeight!==s)return a.bufferWidth=t,a.bufferHeight=s,o._equal=!1,!1}o._equal=!0}else if(!1===o._equal)return!1;if(a.geometryId!==n.id)return a.geometryId=n.id,!1;const h=this.getGeometryData(e.geometry);if(h._renderId!==s){h._renderId=s;const e=n.attributes,t=h.attributes;let i=0,r=0;for(const t in e)i++;for(const s in t){r++;const i=t[s],n=e[s];if(void 0===n)return delete t[s],h._equal=!1,!1;if(i.id!==n.id||i.version!==n.version)return i.id=n.id,i.version=n.version,h._equal=!1,!1}if(r!==i)return h.attributes=this.getAttributesData(e),h._equal=!1,!1;const a=n.index,o=h.indexId,l=h.indexVersion,u=a?a.id:null,c=a?a.version:null;if(o!==u||l!==c)return h.indexId=u,h.indexVersion=c,h._equal=!1,!1;if(h.drawRange.start!==n.drawRange.start||h.drawRange.count!==n.drawRange.count)return h.drawRange.start=n.drawRange.start,h.drawRange.count=n.drawRange.count,h._equal=!1,!1;h._equal=!0}else if(!1===h._equal)return!1;if(a.morphTargetInfluences){let e=!1;for(let t=0;t<a.morphTargetInfluences.length;t++)a.morphTargetInfluences[t]!==i.morphTargetInfluences[t]&&(a.morphTargetInfluences[t]=i.morphTargetInfluences[t],e=!0);if(e)return!1}if(a.lights)for(let e=0;e<t.length;e++)if(a.lights[e].map!==t[e].map)return!1;return a.center&&!1===a.center.equals(i.center)?(a.center.copy(i.center),!0):(null!==e.bundle&&(a.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(An.has(e)){const s=An.get(e);if(s.renderId===t)return s.lightsData}const s=this.getLightsData(e.getLights());return An.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,s)}}const Pn=[/^StackTrace\.js$/,/^TSLCore\.js$/,/^.*Node\.js$/,/^three\.webgpu.*\.js$/];class Bn{constructor(e=null){this.isStackTrace=!0,this.stack=function(e){const t=/(?:at\s+(.+?)\s+\()?(?:(.+?)@)?([^@\s()]+):(\d+):(\d+)/;return e.split("\n").map(e=>{const s=e.match(t);if(!s)return null;const i=s[1]||s[2]||"",r=s[3].split("?")[0],n=parseInt(s[4],10),a=parseInt(s[5],10);return{fn:i,file:r.split("/").pop(),line:n,column:a}}).filter(e=>e&&!Pn.some(t=>t.test(e.file)))}(e||(new Error).stack)}getLocation(){if(0===this.stack.length)return"[Unknown location]";const e=this.stack[0],t=e.fn;return`${t?`"${t}()" at `:""}"${e.file}:${e.line}"`}getError(e){if(0===this.stack.length)return e;return`${e}\n${this.stack.map(e=>{const t=`${e.file}:${e.line}:${e.column}`;return e.fn?` at ${e.fn} (${t})`:` at ${t}`}).join("\n")}`}}function Fn(e,t=0){let s=3735928559^t,i=1103547991^t;if(Array.isArray(e))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 Ln=e=>Fn(e),Dn=e=>Fn(e),In=(...e)=>Fn(e),On=new Map([[1,"float"],[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),Un=new WeakMap;function kn(e){return On.get(e)}function zn(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 Vn(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 zs(...t):"vec2"===s?new Dt(...t):"vec3"===s?new Ot(...t):"vec4"===s?new ss(...t):"mat2"===s?new wn(...t):"mat3"===s?new zt(...t):"mat4"===s?new ns(...t):"bool"===e?t[0]||!1:"float"===e||"int"===e||"uint"===e?t[0]||0:"string"===e?t[0]||"":"ArrayBuffer"===e?(i=t[0],Uint8Array.from(atob(i),e=>e.charCodeAt(0)).buffer):null;var i}function Gn(e){let t=Un.get(e);return void 0===t&&(t={},Un.set(e,t)),t}const jn="vertex",$n="none",Wn="frame",Hn="render",qn="object",Xn="readOnly",Yn="writeOnly",Kn="readWrite",Qn=["setup","analyze","generate"],Zn=["fragment","vertex","compute"],Jn=["x","y","z","w"],ea={analyze:"setup",generate:"analyze"};let ta=0;class sa extends St{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=$n,this.updateBeforeType=$n,this.updateAfterType=$n,this.version=0,this.name="",this.global=!1,this.parents=!1,this.isNode=!0,this._beforeNodes=null,this._cacheKey=null,this._uuid=null,this._cacheKeyVersion=0,this.id=ta++,this.stackTrace=null,!0===sa.captureStackTrace&&(this.stackTrace=new Bn)}set needsUpdate(e){!0===e&&this.version++}get uuid(){return null===this._uuid&&(this._uuid=Lt.generateUUID()),this._uuid}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,Wn)}onRenderUpdate(e){return this.onUpdate(e,Hn)}onObjectUpdate(e){return this.onUpdate(e,qn)}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(Ln(i.slice(0,-4)),r.getCacheKey(e,t));this._cacheKey=In(Dn(s),this.customCacheKey()),this._cacheKeyVersion=this.version}return this._cacheKey}customCacheKey(){return this.id}getScope(){return this}getHash(){return String(this.id)}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,t=null){const s=e.getDataFromNode(this);let i;return null!==t?(s.typeFromOutput=s.typeFromOutput||{},i=s.typeFromOutput[t],void 0===i&&(i=this.generateNodeType(e,t),s.typeFromOutput[t]=i)):(i=s.type,void 0===i&&(i=this.generateNodeType(e),s.type=i)),i}generateNodeType(e,t=null){const s=e.getNodeProperties(this);return s.outputNode?s.outputNode.getNodeType(e,t):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(){bt("Abstract function.")}updateAfter(){bt("Abstract function.")}update(){bt("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=ea[e.buildStage];if(r&&!0!==i.buildStages[r]){const t=e.getBuildStage();e.setBuildStage(r),this.build(e),e.setBuildStage(t)}e.addChain(this);let n=null;const a=e.getBuildStage();if("setup"===a){e.addNode(this),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)}e.addSequentialNode(this)}n=t.outputNode}else if("analyze"===a)this.analyze(e,t);else if("generate"===a){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):(bt("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&&(_t(`TSL: Invalid generated code, expected a "${t}".`),n=e.generateConst(t))}return e.removeChain(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}}sa.captureStackTrace=!1;class ia extends sa{static get type(){return"ArrayElementNode"}constructor(e,t){super(),this.node=e,this.indexNode=t,this.isArrayElementNode=!0}generateNodeType(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 ra extends sa{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}generateNodeType(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 na extends sa{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),a=e.getPropertyName(n);return e.addLineFlowCode(`${a} = ${r}`,this),i.snippet=r,i.propertyName=a,e.format(i.propertyName,s,t)}}return super.build(e,t)}}class aa extends na{static get type(){return"JoinNode"}constructor(e=[],t=null){super(t),this.nodes=e}generateNodeType(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),a=[];let o=0;for(const t of r){if(o>=i){_t(`TSL: Length of parameters exceeds maximum length of function '${s}()' type.`,this.stackTrace);break}let r,h=t.getNodeType(e),l=e.getTypeLength(h);o+l>i&&(_t(`TSL: Length of '${s}()' data exceeds maximum length of output type.`,this.stackTrace),l=i-o,h=e.getTypeFromLength(l)),o+=l,r=t.build(e,h);if(e.getComponentType(h)!==n){const t=e.getTypeFromLength(l,n);r=e.format(r,h,t)}a.push(r)}const h=`${e.getType(s)}( ${a.join(", ")} )`;return e.format(h,s,t)}}const oa=Jn.join("");class ha extends sa{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(Jn.indexOf(t)+1,e);return e}getComponentType(e){return e.getComponentType(this.node.getNodeType(e))}generateNodeType(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 a=s.build(e,n);r=this.components.length===i&&this.components===oa.slice(0,this.components.length)?e.format(a,n,t):e.format(`${a}.${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 la extends na{static get type(){return"SetNode"}constructor(e,t,s){super(),this.sourceNode=e,this.components=t,this.targetNode=s}generateNodeType(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)),a=e.getTypeFromLength(s.length,n),o=i.build(e,a),h=t.build(e,r),l=e.getTypeLength(r),u=[];for(let e=0;e<l;e++){const t=Jn[e];t===s[0]?(u.push(o),e+=s.length-1):u.push(h+"."+t)}return`${e.getType(r)}( ${u.join(", ")} )`}}class ua extends na{static get type(){return"FlipNode"}constructor(e,t){super(),this.sourceNode=e,this.components=t}generateNodeType(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),a=e.getPropertyName(n);e.addLineFlowCode(a+" = "+r,this);const o=e.getTypeLength(i),h=[];let l=0;for(let e=0;e<o;e++){const s=Jn[e];s===t[l]?(h.push("1.0 - "+a+"."+s),l++):h.push(a+"."+s)}return`${e.getType(i)}( ${h.join(", ")} )`}}class ca extends sa{static get type(){return"InputNode"}constructor(e,t=null){super(t),this.isInputNode=!0,this.value=e,this.precision=null}generateNodeType(){return null===this.nodeType?zn(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=zn(this.value),e.nodeType=this.nodeType,"ArrayBuffer"===e.valueType&&(e.value=function(e){let t="";const s=new Uint8Array(e);for(let e=0;e<s.length;e++)t+=String.fromCharCode(s[e]);return btoa(t)}(e.value)),e.precision=this.precision}deserialize(e){super.deserialize(e),this.nodeType=e.nodeType,this.value=Array.isArray(e.value)?Vn(e.valueType,...e.value):e.value,this.precision=e.precision||null,this.value&&this.value.fromArray&&(this.value=this.value.fromArray(e.value))}generate(){bt("Abstract function.")}}const da=/float|u?int/;class pa extends ca{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 da.test(s)&&da.test(t)?e.generateConst(t,this.value):e.format(this.generateConst(e),s,t)}}class ma extends sa{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)}generateNodeType(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)){bt(`TSL: Member "${this.property}" does not exist in struct.`,this.stackTrace);const t=this.getNodeType(e);return e.generateConst(t)}return this.structNode.build(e)+"."+this.property}}let ga=null;const fa=new Map;function ya(e,t){if(fa.has(e))bt(`TSL: Redefinition of method chaining '${e}'.`);else{if("function"!=typeof t)throw new Error(`THREE.TSL: Node element ${e} is not a function`);fa.set(e,t),"assign"!==e&&(sa.prototype[e]=function(...e){return this.isStackNode?this.addToStack(t(...e)):t(this,...e)},sa.prototype[e+"Assign"]=function(...e){return this.isStackNode?this.assign(e[0],t(...e)):this.assign(t(this,...e))})}}const ba=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("");sa.prototype.assign=function(...e){if(!0!==this.isStackNode)return null!==ga?ga.assign(this,...e):_t("TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().",new Bn),this;{const t=fa.get("assign");return this.addToStack(t(...e))}},sa.prototype.toVarIntent=function(){return this},sa.prototype.get=function(e){return new ma(this,e)};const _a={};function xa(e,t,s){_a[e]=_a[t]=_a[s]={get(){this._cache=this._cache||{};let t=this._cache[e];return void 0===t&&(t=new ha(this,e),this._cache[e]=t),t},set(t){this[e].assign(Wa(t))}};const i=e.toUpperCase(),r=t.toUpperCase(),n=s.toUpperCase();sa.prototype["set"+i]=sa.prototype["set"+r]=sa.prototype["set"+n]=function(t){const s=ba(e);return new la(this,s,Wa(t))},sa.prototype["flip"+i]=sa.prototype["flip"+r]=sa.prototype["flip"+n]=function(){const t=ba(e);return new ua(this,t)}}const va=["x","y","z","w"],Ta=["r","g","b","a"],Sa=["s","t","p","q"];for(let e=0;e<4;e++){let t=va[e],s=Ta[e],i=Sa[e];xa(t,s,i);for(let r=0;r<4;r++){t=va[e]+va[r],s=Ta[e]+Ta[r],i=Sa[e]+Sa[r],xa(t,s,i);for(let n=0;n<4;n++){t=va[e]+va[r]+va[n],s=Ta[e]+Ta[r]+Ta[n],i=Sa[e]+Sa[r]+Sa[n],xa(t,s,i);for(let a=0;a<4;a++)t=va[e]+va[r]+va[n]+va[a],s=Ta[e]+Ta[r]+Ta[n]+Ta[a],i=Sa[e]+Sa[r]+Sa[n]+Sa[a],xa(t,s,i)}}}for(let e=0;e<32;e++)_a[e]={get(){this._cache=this._cache||{};let t=this._cache[e];return void 0===t&&(t=new ia(this,new pa(e,"uint")),this._cache[e]=t),t},set(t){this[e].assign(Wa(t))}};Object.defineProperties(sa.prototype,_a);const wa=new WeakMap,Ma=function(e,t=null){for(const s in e)e[s]=Wa(e[s],t);return e},Na=function(e,t=null){const s=e.length;for(let i=0;i<s;i++)e[i]=Wa(e[i],t);return e},Aa=function(e,t=null,s=null,i=null){function r(e){return null!==i?(e=Wa(Object.assign(e,i)),!0===i.intent&&(e=e.toVarIntent())):e=Wa(e),e}let n,a,o,h=t;function l(t){let s;return s=h?/[a-z]/i.test(h)?h+"()":h:e.type,void 0!==a&&t.length<a?(_t(`TSL: "${s}" parameter length is less than minimum required.`,new Bn),t.concat(new Array(a-t.length).fill(0))):void 0!==o&&t.length>o?(_t(`TSL: "${s}" parameter length exceeds limit.`,new Bn),t.slice(0,o)):t}return null===t?n=(...t)=>r(new e(...Xa(l(t)))):null!==s?(s=Wa(s),n=(...i)=>r(new e(t,...Xa(l(i)),s))):n=(...s)=>r(new e(t,...Xa(l(s)))),n.setParameterLength=(...e)=>(1===e.length?a=o=e[0]:2===e.length&&([a,o]=e),n),n.setName=e=>(h=e,n),n},Ea=function(e,...t){return new e(...Xa(t))};class Ra extends sa{constructor(e,t){super(),this.shaderNode=e,this.rawInputs=t,this.isShaderCallNodeInternal=!0}generateNodeType(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 a=e.subBuildFn,o=e.fnCall;e.subBuildFn=r,e.fnCall=this;let h=null;if(t.layout){let i=wa.get(e.constructor);void 0===i&&(i=new WeakMap,wa.set(e.constructor,i));let r=i.get(t);void 0===r&&(r=Wa(e.buildFunctionNode(t)),i.set(t,r)),e.addInclude(r);const n=s?function(e){let t;qa(e);t=e[0]&&(e[0].isNode||Object.getPrototypeOf(e[0])!==Object.prototype)?[...e]:e[0];return t}(s):null;h=Wa(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 qa(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 Wa(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 sa&&(n=void 0===e[i]?e[t++]:Reflect.get(e,i,r));else n=Reflect.get(s,i,r);n=Wa(n)}return n}})}(s):null,n=Array.isArray(s)?s.length>0:null!==s,a=t.jsFunc,o=n||a.length>1?a(r,i):a(i);h=Wa(o)}return e.subBuildFn=a,e.fnCall=o,t.once&&(i[n]=h),h}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),a=this.getOutputNode(e),o=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?a.build(e,t):"generate"===i&&(s=a.build(e,t)||"");return e.fnCall=o,s}}class Ca extends sa{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 Ra(this,e)}setup(){return this.call()}}const Pa=[!1,!0],Ba=[0,1,2,3],Fa=[-1,-2],La=[.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],Da=new Map;for(const e of Pa)Da.set(e,new pa(e));const Ia=new Map;for(const e of Ba)Ia.set(e,new pa(e,"uint"));const Oa=new Map([...Ia].map(e=>new pa(e.value,"int")));for(const e of Fa)Oa.set(e,new pa(e,"int"));const Ua=new Map([...Oa].map(e=>new pa(e.value)));for(const e of La)Ua.set(e,new pa(e));for(const e of La)Ua.set(-e,new pa(-e));const ka={bool:Da,uint:Ia,ints:Oa,float:Ua},za=new Map([...Da,...Ua]),Va=(e,t)=>za.has(e)?za.get(e):!0===e.isNode?e:new pa(e,t),Ga=function(e,t=null){return(...s)=>{for(const t of s)if(void 0===t)return _t(`TSL: Invalid parameter for the type "${e}".`,new Bn),new pa(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=[Vn(e,...s)]),1===s.length&&null!==t&&t.has(s[0]))return Ha(t.get(s[0]));if(1===s.length){const t=Va(s[0],e);return t.nodeType===e?Ha(t):Ha(new ra(t,e))}const i=s.map(e=>Va(e));return Ha(new aa(i,e))}};function ja(e){return e&&e.isNode&&e.traverse(t=>{t.isConstNode&&(e=t.value)}),Boolean(e)}function $a(e,t){return new Ca(e,t)}const Wa=(e,t=null)=>function(e,t=null){const s=zn(e);return"node"===s?e:null===t&&("float"===s||"boolean"===s)||s&&"shader"!==s&&"string"!==s?Wa(Va(e,t)):"shader"===s?e.isFn?e:eo(e):e}(e,t),Ha=(e,t=null)=>Wa(e,t).toVarIntent(),qa=(e,t=null)=>new Ma(e,t),Xa=(e,t=null)=>new Na(e,t),Ya=(e,t=null,s=null,i=null)=>new Aa(e,t,s,i),Ka=(e,...t)=>new Ea(e,...t),Qa=(e,t=null,s=null,i={})=>new Aa(e,t,s,{...i,intent:!0});let Za=0;class Ja extends sa{constructor(e,t=null){super();let s=null;null!==t&&("object"==typeof t?s=t.return:("string"==typeof t?s=t:_t("TSL: Invalid layout type.",new Bn),t=null)),this.shaderNode=new $a(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"+Za++,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}generateNodeType(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 _t('TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".',this.stackTrace),e.generateConst(t)}}function eo(e,t=null){const s=new Ja(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 to=e=>{ga=e},so=()=>ga,io=(...e)=>ga.If(...e);function ro(e){return ga&&ga.addToStack(e),e}ya("toStack",ro);const no=new Ga("color"),ao=new Ga("float",ka.float),oo=new Ga("int",ka.ints),ho=new Ga("uint",ka.uint),lo=new Ga("bool",ka.bool),uo=new Ga("vec2"),co=new Ga("ivec2"),po=new Ga("uvec2"),mo=new Ga("bvec2"),go=new Ga("vec3"),fo=new Ga("ivec3"),yo=new Ga("uvec3"),bo=new Ga("bvec3"),_o=new Ga("vec4"),xo=new Ga("ivec4"),vo=new Ga("uvec4"),To=new Ga("bvec4"),So=new Ga("mat2"),wo=new Ga("mat3"),Mo=new Ga("mat4");ya("toColor",no),ya("toFloat",ao),ya("toInt",oo),ya("toUint",ho),ya("toBool",lo),ya("toVec2",uo),ya("toIVec2",co),ya("toUVec2",po),ya("toBVec2",mo),ya("toVec3",go),ya("toIVec3",fo),ya("toUVec3",yo),ya("toBVec3",bo),ya("toVec4",_o),ya("toIVec4",xo),ya("toUVec4",vo),ya("toBVec4",To),ya("toMat2",So),ya("toMat3",wo),ya("toMat4",Mo);ya("element",Ya(ia).setParameterLength(2)),ya("convert",(e,t)=>new ra(Wa(e),t)),ya("append",e=>(bt("TSL: .append() has been renamed to .toStack().",new Bn),ro(e)));class No extends sa{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 Ln(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 Ao=(e,t)=>new No(e,t),Eo=(e,t)=>new No(e,t,!0),Ro=Ka(No,"vec4","DiffuseColor"),Co=Ka(No,"vec3","DiffuseContribution"),Po=Ka(No,"vec3","EmissiveColor"),Bo=Ka(No,"float","Roughness"),Fo=Ka(No,"float","Metalness"),Lo=Ka(No,"float","Clearcoat"),Do=Ka(No,"float","ClearcoatRoughness"),Io=Ka(No,"vec3","Sheen"),Oo=Ka(No,"float","SheenRoughness"),Uo=Ka(No,"float","Iridescence"),ko=Ka(No,"float","IridescenceIOR"),zo=Ka(No,"float","IridescenceThickness"),Vo=Ka(No,"float","AlphaT"),Go=Ka(No,"float","Anisotropy"),jo=Ka(No,"vec3","AnisotropyT"),$o=Ka(No,"vec3","AnisotropyB"),Wo=Ka(No,"color","SpecularColor"),Ho=Ka(No,"color","SpecularColorBlended"),qo=Ka(No,"float","SpecularF90"),Xo=Ka(No,"float","Shininess"),Yo=Ka(No,"vec4","Output"),Ko=Ka(No,"float","dashSize"),Qo=Ka(No,"float","gapSize"),Zo=Ka(No,"float","IOR"),Jo=Ka(No,"float","Transmission"),eh=Ka(No,"float","Thickness"),th=Ka(No,"float","AttenuationDistance"),sh=Ka(No,"color","AttenuationColor"),ih=Ka(No,"float","Dispersion");class rh extends sa{static get type(){return"UniformGroupNode"}constructor(e,t=!1,s=1,i=null){super("string"),this.name=e,this.shared=t,this.order=s,this.updateType=i,this.isUniformGroup=!0}update(){this.needsUpdate=!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 nh=(e,t=1,s=null)=>new rh(e,!1,t,s),ah=(e,t=0,s=null)=>new rh(e,!0,t,s),oh=ah("render",0,Hn),hh=nh("object",1,qn);class lh extends ca{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=hh}setName(e){return this.name=e,this}label(e){return bt('TSL: "label()" has been deprecated. Use "setName()" instead.',new Bn),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),a=e.getUniformFromNode(r,n,e.shaderStage,this.name||e.context.nodeName),o=e.getPropertyName(a);void 0!==e.context.nodeName&&delete e.context.nodeName;let h=o;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,h=e.format(o,n,s),e.addLineFlowCode(`${i} = ${h}`,this)}h=i}return e.format(h,s,t)}}const uh=(e,t)=>{const s=(e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null)(t||e);if(s===e&&(e=Vn(s)),e&&!0===e.isNode){let t=e.value;e.traverse(e=>{!0===e.isConstNode&&(t=e.value)}),e=t}return new lh(e,s)};class ch extends na{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}generateNodeType(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)}}ya("toArray",(e,t)=>((...e)=>{let t;if(1===e.length){const s=e[0];t=new ch(null,s.length,s)}else{const s=e[0],i=e[1];t=new ch(s,i)}return Wa(t)})(Array(t).fill(e)));class dh extends na{static get type(){return"AssignNode"}constructor(e,t){super(),this.targetNode=e,this.sourceNode=t,this.isAssignNode=!0}hasDependencies(){return!1}generateNodeType(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 Jn.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),a=s.getNodeType(e),o=i.build(e,a),h=i.getNodeType(e),l=e.getDataFromNode(this);let u;if(!0===l.initialized)"void"!==t&&(u=n);else if(r){const i=e.getVarFromNode(this,null,a),r=e.getPropertyName(i);e.addLineFlowCode(`${r} = ${o}`,this);const h=s.node,l=h.node.context({assign:!0}).build(e);for(let t=0;t<h.components.length;t++){const s=h.components[t];e.addLineFlowCode(`${l}.${s} = ${r}[ ${t} ]`,this)}"void"!==t&&(u=n)}else u=`${n} = ${o}`,"void"!==t&&"void"!==h||(e.addLineFlowCode(u,this),"void"!==t&&(u=n));return l.initialized=!0,e.format(u,a,t)}}ya("assign",Ya(dh).setParameterLength(2));class ph extends na{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}generateNodeType(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)_t("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(_t("TSL: The number of provided parameters is less than the expected number of inputs in 'Fn()'.");r.length<i.length;)r.push(ao(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)):(_t(`TSL: Input '${e.name}' not found in 'Fn()'.`),t.push(n(ao(0),e)))}return`${s.build(e,"property")}( ${t.join(", ")} )`}}ya("call",(e,...t)=>(t=t.length>1||t[0]&&!0===t[0].isNode?Xa(t):qa(t[0]),new ph(Wa(e),t)));const mh={"==":"equal","!=":"notEqual","<":"lessThan",">":"greaterThan","<=":"lessThanEqual",">=":"greaterThanEqual","%":"mod"};class gh extends na{static get type(){return"OperatorNode"}constructor(e,t,s,...i){if(super(),i.length>0){let r=new gh(e,t,s);for(let t=0;t<i.length-1;t++)r=new gh(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(mh[this.op],t)}generateNodeType(e,t=null){const s=this.op,i=this.aNode,r=this.bNode,n=i.getNodeType(e),a=r?r.getNodeType(e):null;if("void"===n||"void"===a)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(a));return t>1?`bvec${t}`:"bool"}if(e.isMatrix(n)){if("float"===a)return n;if(e.isVector(a))return e.getVectorFromMatrix(n);if(e.isMatrix(a))return n}else if(e.isMatrix(a)){if("float"===n)return a;if(e.isVector(n))return e.getVectorFromMatrix(a)}return e.getTypeLength(a)>e.getTypeLength(n)?a:n}generate(e,t){const s=this.op,{aNode:i,bNode:r}=this,n=this.getNodeType(e,t);let a=null,o=null;"void"!==n?(a=i.getNodeType(e),o=r?r.getNodeType(e):null,"<"===s||">"===s||"<="===s||">="===s||"=="===s||"!="===s?e.isVector(a)?o=a:e.isVector(o)?a=o:a!==o&&(a=o="float"):">>"===s||"<<"===s?(a=n,o=e.changeComponentType(o,"uint")):"%"===s?(a=n,o=e.isInteger(a)&&e.isInteger(o)?o:a):e.isMatrix(a)?"float"===o?o="float":e.isVector(o)?o=e.getVectorFromMatrix(a):e.isMatrix(o)||(a=o=n):a=e.isMatrix(o)?"float"===a?"float":e.isVector(a)?e.getVectorFromMatrix(o):o=n:o=n):a=o=n;const h=i.build(e,a),l=r?r.build(e,o):null,u=e.getFunctionOperator(s);if("void"!==t){const i=e.renderer.coordinateSystem===ht;if("=="===s||"!="===s||"<"===s||">"===s||"<="===s||">="===s)return i&&e.isVector(a)?e.format(`${this.getOperatorMethod(e,t)}( ${h}, ${l} )`,n,t):e.format(`( ${h} ${s} ${l} )`,n,t);if("%"===s)return e.isInteger(o)?e.format(`( ${h} % ${l} )`,n,t):e.format(`${this.getOperatorMethod(e,n)}( ${h}, ${l} )`,n,t);if("!"===s||"~"===s)return e.format(`(${s}${h})`,a,t);if(u)return e.format(`${u}( ${h}, ${l} )`,n,t);if(e.isMatrix(a)&&"float"===o)return e.format(`( ${l} ${s} ${h} )`,n,t);if("float"===a&&e.isMatrix(o))return e.format(`${h} ${s} ${l}`,n,t);{let r=`( ${h} ${s} ${l} )`;return!i&&"bool"===n&&e.isVector(a)&&e.isVector(o)&&(r=`all${r}`),e.format(r,n,t)}}if("void"!==a)return u?e.format(`${u}( ${h}, ${l} )`,n,t):e.isMatrix(a)&&"float"===o?e.format(`${l} ${s} ${h}`,n,t):e.format(`${h} ${s} ${l}`,n,t)}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const fh=Qa(gh,"+").setParameterLength(2,1/0).setName("add"),yh=Qa(gh,"-").setParameterLength(2,1/0).setName("sub"),bh=Qa(gh,"*").setParameterLength(2,1/0).setName("mul"),_h=Qa(gh,"/").setParameterLength(2,1/0).setName("div"),xh=Qa(gh,"%").setParameterLength(2).setName("mod"),vh=Qa(gh,"==").setParameterLength(2).setName("equal"),Th=Qa(gh,"!=").setParameterLength(2).setName("notEqual"),Sh=Qa(gh,"<").setParameterLength(2).setName("lessThan"),wh=Qa(gh,">").setParameterLength(2).setName("greaterThan"),Mh=Qa(gh,"<=").setParameterLength(2).setName("lessThanEqual"),Nh=Qa(gh,">=").setParameterLength(2).setName("greaterThanEqual"),Ah=Qa(gh,"&&").setParameterLength(2,1/0).setName("and"),Eh=Qa(gh,"||").setParameterLength(2,1/0).setName("or"),Rh=Qa(gh,"!").setParameterLength(1).setName("not"),Ch=Qa(gh,"^^").setParameterLength(2).setName("xor"),Ph=Qa(gh,"&").setParameterLength(2).setName("bitAnd"),Bh=Qa(gh,"~").setParameterLength(1).setName("bitNot"),Fh=Qa(gh,"|").setParameterLength(2).setName("bitOr"),Lh=Qa(gh,"^").setParameterLength(2).setName("bitXor"),Dh=Qa(gh,"<<").setParameterLength(2).setName("shiftLeft"),Ih=Qa(gh,">>").setParameterLength(2).setName("shiftRight"),Oh=eo(([e])=>(e.addAssign(1),e)),Uh=eo(([e])=>(e.subAssign(1),e)),kh=eo(([e])=>{const t=oo(e).toConst();return e.addAssign(1),t}),zh=eo(([e])=>{const t=oo(e).toConst();return e.subAssign(1),t});ya("add",fh),ya("sub",yh),ya("mul",bh),ya("div",_h),ya("mod",xh),ya("equal",vh),ya("notEqual",Th),ya("lessThan",Sh),ya("greaterThan",wh),ya("lessThanEqual",Mh),ya("greaterThanEqual",Nh),ya("and",Ah),ya("or",Eh),ya("not",Rh),ya("xor",Ch),ya("bitAnd",Ph),ya("bitNot",Bh),ya("bitOr",Fh),ya("bitXor",Lh),ya("shiftLeft",Dh),ya("shiftRight",Ih),ya("incrementBefore",Oh),ya("decrementBefore",Uh),ya("increment",kh),ya("decrement",zh);ya("modInt",(e,t)=>(bt('TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.',new Bn),xh(oo(e),oo(t))));class Vh extends na{static get type(){return"MathNode"}constructor(e,t,s=null,i=null){if(super(),(e===Vh.MAX||e===Vh.MIN)&&arguments.length>3){let r=new Vh(e,t,s);for(let t=2;t<arguments.length-1;t++)r=new Vh(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),a=e.isMatrix(i)?0:e.getTypeLength(i);return r>n&&r>a?t:n>a?s:a>r?i:t}generateNodeType(e){const t=this.method;return t===Vh.LENGTH||t===Vh.DISTANCE||t===Vh.DOT?"float":t===Vh.CROSS?"vec3":t===Vh.ALL||t===Vh.ANY?"bool":t===Vh.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===Vh.ONE_MINUS)r=yh(1,t);else if(i===Vh.RECIPROCAL)r=_h(1,t);else if(i===Vh.DIFFERENCE)r=fl(yh(t,s));else if(i===Vh.TRANSFORM_DIRECTION){let i=t,n=s;e.isMatrix(i.getNodeType(e))?n=_o(go(n),0):i=_o(go(i),0);const a=bh(i,n).xyz;r=sl(a)}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,a=this.bNode,o=this.cNode,h=e.renderer.coordinateSystem;if(s===Vh.NEGATE)return e.format("( - "+n.build(e,r)+" )",i,t);{const l=[];return s===Vh.CROSS?l.push(n.build(e,i),a.build(e,i)):h===ht&&s===Vh.STEP?l.push(n.build(e,1===e.getTypeLength(n.getNodeType(e))?"float":r),a.build(e,r)):h!==ht||s!==Vh.MIN&&s!==Vh.MAX?s===Vh.REFRACT?l.push(n.build(e,r),a.build(e,r),o.build(e,"float")):s===Vh.MIX?l.push(n.build(e,r),a.build(e,r),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":r)):(h===lt&&s===Vh.ATAN&&null!==a&&(s="atan2"),"fragment"===e.shaderStage||s!==Vh.DFDX&&s!==Vh.DFDY||(bt(`TSL: '${s}' is not supported in the ${e.shaderStage} stage.`,this.stackTrace),s="/*"+s+"*/"),l.push(n.build(e,r)),null!==a&&l.push(a.build(e,r)),null!==o&&l.push(o.build(e,r))):l.push(n.build(e,r),a.build(e,1===e.getTypeLength(a.getNodeType(e))?"float":r)),e.format(`${e.getMethod(s,i)}( ${l.join(", ")} )`,i,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}Vh.ALL="all",Vh.ANY="any",Vh.RADIANS="radians",Vh.DEGREES="degrees",Vh.EXP="exp",Vh.EXP2="exp2",Vh.LOG="log",Vh.LOG2="log2",Vh.SQRT="sqrt",Vh.INVERSE_SQRT="inversesqrt",Vh.FLOOR="floor",Vh.CEIL="ceil",Vh.NORMALIZE="normalize",Vh.FRACT="fract",Vh.SIN="sin",Vh.SINH="sinh",Vh.COS="cos",Vh.COSH="cosh",Vh.TAN="tan",Vh.TANH="tanh",Vh.ASIN="asin",Vh.ASINH="asinh",Vh.ACOS="acos",Vh.ACOSH="acosh",Vh.ATAN="atan",Vh.ATANH="atanh",Vh.ABS="abs",Vh.SIGN="sign",Vh.LENGTH="length",Vh.NEGATE="negate",Vh.ONE_MINUS="oneMinus",Vh.DFDX="dFdx",Vh.DFDY="dFdy",Vh.ROUND="round",Vh.RECIPROCAL="reciprocal",Vh.TRUNC="trunc",Vh.FWIDTH="fwidth",Vh.TRANSPOSE="transpose",Vh.DETERMINANT="determinant",Vh.INVERSE="inverse",Vh.EQUALS="equals",Vh.MIN="min",Vh.MAX="max",Vh.STEP="step",Vh.REFLECT="reflect",Vh.DISTANCE="distance",Vh.DIFFERENCE="difference",Vh.DOT="dot",Vh.CROSS="cross",Vh.POW="pow",Vh.TRANSFORM_DIRECTION="transformDirection",Vh.MIX="mix",Vh.CLAMP="clamp",Vh.REFRACT="refract",Vh.SMOOTHSTEP="smoothstep",Vh.FACEFORWARD="faceforward";const Gh=ao(1e-6),jh=ao(Math.PI),$h=Qa(Vh,Vh.ALL).setParameterLength(1),Wh=Qa(Vh,Vh.ANY).setParameterLength(1),Hh=Qa(Vh,Vh.RADIANS).setParameterLength(1),qh=Qa(Vh,Vh.DEGREES).setParameterLength(1),Xh=Qa(Vh,Vh.EXP).setParameterLength(1),Yh=Qa(Vh,Vh.EXP2).setParameterLength(1),Kh=Qa(Vh,Vh.LOG).setParameterLength(1),Qh=Qa(Vh,Vh.LOG2).setParameterLength(1),Zh=Qa(Vh,Vh.SQRT).setParameterLength(1),Jh=Qa(Vh,Vh.INVERSE_SQRT).setParameterLength(1),el=Qa(Vh,Vh.FLOOR).setParameterLength(1),tl=Qa(Vh,Vh.CEIL).setParameterLength(1),sl=Qa(Vh,Vh.NORMALIZE).setParameterLength(1),il=Qa(Vh,Vh.FRACT).setParameterLength(1),rl=Qa(Vh,Vh.SIN).setParameterLength(1),nl=Qa(Vh,Vh.SINH).setParameterLength(1),al=Qa(Vh,Vh.COS).setParameterLength(1),ol=Qa(Vh,Vh.COSH).setParameterLength(1),hl=Qa(Vh,Vh.TAN).setParameterLength(1),ll=Qa(Vh,Vh.TANH).setParameterLength(1),ul=Qa(Vh,Vh.ASIN).setParameterLength(1),cl=Qa(Vh,Vh.ASINH).setParameterLength(1),dl=Qa(Vh,Vh.ACOS).setParameterLength(1),pl=Qa(Vh,Vh.ACOSH).setParameterLength(1),ml=Qa(Vh,Vh.ATAN).setParameterLength(1,2),gl=Qa(Vh,Vh.ATANH).setParameterLength(1),fl=Qa(Vh,Vh.ABS).setParameterLength(1),yl=Qa(Vh,Vh.SIGN).setParameterLength(1),bl=Qa(Vh,Vh.LENGTH).setParameterLength(1),_l=Qa(Vh,Vh.NEGATE).setParameterLength(1),xl=Qa(Vh,Vh.ONE_MINUS).setParameterLength(1),vl=Qa(Vh,Vh.DFDX).setParameterLength(1),Tl=Qa(Vh,Vh.DFDY).setParameterLength(1),Sl=Qa(Vh,Vh.ROUND).setParameterLength(1),wl=Qa(Vh,Vh.RECIPROCAL).setParameterLength(1),Ml=Qa(Vh,Vh.TRUNC).setParameterLength(1),Nl=Qa(Vh,Vh.FWIDTH).setParameterLength(1),Al=Qa(Vh,Vh.TRANSPOSE).setParameterLength(1),El=Qa(Vh,Vh.DETERMINANT).setParameterLength(1),Rl=Qa(Vh,Vh.INVERSE).setParameterLength(1),Cl=Qa(Vh,Vh.MIN).setParameterLength(2,1/0),Pl=Qa(Vh,Vh.MAX).setParameterLength(2,1/0),Bl=Qa(Vh,Vh.STEP).setParameterLength(2),Fl=Qa(Vh,Vh.REFLECT).setParameterLength(2),Ll=Qa(Vh,Vh.DISTANCE).setParameterLength(2),Dl=Qa(Vh,Vh.DIFFERENCE).setParameterLength(2),Il=Qa(Vh,Vh.DOT).setParameterLength(2),Ol=Qa(Vh,Vh.CROSS).setParameterLength(2),Ul=Qa(Vh,Vh.POW).setParameterLength(2),kl=e=>bh(e,e),zl=e=>bh(e,e,e,e),Vl=Qa(Vh,Vh.TRANSFORM_DIRECTION).setParameterLength(2),Gl=e=>Il(e,e),jl=Qa(Vh,Vh.MIX).setParameterLength(3),$l=(e,t=0,s=1)=>new Vh(Vh.CLAMP,Wa(e),Wa(t),Wa(s)),Wl=e=>$l(e),Hl=Qa(Vh,Vh.REFRACT).setParameterLength(3),ql=Qa(Vh,Vh.SMOOTHSTEP).setParameterLength(3),Xl=Qa(Vh,Vh.FACEFORWARD).setParameterLength(3),Yl=eo(([e])=>{const t=Il(e.xy,uo(12.9898,78.233)),s=xh(t,jh);return il(rl(s).mul(43758.5453))});ya("all",$h),ya("any",Wh),ya("radians",Hh),ya("degrees",qh),ya("exp",Xh),ya("exp2",Yh),ya("log",Kh),ya("log2",Qh),ya("sqrt",Zh),ya("inverseSqrt",Jh),ya("floor",el),ya("ceil",tl),ya("normalize",sl),ya("fract",il),ya("sin",rl),ya("sinh",nl),ya("cos",al),ya("cosh",ol),ya("tan",hl),ya("tanh",ll),ya("asin",ul),ya("asinh",cl),ya("acos",dl),ya("acosh",pl),ya("atan",ml),ya("atanh",gl),ya("abs",fl),ya("sign",yl),ya("length",bl),ya("lengthSq",Gl),ya("negate",_l),ya("oneMinus",xl),ya("dFdx",vl),ya("dFdy",Tl),ya("round",Sl),ya("reciprocal",wl),ya("trunc",Ml),ya("fwidth",Nl),ya("min",Cl),ya("max",Pl),ya("step",(e,t)=>Bl(t,e)),ya("reflect",Fl),ya("distance",Ll),ya("dot",Il),ya("cross",Ol),ya("pow",Ul),ya("pow2",kl),ya("pow3",e=>bh(e,e,e)),ya("pow4",zl),ya("transformDirection",Vl),ya("mix",(e,t,s)=>jl(t,s,e)),ya("clamp",$l),ya("refract",Hl),ya("smoothstep",(e,t,s)=>ql(t,s,e)),ya("faceForward",Xl),ya("difference",Dl),ya("saturate",Wl),ya("cbrt",e=>bh(yl(e),Ul(fl(e),1/3))),ya("transpose",Al),ya("determinant",El),ya("inverse",Rl),ya("rand",Yl);class Kl extends sa{static get type(){return"ConditionalNode"}constructor(e,t,s=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=s}generateNodeType(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,a=e.getNodeProperties(this);a.condNode=t,a.ifNode=n?s:s.context({nodeBlock:s}),a.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:a}=e.getNodeProperties(this),o=e.currentFunctionNode,h="void"!==t,l=h?Ao(s).build(e):"";i.nodeProperty=l;const u=r.build(e,"bool");if(e.context.uniformFlow&&null!==a){const i=n.build(e,s),r=a.build(e,s),o=e.getTernary(u,i,r);return e.format(o,s,t)}e.addFlowCode(`\n${e.tab}if ( ${u} ) {\n\n`).addFlowTab();let c=n.build(e,s);if(c&&(h?c=l+" = "+c+";":(c="return "+c+";",null===o&&(bt("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.",this.stackTrace),c="// "+c))),e.removeFlowTab().addFlowCode(e.tab+"\t"+c+"\n\n"+e.tab+"}"),null!==a){e.addFlowCode(" else {\n\n").addFlowTab();let t=a.build(e,s);t&&(h?t=l+" = "+t+";":(t="return "+t+";",null===o&&(bt("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.",this.stackTrace),t="// "+t))),e.removeFlowTab().addFlowCode(e.tab+"\t"+t+"\n\n"+e.tab+"}\n\n")}else e.addFlowCode("\n\n");return e.format(l,s,t)}}const Ql=Ya(Kl).setParameterLength(2,3);ya("select",Ql);class Zl extends sa{static get type(){return"ContextNode"}constructor(e=null,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}generateNodeType(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 Jl=(e=null,t={})=>{let s=e;return null!==s&&!0===s.isNode||(t=s||t,s=null),new Zl(s,t)},eu=(e,t)=>Jl(e,{nodeName:t});ya("context",Jl),ya("label",function(e,t){return bt('TSL: "label()" has been deprecated. Use "setName()" instead.'),eu(e,t)}),ya("uniformFlow",e=>Jl(e,{uniformFlow:!0})),ya("setName",eu),ya("builtinShadowContext",(e,t,s)=>function(e,t,s=null){return Jl(s,{getShadow:({light:s,shadowColorNode:i})=>t===s?i.mul(e):i})}(t,s,e)),ya("builtinAOContext",(e,t)=>function(e,t=null){return Jl(t,{getAO:(t,{material:s})=>!0===s.transparent?t:null!==t?t.mul(e):e})}(t,e));class tu extends sa{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)}generateNodeType(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 a=!1,o=!1;i&&(a=e.isDeterministic(t),o=n?i:a);const h=this.getNodeType(e);if("void"==h){!0!==this.isIntent(e)&&_t('TSL: ".toVar()" can not be used with void type.',this.stackTrace);return t.build(e)}const l=e.getVectorType(h),u=t.build(e,l),c=e.getVarFromNode(this,s,l,void 0,o),d=e.getPropertyName(c);let p=d;if(o)if(n)p=a?`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 su=Ya(tu);ya("toVar",(e,t=null)=>su(e,t).toStack()),ya("toConst",(e,t=null)=>su(e,t,!0).toStack()),ya("toVarIntent",e=>su(e).setIntent(!0).toStack());class iu extends sa{static get type(){return"SubBuild"}constructor(e,t,s=null){super(s),this.node=e,this.name=t,this.isSubBuildNode=!0}generateNodeType(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 ru=(e,t,s=null)=>new iu(Wa(e),t,s);class nu extends sa{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=ru(e,"VERTEX"),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)}generateNodeType(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,a=this.interpolationSampling;t.varying=s=e.getVaryingFromNode(this,i,r,n,a),t.node=ru(this.node,"VERTEX")}return s.needsInterpolation||(s.needsInterpolation="fragment"===e.shaderStage),s}setup(e){this.setupVarying(e),e.flowNodeFromShaderStage(jn,this.node)}analyze(e){this.setupVarying(e),e.flowNodeFromShaderStage(jn,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,jn);e.flowNodeFromShaderStage(jn,s.node,r,n),s[t]=n}return e.getPropertyName(i)}}const au=Ya(nu).setParameterLength(1,2);ya("toVarying",au),ya("toVertexStage",e=>au(e));const ou=eo(([e])=>{const t=e.mul(.9478672986).add(.0521327014).pow(2.4),s=e.mul(.0773993808),i=e.lessThanEqual(.04045);return jl(t,s,i)}).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),hu=eo(([e])=>{const t=e.pow(.41666).mul(1.055).sub(.055),s=e.mul(12.92),i=e.lessThanEqual(.0031308);return jl(t,s,i)}).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),lu="WorkingColorSpace";class uu extends na{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===lu?Wt.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!==Wt.enabled&&s!==i&&s&&i?(Wt.getTransfer(s)===Ke&&(r=_o(ou(r.rgb),r.a)),Wt.getPrimaries(s)!==Wt.getPrimaries(i)&&(r=_o(wo(Wt._getMatrix(new zt,s,i)).mul(r.rgb),r.a)),Wt.getTransfer(i)===Ke&&(r=_o(hu(r.rgb),r.a)),r):r}}const cu=(e,t)=>new uu(Wa(e),t,lu);ya("workingToColorSpace",(e,t)=>new uu(Wa(e),lu,t)),ya("colorSpaceToWorking",cu);let du=class extends ia{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}generateNodeType(){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 pu extends sa{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=qn}setGroup(e){return this.group=e,this}element(e){return new du(this,Wa(e))}setNodeType(e){const t=uh(null,e);null!==this.group&&t.setGroup(this.group),this.node=t}generateNodeType(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 mu extends pu{static get type(){return"RendererReferenceNode"}constructor(e,t,s=null){super(e,t,s),this.renderer=s,this.setGroup(oh)}updateReference(e){return this.reference=null!==this.renderer?this.renderer:e.renderer,this.reference}}const gu=(e,t,s=null)=>new mu(e,t,s);class fu extends na{static get type(){return"ToneMappingNode"}constructor(e,t=yu,s=null){super("vec3"),this._toneMapping=e,this.exposureNode=t,this.colorNode=s}customCacheKey(){return In(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=_o(r(t.rgb,this.exposureNode),t.a):(_t("ToneMappingNode: Unsupported Tone Mapping configuration.",s),i=t),i}}const yu=gu("toneMappingExposure","float");ya("toneMapping",(e,t,s)=>((e,t,s)=>new fu(e,Wa(t),Wa(s)))(t,s,e));const bu=new WeakMap;function _u(e,t){let s=bu.get(e);return void 0===s&&(s=new Gi(e,t),bu.set(e,s)),s}class xu extends ca{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=at,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){let t;if(0===this.bufferStride&&0===this.bufferOffset){let s=e.globalCache.getData(this.value);void 0===s&&(s={node:this},e.globalCache.setData(this.value,s)),t=s.node.id}else t=this.id;return String(t)}generateNodeType(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 a;a=!0===i.isInterleavedBuffer?i:!0===i.isBufferAttribute?_u(i.array,r):_u(i,r);const o=new $i(a,s,n);a.setUsage(this.usage),this.attribute=o,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=au(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 vu(e,t=null,s=0,i=0,r=35044,n=!1){return"mat3"===t||null===t&&9===e.itemSize?wo(new xu(e,"vec3",9,0).setUsage(r).setInstanced(n),new xu(e,"vec3",9,3).setUsage(r).setInstanced(n),new xu(e,"vec3",9,6).setUsage(r).setInstanced(n)):"mat4"===t||null===t&&16===e.itemSize?Mo(new xu(e,"vec4",16,0).setUsage(r).setInstanced(n),new xu(e,"vec4",16,4).setUsage(r).setInstanced(n),new xu(e,"vec4",16,8).setUsage(r).setInstanced(n),new xu(e,"vec4",16,12).setUsage(r).setInstanced(n)):new xu(e,t,s,i).setUsage(r)}const Tu=(e,t=null,s=0,i=0)=>vu(e,t,s,i),Su=(e,t=null,s=0,i=0)=>vu(e,t,s,i,at,!0),wu=(e,t=null,s=0,i=0)=>vu(e,t,s,i,ot,!0);ya("toAttribute",e=>Tu(e.value));class Mu extends sa{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===Mu.VERTEX)i=e.getVertexIndex();else if(s===Mu.INSTANCE)i=e.getInstanceIndex();else if(s===Mu.DRAW)i=e.getDrawIndex();else if(s===Mu.INVOCATION_LOCAL)i=e.getInvocationLocalIndex();else if(s===Mu.INVOCATION_SUBGROUP)i=e.getInvocationSubgroupIndex();else{if(s!==Mu.SUBGROUP)throw new Error("THREE.IndexNode: Unknown scope: "+s);i=e.getSubgroupIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)r=i;else{r=au(this).build(e,t)}return r}}Mu.VERTEX="vertex",Mu.INSTANCE="instance",Mu.SUBGROUP="subgroup",Mu.INVOCATION_LOCAL="invocationLocal",Mu.INVOCATION_SUBGROUP="invocationSubgroup",Mu.DRAW="draw";const Nu=Ka(Mu,Mu.VERTEX),Au=Ka(Mu,Mu.INSTANCE);Mu.SUBGROUP,Mu.INVOCATION_SUBGROUP,Mu.INVOCATION_LOCAL;const Eu=Ka(Mu,Mu.DRAW);class Ru extends sa{static get type(){return"ComputeNode"}constructor(e,t){super("void"),this.isComputeNode=!0,this.computeNode=e,this.workgroupSize=t,this.count=null,this.dispatchSize=null,this.version=1,this.name="",this.updateBeforeType=qn,this.onInitFunction=null,this.countNode=null}dispose(){this.dispatchEvent({type:"dispose"})}setName(e){return this.name=e,this}label(e){return bt('TSL: "label()" has been deprecated. Use "setName()" instead.',new Bn),this.setName(e)}onInit(e){return this.onInitFunction=e,this}updateBefore({renderer:e}){e.compute(this)}setup(e){null!==this.count&&null===this.countNode&&(this.countNode=uh(this.count,"uint").onObjectUpdate(()=>this.count));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");if(""!==t&&e.addLineFlowCode(t,this),null!==this.count&&!0===e.allowEarlyReturns){const t=this.countNode.build(e,"uint"),s=Au.build(e,"uint");e.flow.code=`${e.tab}if ( ${s} >= ${t} ) { return; }\n\n${e.flow.code}`}}else{const s=e.getNodeProperties(this).outputComputeNode;if(s)return s.build(e,t)}}}const Cu=(e,t=[64])=>{(0===t.length||t.length>3)&&_t("TSL: compute() workgroupSize must have 1, 2, or 3 elements",new Bn);for(let e=0;e<t.length;e++){const s=t[e];("number"!=typeof s||s<=0||!Number.isInteger(s))&&_t(`TSL: compute() workgroupSize element at index [ ${e} ] must be a positive integer`,new Bn)}for(;t.length<3;)t.push(1);return new Ru(Wa(e),t)};ya("compute",(e,t,s)=>{const i=Cu(e,s);return"number"==typeof t?i.count=t:i.dispatchSize=t,i}),ya("computeKernel",Cu);class Pu extends sa{static get type(){return"IsolateNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isIsolateNode=!0}generateNodeType(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 Bu=e=>new Pu(Wa(e));ya("cache",function(e,t=!0){return bt('TSL: "cache()" has been deprecated. Use "isolate()" instead.'),Bu(e).setParent(t)}),ya("isolate",Bu);class Fu extends sa{static get type(){return"BypassNode"}constructor(e,t){super(),this.isBypassNode=!0,this.outputNode=e,this.callNode=t}generateNodeType(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)}}ya("bypass",Ya(Fu).setParameterLength(2));const Lu=eo(([e,t,s,i=ao(0),r=ao(1),n=lo(!1)])=>{let a=e.sub(t).div(s.sub(t));return ja(n)&&(a=a.clamp()),a.mul(r.sub(i)).add(i)});ya("remap",Lu),ya("remapClamp",function(e,t,s,i=ao(0),r=ao(1)){return Lu(e,t,s,i,r,!0)});class Du extends sa{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 Iu=Ya(Du).setParameterLength(1,2);ya("discard",e=>(e?Ql(e,Iu("discard")):Iu("discard")).toStack());class Ou extends na{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)||He;return 0!==s&&(t=t.toneMapping(s)),i!==He&&i!==Wt.workingColorSpace&&(t=t.workingToColorSpace(i)),t}}const Uu=(e,t=null,s=null)=>new Ou(Wa(e),t,s);ya("renderOutput",Uu);class ku extends na{static get type(){return"DebugNode"}constructor(e,t=null){super(),this.node=e,this.callback=t}generateNodeType(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);if(null!==t)t(e,s);else{const t="--- TSL debug - "+e.shaderStage+" shader ---",i="-".repeat(t.length);let r="";r+="// #"+t+"#\n",r+=e.flow.code.replace(/^\t/gm,"")+"\n",r+="/* ... */ "+s+" /* ... */\n",r+="// #"+i+"#\n",ft(r)}return s}}ya("debug",(e,t=null)=>new ku(Wa(e),t).toStack());class zu extends St{constructor(){super(),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 Vu extends sa{static get type(){return"InspectorNode"}constructor(e,t="",s=null){super(),this.node=e,this.name=t,this.callback=s,this.updateType=Wn,this.isInspectorNode=!0}getName(){return this.name||this.node.name}update(e){e.renderer.inspector.inspect(this)}generateNodeType(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!==zu&&xt('TSL: ".toInspector()" is only available with WebGPU.'),t}}ya("toInspector",function(e,t="",s=null){return(e=Wa(e)).before(new Vu(e,t,s))});class Gu extends sa{static get type(){return"AttributeNode"}constructor(e,t=null){super(t),this.global=!0,this._attributeName=e}getHash(e){return this.getAttributeName(e)}generateNodeType(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 au(this).build(e,s)}return bt(`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 ju=(e,t=null)=>new Gu(e,t),$u=(e=0)=>ju("uv"+(e>0?e:""),"vec2");class Wu extends sa{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 Hu=Ya(Wu).setParameterLength(1,2);class qu extends lh{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=Wn}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 Xu=Ya(qu).setParameterLength(1);class Yu extends Error{constructor(e,t=null){super(e),this.name="NodeError",this.stackTrace=t}}const Ku=new ts;class Qu extends lh{static get type(){return"TextureNode"}constructor(e=Ku,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=$n,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}generateNodeType(){return!0===this.value.isDepthTexture?"float":this.value.type===X?"uvec4":this.value.type===q?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return $u(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return null===this._matrixUniform&&(this._matrixUniform=uh(this.value.matrix)),this._matrixUniform.mul(go(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this}setupUV(e,t){return e.isFlipY()&&(null===this._flipYUniform&&(this._flipYUniform=uh(!1)),t=t.toVar(),t=this.sampler?this._flipYUniform.select(t.flipY(),t):this._flipYUniform.select(t.setY(oo(Hu(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 Yu("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().",this.stackTrace);const i=eo(()=>{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?qn:$n,t})();let r=this.levelNode;null===r&&e.context.getTextureLevel&&(r=e.context.getTextureLevel(this));let n=null,a=null;if(null!==this.compareNode)if(e.renderer.hasCompatibility(dt))n=this.compareNode;else{const e=s.compareFunction;null===e||513===e||e===tt||e===st||e===rt?a=this.compareNode:(n=this.compareNode,xt('TSL: Only "LessCompare", "LessEqualCompare", "GreaterCompare" and "GreaterEqualCompare" are supported for depth texture comparison fallback.'))}t.uvNode=i,t.levelNode=r,t.biasNode=this.biasNode,t.compareNode=n,t.compareStepNode=a,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,a,o,h){const l=this.value;let u;return u=r?e.generateTextureBias(l,t,s,r,n,h):o?e.generateTextureGrad(l,t,s,o,n,h):a?e.generateTextureCompare(l,t,s,a,n,h):!1===this.sampler?e.generateTextureLoad(l,t,s,i,n,h):i?e.generateTextureLevel(l,t,s,i,n,h):e.generateTexture(l,t,s,n,h),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),a=this.getNodeType(e);let o=n.propertyName;if(void 0===o){const{uvNode:t,levelNode:h,biasNode:l,compareNode:u,compareStepNode:c,depthNode:d,gradNode:p,offsetNode:m}=i,g=this.generateUV(e,t),f=h?h.build(e,"float"):null,y=l?l.build(e,"float"):null,b=d?d.build(e,"int"):null,_=u?u.build(e,"float"):null,x=c?c.build(e,"float"):null,v=p?[p[0].build(e,"vec2"),p[1].build(e,"vec2")]:null,T=m?this.generateOffset(e,m):null;let S=b;null===S&&s.isArrayTexture&&!0!==this.isTexture3DNode&&(S="0");const w=e.getVarFromNode(this);o=e.getPropertyName(w);let M=this.generateSnippet(e,r,g,f,y,S,_,v,T);if(null!==x){const t=s.compareFunction;M=t===st||t===rt?Bl(Iu(M,a),Iu(x,"float")).build(e,a):Bl(Iu(x,"float"),Iu(M,a)).build(e,a)}e.addLineFlowCode(`${o} = ${M}`,this),n.snippet=M,n.propertyName=o}let h=o;return e.needsToWorkingColorSpace(s)&&(h=cu(Iu(h,a),s.colorSpace).setup(e).build(e,a)),e.format(h,a,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}sample(e){const t=this.clone();return t.uvNode=Wa(e),t.referenceNode=this.getBase(),Wa(t)}load(e){return this.sample(e).setSampler(!1)}blur(e){const t=this.clone();t.biasNode=Wa(e).mul(Xu(t)),t.referenceNode=this.getBase();const s=t.value;return!1===t.generateMipmaps&&(s&&!1===s.generateMipmaps||s.minFilter===O||s.magFilter===O)&&(bt("TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture."),t.biasNode=null),Wa(t)}level(e){const t=this.clone();return t.levelNode=Wa(e),t.referenceNode=this.getBase(),Wa(t)}size(e){return Hu(this,e)}bias(e){const t=this.clone();return t.biasNode=Wa(e),t.referenceNode=this.getBase(),Wa(t)}getBase(){return this.referenceNode?this.referenceNode.getBase():this}compare(e){const t=this.clone();return t.compareNode=Wa(e),t.referenceNode=this.getBase(),Wa(t)}grad(e,t){const s=this.clone();return s.gradNode=[Wa(e),Wa(t)],s.referenceNode=this.getBase(),Wa(s)}depth(e){const t=this.clone();return t.depthNode=Wa(e),t.referenceNode=this.getBase(),Wa(t)}offset(e){const t=this.clone();return t.offsetNode=Wa(e),t.referenceNode=this.getBase(),Wa(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 Zu=Ya(Qu).setParameterLength(1,4).setName("texture"),Ju=(e=Ku,t=null,s=null,i=null)=>{let r;return e&&!0===e.isTextureNode?(r=Wa(e.clone()),r.referenceNode=e.getBase(),null!==t&&(r.uvNode=Wa(t)),null!==s&&(r.levelNode=Wa(s)),null!==i&&(r.biasNode=Wa(i))):r=Zu(e,t,s,i),r},ec=(...e)=>Ju(...e).setSampler(!1);class tc extends lh{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 sc=(e,t,s)=>new tc(e,t,s);class ic extends ia{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),s=this.getNodeType(e),i=this.node.getPaddedType();return e.format(t,i,s)}}class rc extends tc{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=null===t?zn(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=Hn,this.isArrayBufferNode=!0}generateNodeType(){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,this.update(),super.setup(e)}element(e){return new ic(this,Wa(e))}}const nc=(e,t)=>new rc(e,t);const ac=Ya(class extends sa{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}}).setParameterLength(1);let oc,hc;class lc extends sa{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this._output=null,this.isViewportNode=!0}generateNodeType(){return this.scope===lc.DPR?"float":this.scope===lc.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=$n;return this.scope!==lc.SIZE&&this.scope!==lc.VIEWPORT&&this.scope!==lc.DPR||(e=Hn),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===lc.VIEWPORT?null!==t?hc.copy(t.viewport):(e.getViewport(hc),hc.multiplyScalar(e.getPixelRatio())):this.scope===lc.DPR?this._output.value=e.getPixelRatio():null!==t?(oc.width=t.width,oc.height=t.height):e.getDrawingBufferSize(oc)}setup(){const e=this.scope;let t=null;return t=e===lc.SIZE?uh(oc||(oc=new Dt)):e===lc.VIEWPORT?uh(hc||(hc=new ss)):e===lc.DPR?uh(1):uo(pc.div(dc)),this._output=t,t}generate(e){if(this.scope===lc.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const s=e.getNodeProperties(dc).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${s}.y - ${t}.y )`}return t}return super.generate(e)}}lc.COORDINATE="coordinate",lc.VIEWPORT="viewport",lc.SIZE="size",lc.UV="uv",lc.DPR="dpr";const uc=Ka(lc,lc.DPR),cc=Ka(lc,lc.UV),dc=Ka(lc,lc.SIZE),pc=Ka(lc,lc.COORDINATE),mc=Ka(lc,lc.VIEWPORT),gc=mc.zw;mc.xy;let fc=null,yc=null,bc=null,_c=null,xc=null,vc=null,Tc=null,Sc=null;const wc=uh(0,"uint").setName("u_cameraIndex").setGroup(ah("cameraIndex")).toVarying("v_cameraIndex"),Mc=uh("float").setName("cameraNear").setGroup(oh).onRenderUpdate(({camera:e})=>e.near),Nc=uh("float").setName("cameraFar").setGroup(oh).onRenderUpdate(({camera:e})=>e.far),Ac=eo(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(const t of e.cameras)s.push(t.projectionMatrix);null===yc?yc=nc(s).setGroup(oh).setName("cameraProjectionMatrices"):yc.array=s,t=yc.element(e.isMultiViewCamera?ac("gl_ViewID_OVR"):wc).toConst("cameraProjectionMatrix")}else null===fc&&(fc=uh(e.projectionMatrix).setName("cameraProjectionMatrix").setGroup(oh).onRenderUpdate(({camera:e})=>e.projectionMatrix)),t=fc;return t}).once()(),Ec=eo(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(const t of e.cameras)s.push(t.projectionMatrixInverse);null===_c?_c=nc(s).setGroup(oh).setName("cameraProjectionMatricesInverse"):_c.array=s,t=_c.element(e.isMultiViewCamera?ac("gl_ViewID_OVR"):wc).toConst("cameraProjectionMatrixInverse")}else null===bc&&(bc=uh(e.projectionMatrixInverse).setName("cameraProjectionMatrixInverse").setGroup(oh).onRenderUpdate(({camera:e})=>e.projectionMatrixInverse)),t=bc;return t}).once()(),Rc=eo(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(const t of e.cameras)s.push(t.matrixWorldInverse);null===vc?vc=nc(s).setGroup(oh).setName("cameraViewMatrices"):vc.array=s,t=vc.element(e.isMultiViewCamera?ac("gl_ViewID_OVR"):wc).toConst("cameraViewMatrix")}else null===xc&&(xc=uh(e.matrixWorldInverse).setName("cameraViewMatrix").setGroup(oh).onRenderUpdate(({camera:e})=>e.matrixWorldInverse)),t=xc;return t}).once()(),Cc=eo(({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 Ot);null===Sc?Sc=nc(s).setGroup(oh).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)}):Sc.array=s,t=Sc.element(e.isMultiViewCamera?ac("gl_ViewID_OVR"):wc).toConst("cameraPosition")}else null===Tc&&(Tc=uh(new Ot).setName("cameraPosition").setGroup(oh).onRenderUpdate(({camera:e},t)=>t.value.setFromMatrixPosition(e.matrixWorld))),t=Tc;return t}).once()(),Pc=new Fi;class Bc extends sa{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=qn,this.uniformNode=new lh(null)}generateNodeType(){const e=this.scope;return e===Bc.WORLD_MATRIX?"mat4":e===Bc.POSITION||e===Bc.VIEW_POSITION||e===Bc.DIRECTION||e===Bc.SCALE?"vec3":e===Bc.RADIUS?"float":void 0}update(e){const t=this.object3d,s=this.uniformNode,i=this.scope;if(i===Bc.WORLD_MATRIX)s.value=t.matrixWorld;else if(i===Bc.POSITION)s.value=s.value||new Ot,s.value.setFromMatrixPosition(t.matrixWorld);else if(i===Bc.SCALE)s.value=s.value||new Ot,s.value.setFromMatrixScale(t.matrixWorld);else if(i===Bc.DIRECTION)s.value=s.value||new Ot,t.getWorldDirection(s.value);else if(i===Bc.VIEW_POSITION){const i=e.camera;s.value=s.value||new Ot,s.value.setFromMatrixPosition(t.matrixWorld),s.value.applyMatrix4(i.matrixWorldInverse)}else if(i===Bc.RADIUS){const i=e.object.geometry;null===i.boundingSphere&&i.computeBoundingSphere(),Pc.copy(i.boundingSphere).applyMatrix4(t.matrixWorld),s.value=Pc.radius}}generate(e){const t=this.scope;return t===Bc.WORLD_MATRIX?this.uniformNode.nodeType="mat4":t===Bc.POSITION||t===Bc.VIEW_POSITION||t===Bc.DIRECTION||t===Bc.SCALE?this.uniformNode.nodeType="vec3":t===Bc.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}}Bc.WORLD_MATRIX="worldMatrix",Bc.POSITION="position",Bc.SCALE="scale",Bc.VIEW_POSITION="viewPosition",Bc.DIRECTION="direction",Bc.RADIUS="radius";class Fc extends Bc{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const Lc=Ka(Fc,Fc.WORLD_MATRIX),Dc=uh(new zt).onObjectUpdate(({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld)),Ic=eo(e=>e.context.modelViewMatrix||Oc).once()().toVar("modelViewMatrix"),Oc=Rc.mul(Lc),Uc=eo(e=>(e.context.isHighPrecisionModelViewMatrix=!0,uh("mat4").onObjectUpdate(({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld)))).once()().toVar("highpModelViewMatrix"),kc=eo(e=>{const t=e.context.isHighPrecisionModelViewMatrix;return uh("mat3").onObjectUpdate(({object:e,camera:s})=>(!0!==t&&e.modelViewMatrix.multiplyMatrices(s.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix)))}).once()().toVar("highpModelNormalViewMatrix"),zc=eo(e=>"fragment"!==e.shaderStage?(xt("TSL: `clipSpace` is only available in fragment stage."),_o()):e.context.clipSpace.toVarying("v_clipSpace")).once()(),Vc=ju("position","vec3"),Gc=Vc.toVarying("positionLocal"),jc=Vc.toVarying("positionPrevious"),$c=eo(e=>Lc.mul(Gc).xyz.toVarying(e.getSubBuildProperty("v_positionWorld")),"vec3").once(["POSITION"])(),Wc=eo(()=>Gc.transformDirection(Lc).toVarying("v_positionWorldDirection").normalize().toVar("positionWorldDirection"),"vec3").once(["POSITION"])(),Hc=eo(e=>{if("fragment"===e.shaderStage&&e.material.vertexNode){const e=Ec.mul(zc);return e.xyz.div(e.w).toVar("positionView")}return e.context.setupPositionView().toVarying("v_positionView")},"vec3").once(["POSITION","VERTEX"])(),qc=eo(e=>{let t;return t=e.camera.isOrthographicCamera?go(0,0,1):Hc.negate().toVarying("v_positionViewDirection").normalize(),t.toVar("positionViewDirection")},"vec3").once(["POSITION"])();class Xc extends sa{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 Yc=ao(Ka(Xc)).mul(2).sub(1),Kc=eo(([e],{material:t})=>{const s=t.side;return 1===s?e=e.mul(-1):2===s&&(e=e.mul(Yc)),e}),Qc=ju("normal","vec3"),Zc=eo(e=>!1===e.geometry.hasAttribute("normal")?(bt('TSL: Vertex attribute "normal" not found on geometry.'),go(0,1,0)):Qc,"vec3").once()().toVar("normalLocal"),Jc=Hc.dFdx().cross(Hc.dFdy()).normalize().toVar("normalFlat"),ed=eo(e=>{let t;return t=e.isFlatShading()?Jc:ad(Zc).toVarying("v_normalViewGeometry").normalize(),t},"vec3").once()().toVar("normalViewGeometry"),td=eo(e=>{let t=ed.transformDirection(Rc);return!0!==e.isFlatShading()&&(t=t.toVarying("v_normalWorldGeometry")),t.normalize().toVar("normalWorldGeometry")},"vec3").once()(),sd=eo(e=>{let t;return"NORMAL"===e.subBuildFn||"VERTEX"===e.subBuildFn?(t=ed,!0!==e.isFlatShading()&&(t=Kc(t))):t=e.context.setupNormal().context({getUV:null,getTextureLevel:null}),t},"vec3").once(["NORMAL","VERTEX"])().toVar("normalView"),id=sd.transformDirection(Rc).toVar("normalWorld"),rd=eo(({subBuildFn:e,context:t})=>{let s;return s="NORMAL"===e||"VERTEX"===e?sd:t.setupClearcoatNormal().context({getUV:null,getTextureLevel:null}),s},"vec3").once(["NORMAL","VERTEX"])().toVar("clearcoatNormalView"),nd=eo(([e,t=Lc])=>{const s=wo(t),i=e.div(go(s[0].dot(s[0]),s[1].dot(s[1]),s[2].dot(s[2])));return s.mul(i).xyz}),ad=eo(([e],t)=>{const s=t.context.modelNormalViewMatrix;if(s)return s.transformDirection(e);const i=Dc.mul(e);return Rc.transformDirection(i)});eo(()=>(bt('TSL: "transformedNormalView" is deprecated. Use "normalView" instead.'),sd)).once(["NORMAL","VERTEX"])(),eo(()=>(bt('TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.'),id)).once(["NORMAL","VERTEX"])(),eo(()=>(bt('TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.'),rd)).once(["NORMAL","VERTEX"])();const od=new ns,hd=uh(0).onReference(({material:e})=>e).onObjectUpdate(({material:e})=>e.refractionRatio),ld=uh(1).onReference(({material:e})=>e).onObjectUpdate(function({material:e,scene:t}){return e.envMap?e.envMapIntensity:t.environmentIntensity}),ud=uh(new ns).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?od.makeRotationFromEuler(s).transpose():od.identity(),od}),cd=qc.negate().reflect(sd),dd=qc.negate().refract(sd,hd),pd=cd.transformDirection(Rc).toVar("reflectVector"),md=dd.transformDirection(Rc).toVar("reflectVector"),gd=new Br;class fd extends Qu{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===B?pd:e.mapping===F?md:(_t('CubeTextureNode: Mapping "%s" not supported.',e.mapping),go(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const s=this.value;return!0===s.isDepthTexture?e.renderer.coordinateSystem===lt?go(t.x,t.y.negate(),t.z):t:(t=ud.mul(t),e.renderer.coordinateSystem!==lt&&s.isRenderTargetTexture||(t=go(t.x.negate(),t.yz)),t)}generateUV(e,t){return t.build(e,!0===this.sampler?"vec3":"ivec3")}}const yd=Ya(fd).setParameterLength(1,4).setName("cubeTexture"),bd=(e=gd,t=null,s=null,i=null)=>{let r;return e&&!0===e.isCubeTextureNode?(r=Wa(e.clone()),r.referenceNode=e,null!==t&&(r.uvNode=Wa(t)),null!==s&&(r.levelNode=Wa(s)),null!==i&&(r.biasNode=Wa(i))):r=yd(e,t,s,i),r};class _d extends ia{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}generateNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),s=this.referenceNode.getNodeType(e),i=this.getNodeType(e);return e.format(t,s,i)}}class xd extends sa{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=qn}element(e){return new _d(this,Wa(e))}setGroup(e){return this.group=e,this}setName(e){return this.name=e,this}label(e){return bt('TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}setNodeType(e){let t=null;t=null!==this.count?sc(null,e,this.count):Array.isArray(this.getValueFromReference())?nc(null,e):"texture"===e?Ju(null):"cubeTexture"===e?bd(null):uh(null,e),null!==this.group&&t.setGroup(this.group),null!==this.name&&t.setName(this.name),this.node=t}generateNodeType(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 vd=(e,t,s)=>new xd(e,t,s),Td=(e,t,s,i)=>new xd(e,t,i,s);class Sd extends xd{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 wd=(e,t,s=null)=>new Sd(e,t,s),Md=$u(),Nd=Hc.dFdx(),Ad=Hc.dFdy(),Ed=Md.dFdx(),Rd=Md.dFdy(),Cd=sd,Pd=Ad.cross(Cd),Bd=Cd.cross(Nd),Fd=Pd.mul(Ed.x).add(Bd.mul(Rd.x)),Ld=Pd.mul(Ed.y).add(Bd.mul(Rd.y)),Dd=Fd.dot(Fd).max(Ld.dot(Ld)),Id=Dd.equal(0).select(0,Dd.inverseSqrt()),Od=Fd.mul(Id).toVar("tangentViewFrame"),Ud=Ld.mul(Id).toVar("bitangentViewFrame"),kd=ju("tangent","vec4"),zd=kd.xyz.toVar("tangentLocal"),Vd=eo(e=>{let t;return t="VERTEX"===e.subBuildFn||e.geometry.hasAttribute("tangent")?Ic.mul(_o(zd,0)).xyz.toVarying("v_tangentView").normalize():Od,!0!==e.isFlatShading()&&(t=Kc(t)),t},"vec3").once(["NORMAL","VERTEX"])().toVar("tangentView"),Gd=eo(([e,t],s)=>{let i=e.mul(kd.w).xyz;return"NORMAL"===s.subBuildFn&&!0!==s.isFlatShading()&&(i=i.toVarying(t)),i}).once(["NORMAL"]),jd=wo(Vd,eo(e=>{let t;return t="VERTEX"===e.subBuildFn||e.geometry.hasAttribute("tangent")?Gd(sd.cross(Vd),"v_bitangentView").normalize():Ud,!0!==e.isFlatShading()&&(t=Kc(t)),t},"vec3").once(["NORMAL","VERTEX"])().toVar("bitangentView"),sd).toVar("TBNViewMatrix"),$d=eo(()=>{let e=$o.cross(qc);return e=e.cross($o).normalize(),e=jl(e,sd,Go.mul(Bo.oneMinus()).oneMinus().pow2().pow2()).normalize(),e}).once()(),Wd=e=>go(e,Zh(Wl(ao(1).sub(Il(e,e)))));class Hd extends na{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=0,this.unpackNormalMode=""}setup(e){const{normalMapType:t,scaleNode:s,unpackNormalMode:i}=this;let r=this.node.mul(2).sub(1);if(0===t?"rg"===i?r=Wd(r.xy):"ga"===i?r=Wd(r.yw):""!==i&&_t(`THREE.NodeMaterial: Unexpected unpack normal mode: ${i}`):""!==i&&_t(`THREE.NodeMaterial: Normal map type '${t}' is not compatible with unpack normal mode '${i}'`),null!==s){let t=s;!0===e.isFlatShading()&&(t=Kc(t)),r=go(r.xy.mul(t),r.z)}let n=null;return 1===t?n=ad(r):0===t?n=jd.mul(r).normalize():(_t(`NodeMaterial: Unsupported normal map type: ${t}`),n=sd),n}}const qd=Ya(Hd).setParameterLength(1,2),Xd=eo(({textureNode:e,bumpScale:t})=>{const s=t=>e.isolate().context({getUV:e=>t(e.uvNode||$u()),forceUVContext:!0}),i=ao(s(e=>e));return uo(ao(s(e=>e.add(e.dFdx()))).sub(i),ao(s(e=>e.add(e.dFdy()))).sub(i)).mul(t)}),Yd=eo(e=>{const{surf_pos:t,surf_norm:s,dHdxy:i}=e,r=t.dFdx().normalize(),n=s,a=t.dFdy().normalize().cross(n),o=n.cross(r),h=r.dot(a).mul(Yc),l=h.sign().mul(i.x.mul(a).add(i.y.mul(o)));return h.abs().mul(s).sub(l).normalize()});class Kd extends na{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=Xd({textureNode:this.textureNode,bumpScale:e});return Yd({surf_pos:Hc,surf_norm:sd,dHdxy:t})}}const Qd=Ya(Kd).setParameterLength(1,2),Zd=new Map;class Jd extends sa{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let s=Zd.get(e);return void 0===s&&(s=wd(e,t),Zd.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===Jd.COLOR){const e=void 0!==t.color?this.getColor(s):go();i=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(s===Jd.OPACITY){const e=this.getFloat(s);i=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(s===Jd.SPECULAR_STRENGTH)i=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture("specular").r:ao(1);else if(s===Jd.SPECULAR_INTENSITY){const e=this.getFloat(s);i=t.specularIntensityMap&&!0===t.specularIntensityMap.isTexture?e.mul(this.getTexture(s).a):e}else if(s===Jd.SPECULAR_COLOR){const e=this.getColor(s);i=t.specularColorMap&&!0===t.specularColorMap.isTexture?e.mul(this.getTexture(s).rgb):e}else if(s===Jd.ROUGHNESS){const e=this.getFloat(s);i=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(s).g):e}else if(s===Jd.METALNESS){const e=this.getFloat(s);i=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(s).b):e}else if(s===Jd.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===Jd.NORMAL)t.normalMap?(i=qd(this.getTexture("normal"),this.getCache("normalScale","vec2")),i.normalMapType=t.normalMapType,t.normalMap.format!=le&&t.normalMap.format!=$e&&t.normalMap.format!=Me||(i.unpackNormalMode="rg")):i=t.bumpMap?Qd(this.getTexture("bump").r,this.getFloat("bumpScale")):sd;else if(s===Jd.CLEARCOAT){const e=this.getFloat(s);i=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(s).r):e}else if(s===Jd.CLEARCOAT_ROUGHNESS){const e=this.getFloat(s);i=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(s).r):e}else if(s===Jd.CLEARCOAT_NORMAL)i=t.clearcoatNormalMap?qd(this.getTexture(s),this.getCache(s+"Scale","vec2")):sd;else if(s===Jd.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===Jd.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===Jd.ANISOTROPY)if(t.anisotropyMap&&!0===t.anisotropyMap.isTexture){const e=this.getTexture(s);i=So(Ip.x,Ip.y,Ip.y.negate(),Ip.x).mul(e.rg.mul(2).sub(uo(1)).normalize().mul(e.b))}else i=Ip;else if(s===Jd.IRIDESCENCE_THICKNESS){const e=vd("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const r=vd("0","float",t.iridescenceThicknessRange);i=e.sub(r).mul(this.getTexture(s).g).add(r)}else i=e}else if(s===Jd.TRANSMISSION){const e=this.getFloat(s);i=t.transmissionMap?e.mul(this.getTexture(s).r):e}else if(s===Jd.THICKNESS){const e=this.getFloat(s);i=t.thicknessMap?e.mul(this.getTexture(s).g):e}else if(s===Jd.IOR)i=this.getFloat(s);else if(s===Jd.LIGHT_MAP)i=this.getTexture(s).rgb.mul(this.getFloat("lightMapIntensity"));else if(s===Jd.AO)i=this.getTexture(s).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1);else if(s===Jd.LINE_DASH_OFFSET)i=t.dashOffset?this.getFloat(s):ao(0);else{const t=this.getNodeType(e);i=this.getCache(s,t)}return i}}Jd.ALPHA_TEST="alphaTest",Jd.COLOR="color",Jd.OPACITY="opacity",Jd.SHININESS="shininess",Jd.SPECULAR="specular",Jd.SPECULAR_STRENGTH="specularStrength",Jd.SPECULAR_INTENSITY="specularIntensity",Jd.SPECULAR_COLOR="specularColor",Jd.REFLECTIVITY="reflectivity",Jd.ROUGHNESS="roughness",Jd.METALNESS="metalness",Jd.NORMAL="normal",Jd.CLEARCOAT="clearcoat",Jd.CLEARCOAT_ROUGHNESS="clearcoatRoughness",Jd.CLEARCOAT_NORMAL="clearcoatNormal",Jd.EMISSIVE="emissive",Jd.ROTATION="rotation",Jd.SHEEN="sheen",Jd.SHEEN_ROUGHNESS="sheenRoughness",Jd.ANISOTROPY="anisotropy",Jd.IRIDESCENCE="iridescence",Jd.IRIDESCENCE_IOR="iridescenceIOR",Jd.IRIDESCENCE_THICKNESS="iridescenceThickness",Jd.IOR="ior",Jd.TRANSMISSION="transmission",Jd.THICKNESS="thickness",Jd.ATTENUATION_DISTANCE="attenuationDistance",Jd.ATTENUATION_COLOR="attenuationColor",Jd.LINE_SCALE="scale",Jd.LINE_DASH_SIZE="dashSize",Jd.LINE_GAP_SIZE="gapSize",Jd.LINE_WIDTH="linewidth",Jd.LINE_DASH_OFFSET="dashOffset",Jd.POINT_SIZE="size",Jd.DISPERSION="dispersion",Jd.LIGHT_MAP="light",Jd.AO="ao";const ep=Ka(Jd,Jd.ALPHA_TEST),tp=Ka(Jd,Jd.COLOR),sp=Ka(Jd,Jd.SHININESS),ip=Ka(Jd,Jd.EMISSIVE),rp=Ka(Jd,Jd.OPACITY),np=Ka(Jd,Jd.SPECULAR),ap=Ka(Jd,Jd.SPECULAR_INTENSITY),op=Ka(Jd,Jd.SPECULAR_COLOR),hp=Ka(Jd,Jd.SPECULAR_STRENGTH),lp=Ka(Jd,Jd.REFLECTIVITY),up=Ka(Jd,Jd.ROUGHNESS),cp=Ka(Jd,Jd.METALNESS),dp=Ka(Jd,Jd.NORMAL),pp=Ka(Jd,Jd.CLEARCOAT),mp=Ka(Jd,Jd.CLEARCOAT_ROUGHNESS),gp=Ka(Jd,Jd.CLEARCOAT_NORMAL),fp=Ka(Jd,Jd.ROTATION),yp=Ka(Jd,Jd.SHEEN),bp=Ka(Jd,Jd.SHEEN_ROUGHNESS),_p=Ka(Jd,Jd.ANISOTROPY),xp=Ka(Jd,Jd.IRIDESCENCE),vp=Ka(Jd,Jd.IRIDESCENCE_IOR),Tp=Ka(Jd,Jd.IRIDESCENCE_THICKNESS),Sp=Ka(Jd,Jd.TRANSMISSION),wp=Ka(Jd,Jd.THICKNESS),Mp=Ka(Jd,Jd.IOR),Np=Ka(Jd,Jd.ATTENUATION_DISTANCE),Ap=Ka(Jd,Jd.ATTENUATION_COLOR),Ep=Ka(Jd,Jd.LINE_SCALE),Rp=Ka(Jd,Jd.LINE_DASH_SIZE),Cp=Ka(Jd,Jd.LINE_GAP_SIZE);Jd.LINE_WIDTH;const Pp=Ka(Jd,Jd.LINE_DASH_OFFSET),Bp=Ka(Jd,Jd.POINT_SIZE),Fp=Ka(Jd,Jd.DISPERSION),Lp=Ka(Jd,Jd.LIGHT_MAP),Dp=Ka(Jd,Jd.AO),Ip=uh(new Dt).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))}),Op=eo(e=>e.context.setupModelViewProjection(),"vec4").once()().toVarying("v_modelViewProjection");class Up extends ia{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 kp=Ya(Up).setParameterLength(2);class zp extends tc{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=kn(e.itemSize),s=e.count):i=t,super(e,i,s),this.isStorageBufferNode=!0,this.structTypeNode=r,this.access=Kn,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){let t;if(0===this.bufferCount){let s=e.globalCache.getData(this.value);void 0===s&&(s={node:this},e.globalCache.setData(this.value,s)),t=s.node.id}else t=this.id;return String(t)}getInputType(){return this.value.isIndirectStorageBufferAttribute?"indirectStorageBuffer":"storageBuffer"}element(e){return kp(this,e)}setPBO(e){return this.isPBO=e,this}getPBO(){return this.isPBO}setAccess(e){return this.access=e,this}toReadOnly(){return this.setAccess(Xn)}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getAttributeData(){return null===this._attribute&&(this._attribute=Tu(this.value),this._varying=au(this._attribute)),{attribute:this._attribute,varying:this._varying}}generateNodeType(e){if(null!==this.structTypeNode)return this.structTypeNode.getNodeType(e);if(e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.generateNodeType(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 Vp=(e,t=null,s=0)=>new zp(e,t,s);class Gp extends sa{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=Wn,this.buffer=null,this.bufferColor=null,this.previousInstanceMatrixNode=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){let{instanceMatrixNode:t,instanceColorNode:s}=this;null===t&&(t=this._createInstanceMatrixNode(!0,e),this.instanceMatrixNode=t);const{instanceColor:i,isStorageColor:r}=this;if(i&&null===s){if(r)s=Vp(i,"vec3",Math.max(i.count,1)).element(Au);else{const e=new yr(i.array,3),t=i.usage===ot?wu:Su;this.bufferColor=e,s=go(t(e,"vec3",3,0))}this.instanceColorNode=s}const n=t.mul(Gc).xyz;if(Gc.assign(n),e.needsPreviousData()&&jc.assign(this.getPreviousInstancedPosition(e)),e.hasGeometryAttribute("normal")){const e=nd(Zc,t);Zc.assign(e)}null!==this.instanceColorNode&&Eo("vec3","vInstanceColor").assign(this.instanceColorNode)}update(e){null!==this.buffer&&!0!==this.isStorageMatrix&&(this.buffer.clearUpdateRanges(),this.buffer.updateRanges.push(...this.instanceMatrix.updateRanges),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.version!==this.bufferColor.version&&(this.bufferColor.version=this.instanceColor.version)),null!==this.previousInstanceMatrixNode&&e.object.previousInstanceMatrix.array.set(this.instanceMatrix.array)}getPreviousInstancedPosition(e){const t=e.object;return null===this.previousInstanceMatrixNode&&(t.previousInstanceMatrix=this.instanceMatrix.clone(),this.previousInstanceMatrixNode=this._createInstanceMatrixNode(!1,e)),this.previousInstanceMatrixNode.mul(jc).xyz}_createInstanceMatrixNode(e,t){let s;const{instanceMatrix:i}=this,{count:r}=i;if(this.isStorageMatrix)s=Vp(i,"mat4",Math.max(r,1)).element(Au);else{if(16*r*4<=t.getUniformBufferLimit())s=sc(i.array,"mat4",Math.max(r,1)).element(Au);else{const t=new Sn(i.array,16,1);!0===e&&(this.buffer=t);const r=i.usage===ot?wu:Su,n=[r(t,"vec4",16,0),r(t,"vec4",16,4),r(t,"vec4",16,8),r(t,"vec4",16,12)];s=Mo(...n)}}return s}}class jp extends Gp{static get type(){return"InstancedMeshNode"}constructor(e){const{count:t,instanceMatrix:s,instanceColor:i}=e;super(t,s,i),this.instancedMesh=e}}const $p=Ya(jp).setParameterLength(1);class Wp extends sa{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=Au:this.batchingIdNode=Eu);const t=eo(([e])=>{const t=oo(Hu(ec(this.batchMesh._indirectTexture),0).x).toConst(),s=oo(e).mod(t).toConst(),i=oo(e).div(t).toConst();return ec(this.batchMesh._indirectTexture,co(s,i)).x}).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]}),s=t(oo(this.batchingIdNode)),i=this.batchMesh._matricesTexture,r=oo(Hu(ec(i),0).x).toConst(),n=ao(s).mul(4).toInt().toConst(),a=n.mod(r).toConst(),o=n.div(r).toConst(),h=Mo(ec(i,co(a,o)),ec(i,co(a.add(1),o)),ec(i,co(a.add(2),o)),ec(i,co(a.add(3),o))),l=this.batchMesh._colorsTexture;if(null!==l){const e=eo(([e])=>{const t=oo(Hu(ec(l),0).x).toConst(),s=e,i=s.mod(t).toConst(),r=s.div(t).toConst();return ec(l,co(i,r)).rgb}).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]}),t=e(s);Eo("vec3","vBatchColor").assign(t)}const u=wo(h);Gc.assign(h.mul(Gc));const c=Zc.div(go(u[0].dot(u[0]),u[1].dot(u[1]),u[2].dot(u[2]))),d=u.mul(c).xyz;Zc.assign(d),e.hasGeometryAttribute("tangent")&&zd.mulAssign(u)}}const Hp=Ya(Wp).setParameterLength(1),qp=new WeakMap;class Xp extends sa{static get type(){return"SkinningNode"}constructor(e){super("void"),this.skinnedMesh=e,this.updateType=qn,this.skinIndexNode=ju("skinIndex","uvec4"),this.skinWeightNode=ju("skinWeight","vec4"),this.bindMatrixNode=vd("bindMatrix","mat4"),this.bindMatrixInverseNode=vd("bindMatrixInverse","mat4"),this.boneMatricesNode=Td("skeleton.boneMatrices","mat4",e.skeleton.bones.length),this.positionNode=Gc,this.toPositionNode=Gc,this.previousBoneMatricesNode=null}getSkinnedPosition(e=this.boneMatricesNode,t=this.positionNode){const{skinIndexNode:s,skinWeightNode:i,bindMatrixNode:r,bindMatrixInverseNode:n}=this,a=e.element(s.x),o=e.element(s.y),h=e.element(s.z),l=e.element(s.w),u=r.mul(t),c=fh(a.mul(i.x).mul(u),o.mul(i.y).mul(u),h.mul(i.z).mul(u),l.mul(i.w).mul(u));return n.mul(c).xyz}getSkinnedNormalAndTangent(e=this.boneMatricesNode,t=Zc,s=zd){const{skinIndexNode:i,skinWeightNode:r,bindMatrixNode:n,bindMatrixInverseNode:a}=this,o=e.element(i.x),h=e.element(i.y),l=e.element(i.z),u=e.element(i.w);let c=fh(r.x.mul(o),r.y.mul(h),r.z.mul(l),r.w.mul(u));c=a.mul(c).mul(n);return{skinNormal:c.transformDirection(t).xyz,skinTangent:c.transformDirection(s).xyz}}getPreviousSkinnedPosition(e){const t=e.object;return null===this.previousBoneMatricesNode&&(t.skeleton.previousBoneMatrices=new Float32Array(t.skeleton.boneMatrices),this.previousBoneMatricesNode=Td("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,jc)}setup(e){e.needsPreviousData()&&jc.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(this.toPositionNode&&this.toPositionNode.assign(t),e.hasGeometryAttribute("normal")){const{skinNormal:t,skinTangent:s}=this.getSkinnedNormalAndTangent();Zc.assign(t),e.hasGeometryAttribute("tangent")&&zd.assign(s)}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;qp.get(t)!==e.frameId&&(qp.set(t,e.frameId),null!==this.previousBoneMatricesNode&&(null===t.previousBoneMatrices&&(t.previousBoneMatrices=new Float32Array(t.boneMatrices)),t.previousBoneMatrices.set(t.boneMatrices)),t.update())}}class Yp extends sa{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]=Iu(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=eo(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,a=!1,o=null,h=null,l=null,u=null,c=null,d=null;if(r.isNode?"bool"===r.getNodeType(e)?(a=!0,u="bool",h=r.build(e,u)):(u="int",l=this.getVarName(i),o="0",h=r.build(e,u),c="<"):(u=r.type||"int",l=r.name||this.getVarName(i),o=r.start,h=r.end,c=r.condition,d=r.update,"number"==typeof o?o=e.generateConst(u,o):o&&o.isNode&&(o=o.build(e,u)),"number"==typeof h?h=e.generateConst(u,h):h&&h.isNode&&(h=h.build(e,u)),void 0!==o&&void 0===h?(o+=" - 1",h="0",c=">="):void 0!==h&&void 0===o&&(o="0",c="<"),void 0===c&&(c=Number(o)>Number(h)?">=":"<")),a)n=`while ( ${h} )`;else{const s={start:o,end:h},i=s.start,r=s.end;let a;const p=()=>c.includes("<")?"+=":"-=";if(null!=d)switch(typeof d){case"function":a=e.flowStagesNode(t.updateNode,"void").code.replace(/\t|;/g,"");break;case"number":a=l+" "+p()+" "+e.generateConst(u,d);break;case"string":a=l+" "+d;break;default:d.isNode?a=l+" "+p()+" "+d.build(e):(_t("TSL: 'Loop( { update: ... } )' is not a function, string or number.",this.stackTrace),a="break /* invalid update */")}else d="int"===u||"uint"===u?c.includes("<")?"++":"--":p()+" 1.",a=l+" "+d;n=`for ( ${e.getVar(u,l)+" = "+i}; ${l+" "+c+" "+r}; ${a} )`}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 Kp=(...e)=>new Yp(Xa(e,"int")).toStack(),Qp=new WeakMap,Zp=new ss,Jp=eo(({bufferMap:e,influence:t,stride:s,width:i,depth:r,offset:n})=>{const a=oo(Nu).mul(s).add(n),o=a.div(i),h=a.sub(o.mul(i));return ec(e,co(h,o)).depth(r).xyz.mul(t)});class em extends sa{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=uh(1),this.updateType=qn}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:a,stride:o,size:h}=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 a=Qp.get(e);if(void 0===a||a.count!==n){void 0!==a&&a.texture.dispose();const o=e.morphAttributes.position||[],h=e.morphAttributes.normal||[],l=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),g=new rs(m,c,d,n);g.type=Y,g.needsUpdate=!0;const f=4*u;for(let b=0;b<n;b++){const _=o[b],x=h[b],v=l[b],T=c*d*4*b;for(let S=0;S<_.count;S++){const w=S*f;!0===t&&(Zp.fromBufferAttribute(_,S),m[T+w+0]=Zp.x,m[T+w+1]=Zp.y,m[T+w+2]=Zp.z,m[T+w+3]=0),!0===s&&(Zp.fromBufferAttribute(x,S),m[T+w+4]=Zp.x,m[T+w+5]=Zp.y,m[T+w+6]=Zp.z,m[T+w+7]=0),!0===i&&(Zp.fromBufferAttribute(v,S),m[T+w+8]=Zp.x,m[T+w+9]=Zp.y,m[T+w+10]=Zp.z,m[T+w+11]=4===v.itemSize?Zp.w:1)}}function y(){g.dispose(),Qp.delete(e),e.removeEventListener("dispose",y)}a={count:n,texture:g,stride:u,size:new Dt(c,d)},Qp.set(e,a),e.addEventListener("dispose",y)}return a}(t);!0===s&&Gc.mulAssign(this.morphBaseInfluence),!0===i&&Zc.mulAssign(this.morphBaseInfluence);const l=oo(h.width);Kp(n,({i:e})=>{const t=ao(0).toVar();this.mesh.count>1&&null!==this.mesh.morphTexture&&void 0!==this.mesh.morphTexture?t.assign(ec(this.mesh.morphTexture,co(oo(e).add(1),oo(Au))).r):t.assign(vd("morphTargetInfluences","float").element(e).toVar()),io(t.notEqual(0),()=>{!0===s&&Gc.addAssign(Jp({bufferMap:a,influence:t,stride:o,width:l,depth:e,offset:oo(0)})),!0===i&&Zc.addAssign(Jp({bufferMap:a,influence:t,stride:o,width:l,depth:e,offset:oo(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 tm=Ya(em).setParameterLength(1);class sm extends sa{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class im extends sm{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class rm extends Zl{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:go().toVar("directDiffuse"),directSpecular:go().toVar("directSpecular"),indirectDiffuse:go().toVar("indirectDiffuse"),indirectSpecular:go().toVar("indirectSpecular")};return{radiance:go().toVar("radiance"),irradiance:go().toVar("irradiance"),iblIrradiance:go().toVar("iblIrradiance"),ambientOcclusion:ao(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 nm=Ya(rm);class am extends sm{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}const om=new Dt;class hm extends Qu{static get type(){return"ViewportTextureNode"}constructor(e=cc,t=null,s=null){let i=null;null===s?(i=new Pr,i.minFilter=G,s=i):i=s,super(s,e,t),this.generateMipmaps=!1,this.defaultFramebuffer=i,this.isOutputTextureNode=!0,this.updateBeforeType=Hn,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,s=t.getRenderTarget(),i=t.getCanvasTarget(),r=s||i;return this.value=this.getTextureForReference(r),this.value}updateBefore(e){const t=e.renderer,s=t.getRenderTarget(),i=t.getCanvasTarget(),r=s||i;null===r?t.getDrawingBufferSize(om):r.getDrawingBufferSize?r.getDrawingBufferSize(om):om.set(r.width,r.height);const n=this.getTextureForReference(r);n.image.width===om.width&&n.image.height===om.height||(n.image.width=om.width,n.image.height=om.height,n.needsUpdate=!0);const a=n.generateMipmaps;n.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(n),n.generateMipmaps=a}clone(){const e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}}const lm=Ya(hm,null,null,{generateMipmaps:!0}).setParameterLength(0,3),um=lm(),cm=(e=cc,t=null)=>um.sample(e,t);let dm=null;class pm extends hm{static get type(){return"ViewportDepthTextureNode"}constructor(e=cc,t=null,s=null){null===s&&(null===dm&&(dm=new Fr),s=dm),super(e,t,s)}}const mm=Ya(pm).setParameterLength(0,3);class gm extends sa{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===gm.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,s=this.valueNode;let i=null;if(t===gm.DEPTH_BASE)null!==s&&(i=xm().assign(s));else if(t===gm.DEPTH)i=e.isPerspectiveCamera?ym(Hc.z,Mc,Nc):fm(Hc.z,Mc,Nc);else if(t===gm.LINEAR_DEPTH)if(null!==s)if(e.isPerspectiveCamera){const e=bm(s,Mc,Nc);i=fm(e,Mc,Nc)}else i=s;else i=fm(Hc.z,Mc,Nc);return i}}gm.DEPTH_BASE="depthBase",gm.DEPTH="depth",gm.LINEAR_DEPTH="linearDepth";const fm=(e,t,s)=>e.add(t).div(t.sub(s)),ym=(e,t,s)=>t.add(e).mul(s).div(s.sub(t).mul(e)),bm=eo(([e,t,s],i)=>!0===i.renderer.reversedDepthBuffer?t.mul(s).div(t.sub(s).mul(e).sub(t)):t.mul(s).div(s.sub(t).mul(e).sub(s))),_m=(e,t,s)=>{t=t.max(1e-6).toVar();const i=Qh(e.negate().div(t)),r=Qh(s.div(t));return i.div(r)},xm=Ya(gm,gm.DEPTH_BASE),vm=Ka(gm,gm.DEPTH);mm(),vm.assign=e=>xm(e);class Tm extends sa{static get type(){return"ClippingNode"}constructor(e=Tm.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===Tm.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(s,i):this.scope===Tm.HARDWARE?this.setupHardwareClipping(i,e):this.setupDefault(s,i)}setupAlphaToCoverage(e,t){return eo(()=>{const s=ao().toVar("distanceToPlane"),i=ao().toVar("distanceToGradient"),r=ao(1).toVar("clipOpacity"),n=t.length;if(!1===this.hardwareClipping&&n>0){const e=nc(t).setGroup(oh);Kp(n,({i:t})=>{const n=e.element(t);s.assign(Hc.dot(n.xyz).negate().add(n.w)),i.assign(s.fwidth().div(2)),r.mulAssign(ql(i.negate(),i,s))})}const a=e.length;if(a>0){const t=nc(e).setGroup(oh),n=ao(1).toVar("intersectionClipOpacity");Kp(a,({i:e})=>{const r=t.element(e);s.assign(Hc.dot(r.xyz).negate().add(r.w)),i.assign(s.fwidth().div(2)),n.mulAssign(ql(i.negate(),i,s).oneMinus())}),r.mulAssign(n.oneMinus())}Ro.a.mulAssign(r),Ro.a.equal(0).discard()})()}setupDefault(e,t){return eo(()=>{const s=t.length;if(!1===this.hardwareClipping&&s>0){const e=nc(t).setGroup(oh);Kp(s,({i:t})=>{const s=e.element(t);Hc.dot(s.xyz).greaterThan(s.w).discard()})}const i=e.length;if(i>0){const t=nc(e).setGroup(oh),s=lo(!0).toVar("clipped");Kp(i,({i:e})=>{const i=t.element(e);s.assign(Hc.dot(i.xyz).greaterThan(i.w).and(s))}),s.discard()}})()}setupHardwareClipping(e,t){const s=e.length;return t.enableHardwareClipping(s),eo(()=>{const i=nc(e).setGroup(oh),r=ac(t.getClipDistance());Kp(s,({i:e})=>{const t=i.element(e),s=Hc.dot(t.xyz).sub(t.w).negate();r.element(e).assign(s)})})()}}Tm.ALPHA_TO_COVERAGE="alphaToCoverage",Tm.DEFAULT="default",Tm.HARDWARE="hardware";const Sm=eo(([e])=>il(bh(1e4,rl(bh(17,e.x).add(bh(.1,e.y)))).mul(fh(.1,fl(rl(bh(13,e.y).add(e.x))))))),wm=eo(([e])=>Sm(uo(Sm(e.xy),e.z))),Mm=eo(([e])=>{const t=Pl(bl(vl(e.xyz)),bl(Tl(e.xyz))),s=ao(1).div(ao(.05).mul(t)).toVar("pixScale"),i=uo(Yh(el(Qh(s))),Yh(tl(Qh(s)))),r=uo(wm(el(i.x.mul(e.xyz))),wm(el(i.y.mul(e.xyz)))),n=il(Qh(s)),a=fh(bh(n.oneMinus(),r.x),bh(n,r.y)),o=Cl(n,n.oneMinus()),h=go(a.mul(a).div(bh(2,o).mul(yh(1,o))),a.sub(bh(.5,o)).div(yh(1,o)),yh(1,yh(1,a).mul(yh(1,a)).div(bh(2,o).mul(yh(1,o))))),l=a.lessThan(o.oneMinus()).select(a.lessThan(o).select(h.x,h.y),h.z);return $l(l,1e-6,1)}).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class Nm extends Gu{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 ss(1,1,1,1)),s}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const Am=eo(([e])=>_o(e.rgb.mul(e.a),e.a),{color:"vec4",return:"vec4"});class Em extends Hi{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.maskShadowNode=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}_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(Ln(t.slice(0,-4)),s.getCacheKey());return this.type+Dn(e)}build(e){this.setup(e)}setupObserver(e){return new Cn(e)}setup(e){e.context.setupNormal=()=>ru(this.setupNormal(e),"NORMAL","vec3"),e.context.setupPositionView=()=>this.setupPositionView(e),e.context.setupModelViewProjection=()=>this.setupModelViewProjection(e);const t=e.renderer,s=t.getRenderTarget();e.addStack();const i=this.setupVertex(e),r=ru(this.vertexNode||i,"VERTEX");let n;e.context.clipSpace=r,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 a=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!==a&&e.stack.addToStack(a);const r=_o(i,Ro.a).max(0);n=this.setupOutput(e,r),Yo.assign(n);const o=null!==this.outputNode;if(o&&(n=this.outputNode),e.context.getOutput&&(n=e.context.getOutput(n,e)),null!==s){const e=t.getMRT(),s=this.mrtNode;null!==e?(o&&Yo.assign(n),n=e,null!==s&&(n=e.merge(s))):null!==s&&(n=s)}}else{let t=this.fragmentNode;!0!==t.isOutputStructNode&&(t=_o(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 Tm(Tm.ALPHA_TO_COVERAGE):e.stack.addToStack(new Tm)}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 Tm(Tm.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?_m(Hc.z,Mc,Nc):fm(Hc.z,Mc,Nc))}null!==i&&vm.assign(i).toStack()}setupPositionView(){return Ic.mul(Gc).xyz}setupModelViewProjection(){return Ac.mul(Hc)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.position=e.removeStack(),Op}setupPosition(e){const{object:t,geometry:s}=e;var i;if((s.morphAttributes.position||s.morphAttributes.normal||s.morphAttributes.color)&&tm(t).toStack(),!0===t.isSkinnedMesh&&(i=t,new Xp(i)).toStack(),this.displacementMap){const e=wd("displacementMap","texture"),t=wd("displacementScale","float"),s=wd("displacementBias","float");Gc.addAssign(Zc.normalize().mul(e.x.mul(t).add(s)))}return t.isBatchedMesh&&Hp(t).toStack(),t.isInstancedMesh&&t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&$p(t).toStack(),null!==this.positionNode&&Gc.assign(ru(this.positionNode,"POSITION","vec3")),Gc}setupDiffuseColor(e){const{object:t,geometry:s}=e;null!==this.maskNode&&lo(this.maskNode).not().discard();let i=this.colorNode?_o(this.colorNode):tp;if(!0===this.vertexColors&&s.hasAttribute("color")&&(i=i.mul(((e=0)=>new Nm(e))())),t.instanceColor){i=Eo("vec3","vInstanceColor").mul(i)}if(t.isBatchedMesh&&t._colorsTexture){i=Eo("vec3","vBatchColor").mul(i)}Ro.assign(i);const r=this.opacityNode?ao(this.opacityNode):rp;Ro.a.assign(Ro.a.mul(r));let n=null;(null!==this.alphaTestNode||this.alphaTest>0)&&(n=null!==this.alphaTestNode?ao(this.alphaTestNode):ep,!0===this.alphaToCoverage?(Ro.a=ql(n,n.add(Nl(Ro.a)),Ro.a),Ro.a.lessThanEqual(0).discard()):Ro.a.lessThanEqual(n).discard()),!0===this.alphaHash&&Ro.a.lessThan(Mm(Gc)).discard(),e.isOpaque()&&Ro.a.assign(1)}setupVariants(){}setupOutgoingLight(){return!0===this.lights?go(0):Ro.rgb}setupNormal(){return this.normalNode?go(this.normalNode):dp}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?wd("envMap","cubeTexture"):wd("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new am(Lp)),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=Dp),e.context.getAO&&(r=e.context.getAO(r,e)),r&&t.push(new im(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 a=this.setupOutgoingLight(e);if(n&&n.getScope().hasLights){const t=this.setupLightingModel(e)||null;a=nm(n,t,s,i)}else null!==s&&(a=go(null!==i?jl(a,s,i):s));return(r&&!0===r.isNode||t.emissive&&!0===t.emissive.isColor)&&(Po.assign(go(r||ip)),a=a.add(Po)),a}setupFog(e,t){const s=e.fogNode;return s&&(Yo.assign(t),t=_o(s.toVar())),t}setupPremultipliedAlpha(e,t){return Am(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=Hi.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.maskShadowNode=e.maskShadowNode,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 Rm=new Rr;class Cm extends Em{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(Rm),this.setValues(e)}}const Pm=new qr;class Bm extends Em{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(Pm),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?ao(this.offsetNode):Pp,t=this.dashScaleNode?ao(this.dashScaleNode):Ep,s=this.dashSizeNode?ao(this.dashSizeNode):Rp,i=this.gapSizeNode?ao(this.gapSizeNode):Cp;Ko.assign(s),Qo.assign(i);const r=au(ju("lineDistance").mul(t));(e?r.add(e):r).mod(Ko.add(Qo)).greaterThan(Ko).discard()}}const Fm=new $r;class Lm extends Em{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(Fm),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?ao(this.opacityNode):rp;Ro.assign(cu(_o(Wa(sd).mul(.5).add(.5),e),qe))}}const Dm=eo(([e=Wc])=>{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 uo(t,s)});class Im extends is{constructor(e=1,t={}){super(e,e,t),this.isCubeRenderTarget=!0;const s={width:e,height:e,depth:1},i=[s,s,s,s,s,s];this.texture=new Br(i),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!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 Dr(5,5,5),n=Dm(Wc),a=new Em;a.colorNode=Ju(t,n,0),a.side=1,a.blending=0;const o=new mr(r,a),h=new Gs;h.add(o),t.minFilter===G&&(t.minFilter=z);const l=new vn(1,10,this),u=e.getMRT();return e.setMRT(null),l.update(e,h),e.setMRT(u),t.minFilter=s,t.generateMipmaps=i,o.geometry.dispose(),o.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)}}const Om=new WeakMap;class Um extends na{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=bd(null);const t=new Br;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=Hn}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(Om.has(e)){const t=Om.get(e);zm(t,e.mapping),this._cubeTexture=t}else{const s=e.image;if(function(e){return null!=e&&e.height>0}(s)){const i=new Im(s.height);i.fromEquirectangularTexture(t,e),zm(i.texture,e.mapping),this._cubeTexture=i.texture,Om.set(e,i.texture),e.addEventListener("dispose",km)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function km(e){const t=e.target;t.removeEventListener("dispose",km);const s=Om.get(t);void 0!==s&&(Om.delete(t),s.dispose())}function zm(e,t){303===t?e.mapping=B:304===t&&(e.mapping=F)}const Vm=Ya(Um).setParameterLength(1);class Gm extends sm{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=Vm(this.envNode)}}class jm extends sm{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=ao(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class $m{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class Wm extends $m{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,s=e.reflectedLight,i=e.irradianceLightMap;s.indirectDiffuse.assign(_o(0)),i?s.indirectDiffuse.addAssign(i):s.indirectDiffuse.addAssign(_o(1,1,1,0)),s.indirectDiffuse.mulAssign(t),s.indirectDiffuse.mulAssign(Ro.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(jl(i.rgb,i.rgb.mul(r.rgb),hp.mul(lp)));break;case 1:i.rgb.assign(jl(i.rgb,r.rgb,hp.mul(lp)));break;case 2:i.rgb.addAssign(r.rgb.mul(hp.mul(lp)));break;default:bt("BasicLightingModel: Unsupported .combine value:",t.combine)}}}const Hm=new sr;class qm extends Em{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Hm),this.setValues(e)}setupNormal(){return Kc(ed)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Gm(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new jm(Lp)),t}setupOutgoingLight(){return Ro.rgb}setupLightingModel(){return new Wm}}const Xm=eo(({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))}),Ym=eo(e=>e.diffuseColor.mul(1/Math.PI)),Km=eo(({dotNH:e})=>Xo.mul(ao(.5)).add(1).mul(ao(1/Math.PI)).mul(e.pow(Xo))),Qm=eo(({lightDirection:e})=>{const t=e.add(qc).normalize(),s=sd.dot(t).clamp(),i=qc.dot(t).clamp(),r=Xm({f0:Wo,f90:1,dotVH:i}),n=ao(.25),a=Km({dotNH:s});return r.mul(n).mul(a)});class Zm extends Wm{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const i=sd.dot(e).clamp().mul(t);s.directDiffuse.addAssign(i.mul(Ym({diffuseColor:Ro.rgb}))),!0===this.specular&&s.directSpecular.addAssign(i.mul(Qm({lightDirection:e})).mul(hp))}indirect(e){const{ambientOcclusion:t,irradiance:s,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(s.mul(Ym({diffuseColor:Ro}))),i.indirectDiffuse.mulAssign(t)}}const Jm=new Wr;class eg extends Em{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Jm),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Gm(t):null}setupLightingModel(){return new Zm(!1)}}const tg=new Gr;class sg extends Em{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(tg),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Gm(t):null}setupLightingModel(){return new Zm}setupVariants(){const e=(this.shininessNode?ao(this.shininessNode):sp).max(1e-4);Xo.assign(e);const t=this.specularNode||np;Wo.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}const ig=eo(e=>{if(!1===e.geometry.hasAttribute("normal"))return ao(0);const t=ed.dFdx().abs().max(ed.dFdy().abs());return t.x.max(t.y).max(t.z)}),rg=eo(e=>{const{roughness:t}=e,s=ig();let i=t.max(.0525);return i=i.add(s),i=i.min(1),i}),ng=eo(({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 _h(.5,r.add(n).max(Gh))}).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),ag=eo(({alphaT:e,alphaB:t,dotTV:s,dotBV:i,dotTL:r,dotBL:n,dotNV:a,dotNL:o})=>{const h=o.mul(go(e.mul(s),t.mul(i),a).length()),l=a.mul(go(e.mul(r),t.mul(n),o).length());return _h(.5,h.add(l).max(Gh))}).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"}]}),og=eo(({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"}]}),hg=ao(1/Math.PI),lg=eo(({alphaT:e,alphaB:t,dotNH:s,dotTH:i,dotBH:r})=>{const n=e.mul(t),a=go(t.mul(i),e.mul(r),n.mul(s)),o=a.dot(a),h=n.div(o);return hg.mul(n.mul(h.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"}]}),ug=eo(({lightDirection:e,f0:t,f90:s,roughness:i,f:r,normalView:n=sd,USE_IRIDESCENCE:a,USE_ANISOTROPY:o})=>{const h=i.pow2(),l=e.add(qc).normalize(),u=n.dot(e).clamp(),c=n.dot(qc).clamp(),d=n.dot(l).clamp(),p=qc.dot(l).clamp();let m,g,f=Xm({f0:t,f90:s,dotVH:p});if(ja(a)&&(f=Uo.mix(f,r)),ja(o)){const t=jo.dot(e),s=jo.dot(qc),i=jo.dot(l),r=$o.dot(e),n=$o.dot(qc),a=$o.dot(l);m=ag({alphaT:Vo,alphaB:h,dotTV:s,dotBV:n,dotTL:t,dotBL:r,dotNV:c,dotNL:u}),g=lg({alphaT:Vo,alphaB:h,dotNH:d,dotTH:i,dotBH:a})}else m=ng({alpha:h,dotNL:u,dotNV:c}),g=og({alpha:h,dotNH:d});return f.mul(m).mul(g)}),cg=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 dg=null;const pg=eo(({roughness:e,dotNV:t})=>{null===dg&&(dg=new fr(cg,16,16,le,K),dg.name="DFG_LUT",dg.minFilter=z,dg.magFilter=z,dg.wrapS=D,dg.wrapT=D,dg.generateMipmaps=!1,dg.needsUpdate=!0);const s=uo(e,t);return Ju(dg,s).rg}),mg=eo(({lightDirection:e,f0:t,f90:s,roughness:i,f:r,USE_IRIDESCENCE:n,USE_ANISOTROPY:a})=>{const o=ug({lightDirection:e,f0:t,f90:s,roughness:i,f:r,USE_IRIDESCENCE:n,USE_ANISOTROPY:a}),h=sd.dot(e).clamp(),l=sd.dot(qc).clamp(),u=pg({roughness:i,dotNV:l}),c=pg({roughness:i,dotNV:h}),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),g=c.x.add(c.y),f=ao(1).sub(m),y=ao(1).sub(g),b=t.add(t.oneMinus().mul(.047619)),_=d.mul(p).mul(b).div(ao(1).sub(f.mul(y).mul(b).mul(b)).add(Gh)),x=f.mul(y),v=_.mul(x);return o.add(v)}),gg=eo(e=>{const{dotNV:t,specularColor:s,specularF90:i,roughness:r}=e,n=pg({dotNV:t,roughness:r});return s.mul(n.x).add(i.mul(n.y))}),fg=eo(({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(go(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"}]}),yg=eo(({roughness:e,dotNH:t})=>{const s=e.pow2(),i=ao(1).div(s),r=t.pow2().oneMinus().max(.0078125);return ao(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"}]}),bg=eo(({dotNV:e,dotNL:t})=>ao(1).div(ao(4).mul(t.add(e).sub(t.mul(e))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),_g=eo(({lightDirection:e})=>{const t=e.add(qc).normalize(),s=sd.dot(e).clamp(),i=sd.dot(qc).clamp(),r=sd.dot(t).clamp(),n=yg({roughness:Oo,dotNH:r}),a=bg({dotNV:i,dotNL:s});return Io.mul(n).mul(a)}),xg=eo(({N:e,V:t,roughness:s})=>{const i=e.dot(t).saturate(),r=uo(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"}]}),vg=eo(({f:e})=>{const t=e.length();return Pl(t.mul(t).add(e.z).div(t.add(1)),0)}).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),Tg=eo(({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(),a=r.div(n),o=s.greaterThan(0).select(a,Pl(s.mul(s).oneMinus(),1e-7).inverseSqrt().mul(.5).sub(a));return e.cross(t).mul(o)}).setLayout({name:"LTC_EdgeVectorFormFactor",type:"vec3",inputs:[{name:"v1",type:"vec3"},{name:"v2",type:"vec3"}]}),Sg=eo(({N:e,V:t,P:s,mInv:i,p0:r,p1:n,p2:a,p3:o})=>{const h=n.sub(r).toVar(),l=o.sub(r).toVar(),u=h.cross(l),c=go().toVar();return io(u.dot(s.sub(r)).greaterThanEqual(0),()=>{const h=t.sub(e.mul(t.dot(e))).normalize(),l=e.cross(h).negate(),u=i.mul(wo(h,l,e).transpose()).toVar(),d=u.mul(r.sub(s)).normalize().toVar(),p=u.mul(n.sub(s)).normalize().toVar(),m=u.mul(a.sub(s)).normalize().toVar(),g=u.mul(o.sub(s)).normalize().toVar(),f=go(0).toVar();f.addAssign(Tg({v1:d,v2:p})),f.addAssign(Tg({v1:p,v2:m})),f.addAssign(Tg({v1:m,v2:g})),f.addAssign(Tg({v1:g,v2:d})),c.assign(go(vg({f:f})))}),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"}]}),wg=1/6,Mg=e=>bh(wg,bh(e,bh(e,e.negate().add(3)).sub(3)).add(1)),Ng=e=>bh(wg,bh(e,bh(e,bh(3,e).sub(6))).add(4)),Ag=e=>bh(wg,bh(e,bh(e,bh(-3,e).add(3)).add(3)).add(1)),Eg=e=>bh(wg,Ul(e,3)),Rg=e=>Mg(e).add(Ng(e)),Cg=e=>Ag(e).add(Eg(e)),Pg=e=>fh(-1,Ng(e).div(Mg(e).add(Ng(e)))),Bg=e=>fh(1,Eg(e).div(Ag(e).add(Eg(e)))),Fg=(e,t,s)=>{const i=e.uvNode,r=bh(i,t.zw).add(.5),n=el(r),a=il(r),o=Rg(a.x),h=Cg(a.x),l=Pg(a.x),u=Bg(a.x),c=Pg(a.y),d=Bg(a.y),p=uo(n.x.add(l),n.y.add(c)).sub(.5).mul(t.xy),m=uo(n.x.add(u),n.y.add(c)).sub(.5).mul(t.xy),g=uo(n.x.add(l),n.y.add(d)).sub(.5).mul(t.xy),f=uo(n.x.add(u),n.y.add(d)).sub(.5).mul(t.xy),y=Rg(a.y).mul(fh(o.mul(e.sample(p).level(s)),h.mul(e.sample(m).level(s)))),b=Cg(a.y).mul(fh(o.mul(e.sample(g).level(s)),h.mul(e.sample(f).level(s))));return y.add(b)},Lg=eo(([e,t])=>{const s=uo(e.size(oo(t))),i=uo(e.size(oo(t.add(1)))),r=_h(1,s),n=_h(1,i),a=Fg(e,_o(r,s),el(t)),o=Fg(e,_o(n,i),tl(t));return il(t).mix(a,o)}),Dg=eo(([e,t,s,i,r])=>{const n=go(Hl(t.negate(),sl(e),_h(1,i))),a=go(bl(r[0].xyz),bl(r[1].xyz),bl(r[2].xyz));return sl(n).mul(s.mul(a))}).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"}]}),Ig=eo(([e,t])=>e.mul($l(t.mul(2).sub(2),0,1))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),Og=lm(),Ug=cm(),kg=eo(([e,t,s],{material:i})=>{const r=(1===i.side?Og:Ug).sample(e),n=Qh(dc.x).mul(Ig(t,s));return Lg(r,n)}),zg=eo(([e,t,s])=>(io(s.notEqual(0),()=>{const i=Kh(t).negate().div(s);return Xh(i.negate().mul(e))}),go(1))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),Vg=eo(([e,t,s,i,r,n,a,o,h,l,u,c,d,p,m])=>{let g,f;if(m){g=_o().toVar(),f=go().toVar();const r=u.sub(1).mul(m.mul(.025)),n=go(u.sub(r),u,u.add(r));Kp({start:0,end:3},({i:r})=>{const u=n.element(r),m=Dg(e,t,c,u,o),y=a.add(m),b=l.mul(h.mul(_o(y,1))),_=uo(b.xy.div(b.w)).toVar();_.addAssign(1),_.divAssign(2),_.assign(uo(_.x,_.y.oneMinus()));const x=kg(_,s,u);g.element(r).assign(x.element(r)),g.a.addAssign(x.a),f.element(r).assign(i.element(r).mul(zg(bl(m),d,p).element(r)))}),g.a.divAssign(3)}else{const r=Dg(e,t,c,u,o),n=a.add(r),m=l.mul(h.mul(_o(n,1))),y=uo(m.xy.div(m.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(uo(y.x,y.y.oneMinus())),g=kg(y,s,u),f=i.mul(zg(bl(r),d,p))}const y=f.rgb.mul(g.rgb),b=e.dot(t).clamp(),_=go(gg({dotNV:b,specularColor:r,specularF90:n,roughness:s})),x=f.r.add(f.g,f.b).div(3);return _o(_.oneMinus().mul(y),g.a.oneMinus().mul(x).oneMinus())}),Gg=wo(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),jg=(e,t)=>e.sub(t).div(e.add(t)).pow2(),$g=eo(({outsideIOR:e,eta2:t,cosTheta1:s,thinFilmThickness:i,baseF0:r})=>{const n=jl(e,t,ql(0,.03,i)),a=e.div(n).pow2().mul(s.pow2().oneMinus()).oneMinus();io(a.lessThan(0),()=>go(1));const o=a.sqrt(),h=jg(n,e),l=Xm({f0:h,f90:1,dotVH:s}),u=l.oneMinus(),c=n.lessThan(e).select(Math.PI,0),d=ao(Math.PI).sub(c),p=(e=>{const t=e.sqrt();return go(1).add(t).div(go(1).sub(t))})(r.clamp(0,.9999)),m=jg(p,n.toVec3()),g=Xm({f0:m,f90:1,dotVH:o}),f=go(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,o,2),b=go(d).add(f),_=l.mul(g).clamp(1e-5,.9999),x=_.sqrt(),v=u.pow2().mul(g).div(go(1).sub(_)),T=l.add(v).toVar(),S=v.sub(u).toVar();return Kp({start:1,end:2,condition:"<=",name:"m"},({m:e})=>{S.mulAssign(x);const t=((e,t)=>{const s=e.mul(2*Math.PI*1e-9),i=go(54856e-17,44201e-17,52481e-17),r=go(1681e3,1795300,2208400),n=go(43278e5,93046e5,66121e5),a=ao(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(s.mul(2239900).add(t.x).cos()).mul(s.pow2().mul(-45282e5).exp());let o=i.mul(n.mul(2*Math.PI).sqrt()).mul(r.mul(s).add(t).cos()).mul(s.pow2().negate().mul(n).exp());return o=go(o.x.add(a),o.y,o.z).div(1.0685e-7),Gg.mul(o)})(ao(e).mul(y),ao(e).mul(b)).mul(2);T.addAssign(S.mul(t))}),T.max(go(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"}]}),Wg=eo(({normal:e,viewDir:t,roughness:s})=>{const i=e.dot(t).saturate(),r=s.mul(s),n=s.add(.1).reciprocal(),a=ao(-1.9362).add(s.mul(1.0678)).add(r.mul(.4573)).sub(n.mul(.8469)),o=ao(-.6014).add(s.mul(.5538)).sub(r.mul(.467)).sub(n.mul(.1255));return a.mul(i).add(o).exp().saturate()}),Hg=go(.04),qg=ao(1);class Xg extends $m{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=go().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=go().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=go().toVar("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=go().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=go().toVar("sheenSpecularIndirect")),!0===this.iridescence){const e=sd.dot(qc).clamp(),t=$g({outsideIOR:ao(1),eta2:ko,cosTheta1:e,thinFilmThickness:zo,baseF0:Wo}),s=$g({outsideIOR:ao(1),eta2:ko,cosTheta1:e,thinFilmThickness:zo,baseF0:Ro.rgb});this.iridescenceFresnel=jl(t,s,Fo),this.iridescenceF0Dielectric=fg({f:t,f90:1,dotVH:e}),this.iridescenceF0Metallic=fg({f:s,f90:1,dotVH:e}),this.iridescenceF0=jl(this.iridescenceF0Dielectric,this.iridescenceF0Metallic,Fo)}if(!0===this.transmission){const t=$c,s=Cc.sub($c).normalize(),i=id,r=e.context;r.backdrop=Vg(i,s,Bo,Co,Ho,qo,t,Lc,Rc,Ac,Zo,eh,sh,th,this.dispersion?ih:null),r.backdropAlpha=Jo,Ro.a.mulAssign(jl(1,r.backdrop.a,Jo))}super.start(e)}computeMultiscattering(e,t,s,i,r=null){const n=sd.dot(qc).clamp(),a=pg({roughness:Bo,dotNV:n}),o=r?Uo.mix(i,r):i,h=o.mul(a.x).add(s.mul(a.y)),l=a.x.add(a.y).oneMinus(),u=o.add(o.oneMinus().mul(.047619)),c=h.mul(u).div(l.mul(u).oneMinus());e.addAssign(h),t.addAssign(c.mul(l))}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const i=sd.dot(e).clamp().mul(t).toVar();if(!0===this.sheen){this.sheenSpecularDirect.addAssign(i.mul(_g({lightDirection:e})));const t=Wg({normal:sd,viewDir:qc,roughness:Oo}),s=Wg({normal:sd,viewDir:e,roughness:Oo}),r=Io.r.max(Io.g).max(Io.b).mul(t.max(s)).oneMinus();i.mulAssign(r)}if(!0===this.clearcoat){const s=rd.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(s.mul(ug({lightDirection:e,f0:Hg,f90:qg,roughness:Do,normalView:rd})))}s.directDiffuse.addAssign(i.mul(Ym({diffuseColor:Co}))),s.directSpecular.addAssign(i.mul(mg({lightDirection:e,f0:Ho,f90:1,roughness:Bo,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:a}){const o=t.add(s).sub(i),h=t.sub(s).sub(i),l=t.sub(s).add(i),u=t.add(s).add(i),c=sd,d=qc,p=Hc.toVar(),m=xg({N:c,V:d,roughness:Bo}),g=n.sample(m).toVar(),f=a.sample(m).toVar(),y=wo(go(g.x,0,g.y),go(0,1,0),go(g.z,0,g.w)).toVar(),b=Ho.mul(f.x).add(qo.sub(Ho).mul(f.y)).toVar();if(r.directSpecular.addAssign(e.mul(b).mul(Sg({N:c,V:d,P:p,mInv:y,p0:o,p1:h,p2:l,p3:u}))),r.directDiffuse.addAssign(e.mul(Co).mul(Sg({N:c,V:d,P:p,mInv:wo(1,0,0,0,1,0,0,0,1),p0:o,p1:h,p2:l,p3:u}))),!0===this.clearcoat){const t=rd,s=xg({N:t,V:d,roughness:Do}),i=n.sample(s),r=a.sample(s),c=wo(go(i.x,0,i.y),go(0,1,0),go(i.z,0,i.w)),m=Hg.mul(r.x).add(qg.sub(Hg).mul(r.y));this.clearcoatSpecularDirect.addAssign(e.mul(m).mul(Sg({N:t,V:d,P:p,mInv:c,p0:o,p1:h,p2:l,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(Ym({diffuseColor:Co})).toVar();if(!0===this.sheen){const e=Wg({normal:sd,viewDir:qc,roughness:Oo}),t=Io.r.max(Io.g).max(Io.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(Io,Wg({normal:sd,viewDir:qc,roughness:Oo}))),!0===this.clearcoat){const e=rd.dot(qc).clamp(),t=gg({dotNV:e,specularColor:Hg,specularF90:qg,roughness:Do});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const r=go().toVar("singleScatteringDielectric"),n=go().toVar("multiScatteringDielectric"),a=go().toVar("singleScatteringMetallic"),o=go().toVar("multiScatteringMetallic");this.computeMultiscattering(r,n,qo,Wo,this.iridescenceF0Dielectric),this.computeMultiscattering(a,o,qo,Ro.rgb,this.iridescenceF0Metallic);const h=jl(r,a,Fo),l=jl(n,o,Fo),u=r.add(n),c=Co.mul(u.oneMinus()),d=s.mul(1/Math.PI),p=t.mul(h).add(l.mul(d)).toVar(),m=c.mul(d).toVar();if(!0===this.sheen){const e=Wg({normal:sd,viewDir:qc,roughness:Oo}),t=Io.r.max(Io.g).max(Io.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=sd.dot(qc).clamp().add(t),r=Bo.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=rd.dot(qc).clamp(),s=Xm({dotVH:e,f0:Hg,f90:qg}),i=t.mul(Lo.mul(s).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(Lo));t.assign(i)}if(!0===this.sheen){const e=t.add(this.sheenSpecularDirect,this.sheenSpecularIndirect.mul(1/Math.PI));t.assign(e)}}}const Yg=ao(1),Kg=ao(-2),Qg=ao(.8),Zg=ao(-1),Jg=ao(.4),ef=ao(2),tf=ao(.305),sf=ao(3),rf=ao(.21),nf=ao(4),af=ao(4),of=ao(16),hf=eo(([e])=>{const t=go(fl(e)).toVar(),s=ao(-1).toVar();return io(t.x.greaterThan(t.z),()=>{io(t.x.greaterThan(t.y),()=>{s.assign(Ql(e.x.greaterThan(0),0,3))}).Else(()=>{s.assign(Ql(e.y.greaterThan(0),1,4))})}).Else(()=>{io(t.z.greaterThan(t.y),()=>{s.assign(Ql(e.z.greaterThan(0),2,5))}).Else(()=>{s.assign(Ql(e.y.greaterThan(0),1,4))})}),s}).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),lf=eo(([e,t])=>{const s=uo().toVar();return io(t.equal(0),()=>{s.assign(uo(e.z,e.y).div(fl(e.x)))}).ElseIf(t.equal(1),()=>{s.assign(uo(e.x.negate(),e.z.negate()).div(fl(e.y)))}).ElseIf(t.equal(2),()=>{s.assign(uo(e.x.negate(),e.y).div(fl(e.z)))}).ElseIf(t.equal(3),()=>{s.assign(uo(e.z.negate(),e.y).div(fl(e.x)))}).ElseIf(t.equal(4),()=>{s.assign(uo(e.x.negate(),e.z).div(fl(e.y)))}).Else(()=>{s.assign(uo(e.x,e.y).div(fl(e.z)))}),bh(.5,s.add(1))}).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),uf=eo(([e])=>{const t=ao(0).toVar();return io(e.greaterThanEqual(Qg),()=>{t.assign(Yg.sub(e).mul(Zg.sub(Kg)).div(Yg.sub(Qg)).add(Kg))}).ElseIf(e.greaterThanEqual(Jg),()=>{t.assign(Qg.sub(e).mul(ef.sub(Zg)).div(Qg.sub(Jg)).add(Zg))}).ElseIf(e.greaterThanEqual(tf),()=>{t.assign(Jg.sub(e).mul(sf.sub(ef)).div(Jg.sub(tf)).add(ef))}).ElseIf(e.greaterThanEqual(rf),()=>{t.assign(tf.sub(e).mul(nf.sub(sf)).div(tf.sub(rf)).add(sf))}).Else(()=>{t.assign(ao(-2).mul(Qh(bh(1.16,e))))}),t}).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),cf=eo(([e,t])=>{const s=e.toVar();s.assign(bh(2,s).sub(1));const i=go(s,1).toVar();return io(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"}]}),df=eo(([e,t,s,i,r,n])=>{const a=ao(s),o=go(t),h=$l(uf(a),Kg,n),l=il(h),u=el(h),c=go(pf(e,o,u,i,r,n)).toVar();return io(l.notEqual(0),()=>{const t=go(pf(e,o,u.add(1),i,r,n)).toVar();c.assign(jl(c,t,l))}),c}),pf=eo(([e,t,s,i,r,n])=>{const a=ao(s).toVar(),o=go(t),h=ao(hf(o)).toVar(),l=ao(Pl(af.sub(a),0)).toVar();a.assign(Pl(a,af));const u=ao(Yh(a)).toVar(),c=uo(lf(o,h).mul(u.sub(2)).add(1)).toVar();return io(h.greaterThan(2),()=>{c.y.addAssign(u),h.subAssign(3)}),c.x.addAssign(h.mul(u)),c.x.addAssign(l.mul(bh(3,of))),c.y.addAssign(bh(4,Yh(n).sub(u))),c.x.mulAssign(i),c.y.mulAssign(r),e.sample(c).grad(uo(),uo())}),mf=eo(({envMap:e,mipInt:t,outputDirection:s,theta:i,axis:r,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const h=al(i),l=s.mul(h).add(r.cross(s).mul(rl(i))).add(r.mul(r.dot(s).mul(h.oneMinus())));return pf(e,l,t,n,a,o)}),gf=eo(({n:e,latitudinal:t,poleAxis:s,outputDirection:i,weights:r,samples:n,dTheta:a,mipInt:o,envMap:h,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:c})=>{const d=go(Ql(t,s,Ol(s,i))).toVar();io(d.equal(go(0)),()=>{d.assign(go(i.z,0,i.x.negate()))}),d.assign(sl(d));const p=go().toVar();return p.addAssign(r.element(0).mul(mf({theta:0,axis:d,outputDirection:i,mipInt:o,envMap:h,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:c}))),Kp({start:oo(1),end:e},({i:e})=>{io(e.greaterThanEqual(n),()=>{Iu("break").toStack()});const t=ao(a.mul(ao(e))).toVar();p.addAssign(r.element(e).mul(mf({theta:t.mul(-1),axis:d,outputDirection:i,mipInt:o,envMap:h,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:c}))),p.addAssign(r.element(e).mul(mf({theta:t,axis:d,outputDirection:i,mipInt:o,envMap:h,CUBEUV_TEXEL_WIDTH:l,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:c})))}),_o(p,1)}),ff=eo(([e])=>{const t=ho(e).toVar();return t.assign(t.shiftLeft(ho(16)).bitOr(t.shiftRight(ho(16)))),t.assign(t.bitAnd(ho(1431655765)).shiftLeft(ho(1)).bitOr(t.bitAnd(ho(2863311530)).shiftRight(ho(1)))),t.assign(t.bitAnd(ho(858993459)).shiftLeft(ho(2)).bitOr(t.bitAnd(ho(3435973836)).shiftRight(ho(2)))),t.assign(t.bitAnd(ho(252645135)).shiftLeft(ho(4)).bitOr(t.bitAnd(ho(4042322160)).shiftRight(ho(4)))),t.assign(t.bitAnd(ho(16711935)).shiftLeft(ho(8)).bitOr(t.bitAnd(ho(4278255360)).shiftRight(ho(8)))),ao(t).mul(2.3283064365386963e-10)}),yf=eo(([e,t])=>uo(ao(e).div(ao(t)),ff(e))),bf=eo(([e,t,s])=>{const i=s.mul(s).toConst(),r=go(1,0,0).toConst(),n=Ol(t,r).toConst(),a=Zh(e.x).toConst(),o=bh(2,3.14159265359).mul(e.y).toConst(),h=a.mul(al(o)).toConst(),l=a.mul(rl(o)).toVar(),u=bh(.5,t.z.add(1)).toConst();l.assign(u.oneMinus().mul(Zh(h.mul(h).oneMinus())).add(u.mul(l)));const c=r.mul(h).add(n.mul(l)).add(t.mul(Zh(Pl(0,h.mul(h).add(l.mul(l)).oneMinus()))));return sl(go(i.mul(c.x),i.mul(c.y),Pl(0,c.z)))}),_f=eo(({roughness:e,mipInt:t,envMap:s,N_immutable:i,GGX_SAMPLES:r,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const h=go(i).toVar(),l=go(0).toVar(),u=ao(0).toVar();return io(e.lessThan(.001),()=>{l.assign(pf(s,h,t,n,a,o))}).Else(()=>{const i=Ql(fl(h.z).lessThan(.999),go(0,0,1),go(1,0,0)),c=sl(Ol(i,h)).toVar(),d=Ol(h,c).toVar();Kp({start:ho(0),end:r},({i:i})=>{const p=yf(i,r),m=bf(p,go(0,0,1),e),g=sl(c.mul(m.x).add(d.mul(m.y)).add(h.mul(m.z))),f=sl(g.mul(Il(h,g).mul(2)).sub(h)),y=Pl(Il(h,f),0);io(y.greaterThan(0),()=>{const e=pf(s,f,t,n,a,o);l.addAssign(e.mul(y)),u.addAssign(y)})}),io(u.greaterThan(0),()=>{l.assign(l.div(u))})}),_o(l,1)}),xf=[.125,.215,.35,.446,.526,.582],vf=20,Tf=new pn(-1,1,1,-1,0,1),Sf=new hn(90,1),wf=new zs;let Mf=null,Nf=0,Af=0;const Ef=new Ot,Rf=new WeakMap,Cf=[3,1,5,0,4,2],Pf=cf($u(),ju("faceIndex")).normalize(),Bf=go(Pf.x,Pf.y,Pf.z);class Ff{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:a=Ef,renderTarget:o=null}=r;if(this._setSize(n),!1===this._hasInitialized){bt('PMREMGenerator: ".fromScene()" called before the backend is initialized. Try using "await renderer.init()" instead.');const n=o||this._allocateTarget();return r.renderTarget=n,this.fromSceneAsync(e,t,s,i,r),n}Mf=this._renderer.getRenderTarget(),Nf=this._renderer.getActiveCubeFace(),Af=this._renderer.getActiveMipmapLevel();const h=o||this._allocateTarget();return h.depthBuffer=!0,this._init(h),this._sceneToCubeUV(e,s,i,h,a),t>0&&this._blur(h,0,0,t),this._applyPMREM(h),this._cleanup(h),h}async fromSceneAsync(e,t=0,s=.1,i=100,r={}){return xt('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){bt('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 xt('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){bt("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 xt('PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=If(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=Of(),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===B||e.mapping===F?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(Mf,Nf,Af),e.scissorTest=!1,this._setViewport(e,0,0,e.width,e.height)}_fromTexture(e,t){this._setSizeFromTexture(e),Mf=this._renderer.getRenderTarget(),Nf=this._renderer.getActiveCubeFace(),Af=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 Lf(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=Lf(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+xf.length;for(let a=0;a<n;a++){const n=Math.pow(2,r);t.push(n);let o=1/n;a>e-4?o=xf[a-e+4-1]:0===a&&(o=0),s.push(o);const h=1/(n-2),l=-h,u=1+h,c=[l,l,u,l,u,u,l,l,u,u,l,u],d=6,p=6,m=3,g=2,f=1,y=new Float32Array(m*p*d),b=new Float32Array(g*p*d),_=new Float32Array(f*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=Cf[e];y.set(i,m*p*r),b.set(c,g*p*r);const n=[r,r,r,r,r,r];_.set(n,f*p*r)}const x=new Vi;x.setAttribute("position",new Mi(y,m)),x.setAttribute("uv",new Mi(b,g)),x.setAttribute("faceIndex",new Mi(_,f)),i.push(new mr(x,null)),r>4&&r--}return{lodMeshes:i,sizeLods:t,sigmas:s}}(t)),this._blurMaterial=function(e,t,s){const i=nc(new Array(vf).fill(0)),r=uh(new Ot(0,1,0)),n=uh(0),a=ao(vf),o=uh(0),h=uh(1),l=Ju(),u=uh(0),c=ao(1/t),d=ao(1/s),p=ao(e),m={n:a,latitudinal:o,weights:i,poleAxis:r,outputDirection:Bf,dTheta:n,samples:h,envMap:l,mipInt:u,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:p},g=Df("blur");return g.fragmentNode=gf({...m,latitudinal:o.equal(1)}),Rf.set(g,m),g}(t,e.width,e.height),this._ggxMaterial=function(e,t,s){const i=Ju(),r=uh(0),n=uh(0),a=ao(1/t),o=ao(1/s),h=ao(e),l={envMap:i,roughness:r,mipInt:n,CUBEUV_TEXEL_WIDTH:a,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:h},u=Df("ggx");return u.fragmentNode=_f({...l,N_immutable:Bf,GGX_SAMPLES:ho(512)}),Rf.set(u,l),u}(t,e.width,e.height)}}async _compileMaterial(e){const t=new mr(new Vi,e);await this._renderer.compile(t,Tf)}_sceneToCubeUV(e,t,s,i,r){const n=Sf;n.near=t,n.far=s;const a=[1,1,1,1,-1,1],o=[1,-1,1,-1,1,-1],h=this._renderer,l=h.autoClear;h.getClearColor(wf),h.autoClear=!1,null===this._backgroundBox&&(this._backgroundBox=new mr(new Dr,new sr({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(wf),d=!0),h.setRenderTarget(i),h.clear(),d&&h.render(u,n);for(let t=0;t<6;t++){const s=t%3;0===s?(n.up.set(0,a[t],0),n.position.set(r.x,r.y,r.z),n.lookAt(r.x+o[t],r.y,r.z)):1===s?(n.up.set(0,0,a[t]),n.position.set(r.x,r.y,r.z),n.lookAt(r.x,r.y+o[t],r.z)):(n.up.set(0,a[t],0),n.position.set(r.x,r.y,r.z),n.lookAt(r.x,r.y,r.z+o[t]));const l=this._cubeSize;this._setViewport(i,s*l,t>2?l:0,l,l),h.render(e,n)}h.autoClear=l,e.background=p}_textureToCubeUV(e,t){const s=this._renderer,i=e.mapping===B||e.mapping===F;i?null===this._cubemapMaterial&&(this._cubemapMaterial=If(e)):null===this._equirectMaterial&&(this._equirectMaterial=Of(e));const r=i?this._cubemapMaterial:this._equirectMaterial;r.fragmentNode.value=e;const n=this._lodMeshes[0];n.material=r;const a=this._cubeSize;this._setViewport(t,0,0,3*a,2*a),s.setRenderTarget(t),s.render(n,Tf)}_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,a=this._lodMeshes[s];a.material=n;const o=Rf.get(n),h=s/(this._lodMeshes.length-1),l=t/(this._lodMeshes.length-1),u=Math.sqrt(h*h-l*l)*(0+1.25*h),{_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,o.envMap.value=e.texture,o.roughness.value=u,o.mipInt.value=c-t,this._setViewport(r,p,m,3*d,2*d),i.setRenderTarget(r),i.render(a,Tf),r.texture.frame=(r.texture.frame||0)+1,o.envMap.value=r.texture,o.roughness.value=0,o.mipInt.value=c-s,this._setViewport(e,p,m,3*d,2*d),i.setRenderTarget(e),i.render(a,Tf)}_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,a){const o=this._renderer,h=this._blurMaterial;"latitudinal"!==n&&"longitudinal"!==n&&_t("blur direction must be either latitudinal or longitudinal!");const l=this._lodMeshes[i];l.material=h;const u=Rf.get(h),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):vf;m>vf&&bt(`sigmaRadians, ${r}, is too large and will clip, as it requested ${m} samples when the maximum is set to 20`);const g=[];let f=0;for(let e=0;e<vf;++e){const t=e/p,s=Math.exp(-t*t/2);g.push(s),0===e?f+=s:e<m&&(f+=2*s)}for(let e=0;e<g.length;e++)g[e]=g[e]/f;e.texture.frame=(e.texture.frame||0)+1,u.envMap.value=e.texture,u.samples.value=m,u.weights.array=g,u.latitudinal.value="latitudinal"===n?1:0,a&&(u.poleAxis.value=a);const{_lodMax:y}=this;u.dTheta.value=d,u.mipInt.value=y-s;const b=this._sizeLods[i],_=3*b*(i>y-4?i-y+4:0),x=4*(this._cubeSize-b);this._setViewport(t,_,x,3*b,2*b),o.setRenderTarget(t),o.render(l,Tf)}_setViewport(e,t,s,i,r){this._renderer.isWebGLRenderer?(e.viewport.set(t,e.height-r-s,i,r),e.scissor.set(t,e.height-r-s,i,r)):(e.viewport.set(t,s,i,r),e.scissor.set(t,s,i,r))}}function Lf(e,t){const s=new is(e,t,{magFilter:z,minFilter:z,generateMipmaps:!1,type:K,format:re,colorSpace:Xe});return s.texture.mapping=306,s.texture.name="PMREM.cubeUv",s.texture.isPMREMTexture=!0,s.scissorTest=!0,s}function Df(e){const t=new Em;return t.depthTest=!1,t.depthWrite=!1,t.blending=0,t.name=`PMREM_${e}`,t}function If(e){const t=Df("cubemap");return t.fragmentNode=bd(e,Bf),t}function Of(e){const t=Df("equirect");return t.fragmentNode=Ju(e,Dm(Bf),0),t}const Uf=new WeakMap;function kf(e,t,s){const i=function(e){let t=Uf.get(e);void 0===t&&(t=new WeakMap,Uf.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 zf extends na{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 ts;i.isRenderTargetTexture=!0,this._texture=Ju(i),this._width=uh(0),this._height=uh(0),this._maxMip=uh(0),this.updateBeforeType=Hn}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:kf(i,e.renderer,this._generator),null!==t&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){null===this._generator&&(this._generator=new Ff(e.renderer)),this.updateBefore(e);let t=this.uvNode;null===t&&e.context.getUV&&(t=e.context.getUV(this,e)),t=ud.mul(go(t.x,t.y.negate(),t.z));let s=this.levelNode;return null===s&&e.context.getTextureLevel&&(s=e.context.getTextureLevel(this)),df(this._texture,t,s,this._width,this._height,this._maxMip)}dispose(){super.dispose(),null!==this._generator&&this._generator.dispose()}}const Vf=Ya(zf).setParameterLength(1,3),Gf=new WeakMap;class jf extends sm{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 i=s.isTextureNode?s.value:t[s.property],r=this._getPMREMNodeCache(e.renderer);let n=r.get(i);void 0===n&&(n=Vf(i),r.set(i,n)),s=n}const i=!0===t.useAnisotropy||t.anisotropy>0?$d:sd,r=s.context($f(Bo,i)).mul(ld),n=s.context(Wf(id)).mul(Math.PI).mul(ld),a=Bu(r),o=Bu(n);e.context.radiance.addAssign(a),e.context.iblIrradiance.addAssign(o);const h=e.context.lightingModel.clearcoatRadiance;if(h){const e=s.context($f(Do,rd)).mul(ld),t=Bu(e);h.addAssign(t)}}_getPMREMNodeCache(e){let t=Gf.get(e);return void 0===t&&(t=new WeakMap,Gf.set(e,t)),t}}const $f=(e,t)=>{let s=null;return{getUV:()=>(null===s&&(s=qc.negate().reflect(t),s=zl(e).mix(s,t).normalize(),s=s.transformDirection(Rc)),s),getTextureLevel:()=>e}},Wf=e=>({getUV:()=>e,getTextureLevel:()=>ao(1)}),Hf=new zr;class qf extends Em{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(Hf),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return null===t&&e.environmentNode&&(t=e.environmentNode),t?new jf(t):null}setupLightingModel(){return new Xg}setupSpecular(){const e=jl(go(.04),Ro.rgb,Fo);Wo.assign(go(.04)),Ho.assign(e),qo.assign(1)}setupVariants(){const e=this.metalnessNode?ao(this.metalnessNode):cp;Fo.assign(e);let t=this.roughnessNode?ao(this.roughnessNode):up;t=rg({roughness:t}),Bo.assign(t),this.setupSpecular(),Co.assign(Ro.rgb.mul(e.oneMinus()))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}const Xf=new Vr;class Yf extends qf{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(Xf),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?ao(this.iorNode):Mp;Zo.assign(e),Wo.assign(Cl(kl(Zo.sub(1).div(Zo.add(1))).mul(op),go(1)).mul(ap)),Ho.assign(jl(Wo,Ro.rgb,Fo)),qo.assign(jl(ap,1,Fo))}setupLightingModel(){return new Xg(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?ao(this.clearcoatNode):pp,t=this.clearcoatRoughnessNode?ao(this.clearcoatRoughnessNode):mp;Lo.assign(e),Do.assign(rg({roughness:t}))}if(this.useSheen){const e=this.sheenNode?go(this.sheenNode):yp,t=this.sheenRoughnessNode?ao(this.sheenRoughnessNode):bp;Io.assign(e),Oo.assign(t)}if(this.useIridescence){const e=this.iridescenceNode?ao(this.iridescenceNode):xp,t=this.iridescenceIORNode?ao(this.iridescenceIORNode):vp,s=this.iridescenceThicknessNode?ao(this.iridescenceThicknessNode):Tp;Uo.assign(e),ko.assign(t),zo.assign(s)}if(this.useAnisotropy){const e=(this.anisotropyNode?uo(this.anisotropyNode):_p).toVar();Go.assign(e.length()),io(Go.equal(0),()=>{e.assign(uo(1,0))}).Else(()=>{e.divAssign(uo(Go)),Go.assign(Go.saturate())}),Vo.assign(Go.pow2().mix(Bo.pow2(),1)),jo.assign(jd[0].mul(e.x).add(jd[1].mul(e.y))),$o.assign(jd[1].mul(e.x).sub(jd[0].mul(e.y)))}if(this.useTransmission){const e=this.transmissionNode?ao(this.transmissionNode):Sp,t=this.thicknessNode?ao(this.thicknessNode):wp,s=this.attenuationDistanceNode?ao(this.attenuationDistanceNode):Np,i=this.attenuationColorNode?go(this.attenuationColorNode):Ap;if(Jo.assign(e),eh.assign(t),th.assign(s),sh.assign(i),this.useDispersion){const e=this.dispersionNode?ao(this.dispersionNode):Fp;ih.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?go(this.clearcoatNormalNode):gp}setup(e){e.context.setupClearcoatNormal=()=>ru(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.iorNode=e.iorNode,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 Kf=eo(({normal:e,lightDirection:t,builder:s})=>{const i=e.dot(t),r=uo(i.mul(.5).add(.5),0);if(s.material.gradientMap){const e=wd("gradientMap","texture").context({getUV:()=>r});return go(e.r)}{const e=r.fwidth().mul(.5);return jl(go(.7),go(1),ql(ao(.7).sub(e.x),ao(.7).add(e.x),r.x))}});class Qf extends $m{direct({lightDirection:e,lightColor:t,reflectedLight:s},i){const r=Kf({normal:Qc,lightDirection:e,builder:i}).mul(t);s.directDiffuse.addAssign(r.mul(Ym({diffuseColor:Ro.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:s,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(s.mul(Ym({diffuseColor:Ro}))),i.indirectDiffuse.mulAssign(t)}}const Zf=new jr;class Jf extends Em{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Zf),this.setValues(e)}setupLightingModel(){return new Qf}}const ey=eo(()=>{const e=go(qc.z,0,qc.x.negate()).normalize(),t=qc.cross(e);return uo(e.dot(sd),t.dot(sd)).mul(.495).add(.5)}).once(["NORMAL","VERTEX"])().toVar("matcapUV"),ty=new Hr;class sy extends Em{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(ty),this.setValues(e)}setupVariants(e){const t=ey;let s;s=e.material.matcap?wd("matcap","texture").context({getUV:()=>t}):go(jl(.2,.8,t.y)),Ro.rgb.mulAssign(s.rgb)}}class iy extends na{static get type(){return"RotateNode"}constructor(e,t){super(),this.positionNode=e,this.rotationNode=t}generateNodeType(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 So(e,i,i.negate(),e).mul(s)}{const e=t,i=Mo(_o(1,0,0,0),_o(0,al(e.x),rl(e.x).negate(),0),_o(0,rl(e.x),al(e.x),0),_o(0,0,0,1)),r=Mo(_o(al(e.y),0,rl(e.y),0),_o(0,1,0,0),_o(rl(e.y).negate(),0,al(e.y),0),_o(0,0,0,1)),n=Mo(_o(al(e.z),rl(e.z).negate(),0,0),_o(rl(e.z),al(e.z),0,0),_o(0,0,1,0),_o(0,0,0,1));return i.mul(r).mul(n).mul(_o(s,1)).xyz}}}const ry=Ya(iy).setParameterLength(2),ny=new qi;class ay extends Em{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(ny),this.setValues(e)}setupPositionView(e){const{object:t,camera:s}=e,{positionNode:i,rotationNode:r,scaleNode:n,sizeAttenuation:a}=this,o=Ic.mul(go(i||0));let h=uo(Lc[0].xyz.length(),Lc[1].xyz.length());null!==n&&(h=h.mul(uo(n))),s.isPerspectiveCamera&&!1===a&&(h=h.mul(o.z.negate()));let l=Vc.xy;if(t.center&&!0===t.center.isVector2){const e=((e,t,s)=>new pu(e,t,s))("center","vec2",t);l=l.sub(e.sub(.5))}l=l.mul(h);const u=ao(r||fp),c=ry(l,u);return _o(o.xy.add(c),o.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 oy=new Cr,hy=new Dt;class ly extends ay{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(oy),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return Ic.mul(go(e||Gc)).xyz}setupVertexSprite(e){const{material:t,camera:s}=e,{rotationNode:i,scaleNode:r,sizeNode:n,sizeAttenuation:a}=this;let o=super.setupVertex(e);if(!0!==t.isNodeMaterial)return o;let h=null!==n?uo(n):Bp;h=h.mul(uc),s.isPerspectiveCamera&&!0===a&&(h=h.mul(uy.div(Hc.z.negate()))),r&&r.isNode&&(h=h.mul(uo(r)));let l=Vc.xy;if(i&&i.isNode){const e=ao(i);l=ry(l,e)}return l=l.mul(h),l=l.div(gc.div(2)),l=l.mul(o.w),o=o.add(_o(l,0,0)),o}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 uy=uh(1).onFrameUpdate(function({renderer:e}){const t=e.getSize(hy);this.value=.5*t.y});class cy extends $m{constructor(){super(),this.shadowNode=ao(1).toVar("shadowMask")}direct({lightNode:e}){null!==e.shadowNode&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){Ro.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(Ro.rgb)}}const dy=new kr;class py extends Em{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(dy),this.setValues(e)}setupLightingModel(){return new cy}}Ao("vec3"),Ao("vec3"),Ao("vec3");class my{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(){null!==this._context&&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 gy{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 fy=0;class yy{constructor(e,t,s,i,r,n,a,o,h,l){this.id=fy++,this._nodes=e,this._geometries=t,this.renderer=s,this.object=i,this.material=r,this.scene=n,this.camera=a,this.lightsNode=o,this.context=h,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=l,this.clippingContextCacheKey=null!==l?l.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.id),void 0===e)continue;s.push(e);const a=e.isInterleavedBufferAttribute?e.data:e;i.add(a)}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}),a=this.getIndex(),o=null!==a;let h=1;if(!0===s.isInstancedBufferGeometry?h=s.instanceCount:void 0!==e.count&&(h=Math.max(0,e.count)),0===h)return null;if(n.instanceCount=h,!0===e.isBatchedMesh)return n;let l=1;!0!==t.wireframe||e.isPoints||e.isLineSegments||e.isLine||e.isLineLoop||(l=2);let u=r.start*l,c=(r.start+r.count)*l;null!==i&&(u=Math.max(u,i.start*l),c=Math.min(c,(i.start+i.count)*l));const d=s.attributes.position;let p=1/0;o?p=a.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+",",Ln(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=In(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=In(e,1)),e=In(e,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 by=[];class _y{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,a,o){const h=this.getChainMap(o);by[0]=e,by[1]=t,by[2]=n,by[3]=r;let l=h.get(by);return void 0===l?(l=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,s,i,r,n,a,o),h.set(by,l)):(l.camera=i,l.updateClipping(a),l.needsGeometryUpdate&&l.setGeometry(e.geometry),(l.version!==t.version||l.needsUpdate)&&(l.initialCacheKey!==l.getCacheKey()?(l.dispose(),l=this.get(e,t,s,i,r,n,a,o)):l.version=t.version)),by[0]=null,by[1]=null,by[2]=null,by[3]=null,l}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new gy)}dispose(){this.chainMaps={}}createRenderObject(e,t,s,i,r,n,a,o,h,l,u){const c=this.getChainMap(u),d=new yy(e,t,s,i,r,n,a,o,h,l);return d.onDispose=()=>{this.pipelines.delete(d),this.bindings.deleteForRender(d),this.nodes.delete(d),c.delete(d.getChainArray())},d}}class xy{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 vy=1,Ty=2,Sy=3,wy=4,My=16;class Ny extends xy{constructor(e,t){super(),this.backend=e,this.info=t}delete(e){const t=super.delete(e);return null!==t&&(this.backend.destroyAttribute(e),this.info.destroyAttribute(e)),t}update(e,t){const s=this.get(e);if(void 0===s.version)t===vy?(this.backend.createAttribute(e),this.info.createAttribute(e)):t===Ty?(this.backend.createIndexAttribute(e),this.info.createIndexAttribute(e)):t===Sy?(this.backend.createStorageAttribute(e),this.info.createStorageAttribute(e)):t===wy&&(this.backend.createIndirectStorageAttribute(e),this.info.createIndirectStorageAttribute(e)),s.version=this._getBufferAttribute(e).version;else{const t=this._getBufferAttribute(e);(s.version<t.version||t.usage===ot)&&(this.backend.updateAttribute(e),s.version=t.version)}}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}function Ay(e){return null!==e.index?e.index.version:e.attributes.position.version}function Ey(e){return null!==e.index?e.index.id:e.attributes.position.id}function Ry(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(i.count>=65535?Ai:Ni)(t,1);return r.version=Ay(e),r.__id=Ey(e),r}class Cy extends xy{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,Sy):this.updateAttribute(e,vy);const s=this.getIndex(e);null!==s&&this.updateAttribute(s,Ty);const i=e.geometry.indirect;null!==i&&this.updateAttribute(i,wy)}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=Ry(t),e.set(t,s)):s.version===Ay(t)&&s.__id===Ey(t)||(this.attributes.delete(s),s=Ry(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 Py{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,attributes:0,indexAttributes:0,storageAttributes:0,indirectStorageAttributes:0,readbackBuffers:0,programs:0,renderTargets:0,total:0,texturesSize:0,attributesSize:0,indexAttributesSize:0,storageAttributesSize:0,indirectStorageAttributesSize:0,readbackBuffersSize:0,programsSize:0},this.memoryMap=new Map}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):_t("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;for(const e in this.memory)this.memory[e]=0;this.memoryMap.clear()}createTexture(e){const t=this._getTextureMemorySize(e);this.memoryMap.set(e,t),this.memory.textures++,this.memory.total+=t,this.memory.texturesSize+=t}destroyTexture(e){const t=this.memoryMap.get(e)||0;this.memoryMap.delete(e),this.memory.textures--,this.memory.total-=t,this.memory.texturesSize-=t}_createAttribute(e,t){const s=this._getAttributeMemorySize(e);this.memoryMap.set(e,{size:s,type:t}),this.memory[t]++,this.memory.total+=s,this.memory[t+"Size"]+=s}createAttribute(e){this._createAttribute(e,"attributes")}createIndexAttribute(e){this._createAttribute(e,"indexAttributes")}createStorageAttribute(e){this._createAttribute(e,"storageAttributes")}createIndirectStorageAttribute(e){this._createAttribute(e,"indirectStorageAttributes")}destroyAttribute(e){const t=this.memoryMap.get(e);t&&(this.memoryMap.delete(e),this.memory[t.type]--,this.memory.total-=t.size,this.memory[t.type+"Size"]-=t.size)}createReadbackBuffer(e){const t=e.maxByteLength;this.memoryMap.set(e,{size:t,type:"readbackBuffers"}),this.memory.readbackBuffers++,this.memory.total+=t,this.memory.readbackBuffersSize+=t}destroyReadbackBuffer(e){const{size:t}=this.memoryMap.get(e);this.memoryMap.delete(e),this.memory.readbackBuffers--,this.memory.total-=t,this.memory.readbackBuffersSize-=t}createProgram(e){const t=e.code.length;this.memoryMap.set(e,t),this.memory.programs++,this.memory.total+=t,this.memory.programsSize+=t}destroyProgram(e){const t=this.memoryMap.get(e)||0;this.memoryMap.delete(e),this.memory.programs--,this.memory.total-=t,this.memory.programsSize-=t}_getTextureMemorySize(e){if(e.isCompressedTexture)return 1;let t=1;e.type===$||e.type===j?t=1:e.type===W||e.type===H||e.type===K?t=2:e.type!==q&&e.type!==X&&e.type!==Y||(t=4);let s=4;e.format===se||e.format===oe||e.format===he||e.format===ne||e.format===ae?s=1:e.format===le||e.format===ue?s=2:e.format!==ie&&1032!==e.format||(s=3);let i=t*s;e.type===Q||e.type===Z?i=2:e.type!==J&&e.type!==ee&&e.type!==te||(i=4);const r=e.width||1,n=e.height||1,a=e.isCubeTexture?6:e.depth||1;let o=r*n*a*i;const h=e.mipmaps;if(h&&h.length>0){let e=0;for(let t=0;t<h.length;t++){const s=h[t];if(s.data)e+=s.data.byteLength;else{e+=(s.width||Math.max(1,r>>t))*(s.height||Math.max(1,n>>t))*a*i}}o+=e}else e.generateMipmaps&&(o*=1.333);return Math.round(o)}_getAttributeMemorySize(e){return e.isInterleavedBufferAttribute&&(e=e.data),e.array?e.array.byteLength:e.count&&e.itemSize?e.count*e.itemSize*4:0}}class By{constructor(e){this.cacheKey=e,this.usedTimes=0}}class Fy extends By{constructor(e,t,s){super(e),this.vertexProgram=t,this.fragmentProgram=s}}class Ly extends By{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let Dy=0;class Iy{constructor(e,t,s,i=null,r=null){this.id=Dy++,this.code=e,this.stage=t,this.name=s,this.transforms=i,this.attributes=r,this.usedTimes=0}}class Oy extends xy{constructor(e,t,s){super(),this.backend=e,this.nodes=t,this.info=s,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 a=this.programs.compute.get(n.computeShader);void 0===a&&(r&&0===r.computeProgram.usedTimes&&this._releaseProgram(r.computeProgram),a=new Iy(n.computeShader,"compute",e.name,n.transforms,n.nodeAttributes),this.programs.compute.set(n.computeShader,a),s.createProgram(a),this.info.createProgram(a));const o=this._getComputeCacheKey(e,a);let h=this.caches.get(o);void 0===h&&(r&&0===r.usedTimes&&this._releasePipeline(r),h=this._getComputePipeline(e,a,o,t)),h.usedTimes++,a.usedTimes++,i.version=e.version,i.pipeline=h}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(),a=e.material?e.material.name:"";let o=this.programs.vertex.get(n.vertexShader);void 0===o&&(r&&0===r.vertexProgram.usedTimes&&this._releaseProgram(r.vertexProgram),o=new Iy(n.vertexShader,"vertex",a),this.programs.vertex.set(n.vertexShader,o),s.createProgram(o),this.info.createProgram(o));let h=this.programs.fragment.get(n.fragmentShader);void 0===h&&(r&&0===r.fragmentProgram.usedTimes&&this._releaseProgram(r.fragmentProgram),h=new Iy(n.fragmentShader,"fragment",a),this.programs.fragment.set(n.fragmentShader,h),s.createProgram(h),this.info.createProgram(h));const l=this._getRenderCacheKey(e,o,h);let u=this.caches.get(l);void 0===u?(r&&0===r.usedTimes&&this._releasePipeline(r),u=this._getRenderPipeline(e,o,h,l,t)):e.pipeline=u,u.usedTimes++,o.usedTimes++,h.usedTimes++,i.pipeline=u}return i.pipeline}isReady(e){const t=this.get(e).pipeline;if(void 0===t)return!1;const s=this.backend.get(t);return void 0!==s.pipeline&&null!==s.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 Ly(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 Fy(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),this.info.destroyProgram(e)}_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 Uy extends xy{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?wy:Sy;this.attributes.update(e,s)}}_update(e,t){const{backend:s}=this;let i=!1,r=!0,n=0,a=0;for(const t of e.bindings){if(!1!==this.nodes.updateGroup(t)){if(t.isStorageBuffer){const e=t.attribute,r=e.isIndirectStorageBufferAttribute?wy:Sy,n=s.get(t);this.attributes.update(e,r),n.attribute!==e&&(n.attribute=e,i=!0)}if(t.isUniformBuffer){t.update()&&s.updateBinding(t)}else if(t.isSampledTexture){const o=t.update(),h=t.texture,l=this.textures.get(h);o&&(this.textures.updateTexture(h),t.generation!==l.generation&&(t.generation=l.generation,i=!0),l.bindGroups.add(e));if(void 0!==s.get(h).externalTexture||l.isDefaultTexture?r=!1:(n=10*n+h.id,a+=h.version),!0===h.isStorageTexture&&!0===h.mipmapsAutoUpdate){const e=this.get(h);!0===t.store?e.needsMipmap=!0:this.textures.needsMipmaps(h)&&!0===e.needsMipmap&&(this.backend.generateMipmaps(h),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)}}t.isBuffer&&t.updateRanges.length>0&&t.clearUpdateRanges()}}!0===i&&this.backend.updateBindings(e,t,r?n:0,a)}}function ky(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 zy(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 Vy(e){return(e.transmission>0||e.transmissionNode&&e.transmissionNode.isNode)&&2===e.side&&!1===e.forceSinglePass}class Gy{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,a){let o=this.renderItems[this.renderItemsIndex];return void 0===o?(o={id:e.id,object:e,geometry:t,material:s,groupOrder:i,renderOrder:e.renderOrder,z:r,group:n,clippingContext:a},this.renderItems[this.renderItemsIndex]=o):(o.id=e.id,o.object=e,o.geometry=t,o.material=s,o.groupOrder=i,o.renderOrder=e.renderOrder,o.z=r,o.group=n,o.clippingContext=a),this.renderItemsIndex++,o}push(e,t,s,i,r,n,a){const o=this.getNextRenderItem(e,t,s,i,r,n,a);!0===e.occlusionTest&&this.occlusionQueryCount++,!0===s.transparent||s.transmission>0||s.transmissionNode&&s.transmissionNode.isNode||s.backdropNode&&s.backdropNode.isNode?(Vy(s)&&this.transparentDoublePass.push(o),this.transparent.push(o)):this.opaque.push(o)}unshift(e,t,s,i,r,n,a){const o=this.getNextRenderItem(e,t,s,i,r,n,a);!0===s.transparent||s.transmission>0||s.transmissionNode&&s.transmissionNode.isNode||s.backdropNode&&s.backdropNode.isNode?(Vy(s)&&this.transparentDoublePass.unshift(o),this.transparent.unshift(o)):this.opaque.unshift(o)}pushBundle(e){this.bundles.push(e)}pushLight(e){this.lightsArray.push(e)}sort(e,t){this.opaque.length>1&&this.opaque.sort(e||ky),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||zy),this.transparent.length>1&&this.transparent.sort(t||zy)}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 jy=[];class $y{constructor(e){this.lighting=e,this.lists=new gy}get(e,t){const s=this.lists;jy[0]=e,jy[1]=t;let i=s.get(jy);return void 0===i&&(i=new Gy(this.lighting,e,t),s.set(jy,i)),jy[0]=null,jy[1]=null,i}dispose(){this.lists=new gy}}let Wy=0;class Hy{constructor(){this.id=Wy++,this.mrt=null,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 ss,this.scissor=!1,this.scissorValue=new ss,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.camera=null,this.isRenderContext=!0}getCacheKey(){return qy(this)}}function qy(e){const{textures:t,activeCubeFace:s,activeMipmapLevel:i}=e,r=[s,i];for(const e of t)r.push(e.id);return Dn(r)}class Xy{constructor(e){this.renderer=e,this._renderContexts={}}get(e=null,t=null,s=0){let i;if(null===e)i="default";else{const t=e.texture.format,s=e.texture.type;i=`${e.textures.length}:${t}:${s}:${e.samples}:${e.depthBuffer}:${e.stencilBuffer}`}const r=i+"-"+(null!==t?t.id:"default")+"-"+s;let n=this._renderContexts[r];return void 0===n&&(n=new Hy,n.mrt=t,this._renderContexts[r]=n),null!==e&&(n.sampleCount=0===e.samples?1:e.samples),n.clearDepthValue=this.renderer.getClearDepth(),n.clearStencilValue=this.renderer.getClearStencil(),n}dispose(){this._renderContexts={}}}const Yy=new Ot;class Ky extends xy{constructor(e,t,s){super(),this.renderer=e,this.backend=t,this.info=s,this._htmlTextures=new Set}updateRenderTarget(e,t=0){const s=this.get(e),i=0===e.samples?1:e.samples,r=s.depthTextureMips||(s.depthTextureMips={}),n=e.textures,a=this.getSize(n[0]),o=a.width>>t,h=a.height>>t;let l=e.depthTexture||r[t];const u=!0===e.depthBuffer||!0===e.stencilBuffer;let c=!1;void 0===l&&u&&(l=new Fr,l.format=e.stencilBuffer?ae:ne,l.type=e.stencilBuffer?J:X,l.image.width=o,l.image.height=h,l.image.depth=a.depth,l.renderTarget=e,l.isArrayTexture=!0===e.multiview&&a.depth>1,r[t]=l),s.width===a.width&&a.height===s.height||(c=!0,l&&(l.needsUpdate=!0,l.image.width=o,l.image.height=h,l.image.depth=l.isArrayTexture?l.image.depth:1)),s.width=a.width,s.height=a.height,s.textures=n,s.depthTexture=l||null,s.depth=e.depthBuffer,s.stencil=e.stencilBuffer,s.renderTarget=e,s.sampleCount!==i&&(c=!0,l&&(l.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)}l&&this.updateTexture(l,d)}!0!==s.initialized&&(s.initialized=!0,this.info.memory.renderTargets++,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:j}if(e.isHTMLTexture&&e.image){const t=this.renderer.domElement;if("requestPaint"in t){if(t.hasAttribute("layoutsubtree")||t.setAttribute("layoutsubtree","true"),e.image.parentNode!==t&&t.appendChild(e.image),0===this._htmlTextures.size){const e=this._htmlTextures;t.onpaint=t=>{const s=t&&t.changedElements;for(const t of e)s&&!s.includes(t.image)||(t.needsUpdate=!0)}}this._htmlTextures.add(e)}}const{width:n,height:a,depth:o}=this.getSize(e);if(t.width=n,t.height=a,t.depth=o,t.needsMipmaps=this.needsMipmaps(e),t.levels=t.needsMipmaps?this.getMipLevels(e,n,a):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)bt("Renderer: Texture marked for update but image is undefined.");else if(!1===i.complete)bt("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,s.bindGroups=new Set,this.info.createTexture(e),e.isVideoTexture&&!0===Wt.enabled&&Wt.getTransfer(e.colorSpace)!==Ke&&bt("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=Yy){let s=e.images?e.images[0]:e.image;return s?(void 0!==s.image&&(s=s.image),e.isHTMLTexture?(t.width=s.offsetWidth||1,t.height=s.offsetHeight||1,t.depth=1):"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),this.info.memory.renderTargets--}}_destroyTexture(e){if(!0===this.has(e)){const t=this.get(e);e.removeEventListener("dispose",t.onDispose);const s=t.isDefaultTexture;if(this.backend.destroyTexture(e,s),t.bindGroups)for(const e of t.bindGroups){const t=this.backend.get(e);t.groups=void 0,t.versions=void 0}this._htmlTextures.delete(e),this.delete(e),this.info.destroyTexture(e)}}}class Qy extends zs{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 Zy extends No{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):(_t(`TSL: Member "${t}" not found in struct "${s}".`,new Bn),r="float"),r}getHash(){return String(this.id)}generate(){return this.name}}class Jy extends sa{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(e)?this.outputNode.getElementType(e):"void"}generateNodeType(e){return this.hasOutput(e)?this.outputNode.getNodeType(e):"void"}getMemberType(e,t){return this.hasOutput(e)?this.outputNode.getMemberType(e,t):"void"}addToStack(e,t=this.nodes.length){return!0!==e.isNode?(_t("TSL: Invalid node added to stack.",new Bn),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 $a(t);return this._currentCond=Ql(e,s),this.addToStack(this._currentCond)}ElseIf(e,t){const s=new $a(t),i=Ql(e,s);return this._currentCond.elseNode=i,this._currentCond=i,this}Else(e){return this._currentCond.elseNode=new $a(e),this}Switch(e){return this._expressionNode=Wa(e),this}Case(...e){const t=[];if(e.length>=2)for(let s=0;s<e.length-1;s++)t.push(this._expressionNode.equal(Wa(e[s])));else _t("TSL: Invalid parameter length. Case() requires at least two parameters.",new Bn);const s=new $a(e[e.length-1]);let i=t[0];for(let e=1;e<t.length;e++)i=i.or(t[e]);const r=Ql(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}hasOutput(e){return this.outputNode&&this.outputNode.isNode&&"void"!==this.outputNode.getNodeType(e)}build(e,...t){const s=so(),i=e.buildStage;to(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 a=this.nodes.filter(e=>-1===n.indexOf(e));for(const e of a)r(e);let o;return o=this.hasOutput(e)?this.outputNode.build(e,...t):super.build(e,...t),to(s),e.removeActiveStack(this),o}}const eb=Ya(Jy).setParameterLength(0,1);class tb extends na{static get type(){return"BitcastNode"}constructor(e,t,s=null){super(),this.valueNode=e,this.conversionType=t,this.inputType=s,this.isBitcastNode=!0}generateNodeType(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 sb=Qa(tb).setParameterLength(2),ib={};class rb extends Vh{static get type(){return"BitcountNode"}constructor(e,t){super(e,t),this.isBitcountNode=!0}_resolveElementType(e,t,s){"int"===s?t.assign(sb(e,"uint")):t.assign(e)}_returnDataNode(e){switch(e){case"uint":return ho;case"int":return oo;case"uvec2":return po;case"uvec3":return yo;case"uvec4":return vo;case"ivec2":return co;case"ivec3":return fo;case"ivec4":return xo}}_createTrailingZerosBaseLayout(e,t){const s=this._returnDataNode(t),i=eo(([e])=>{const i=ho(0);this._resolveElementType(e,i,t);const r=(e=>new tb(e,"uint","float"))(ao(i.bitAnd(_l(i)))),n=r.shiftRight(23).sub(127);return s(n)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]});return i}_createLeadingZerosBaseLayout(e,t){const s=this._returnDataNode(t),i=eo(([e])=>{io(e.equal(ho(0)),()=>ho(32));const i=ho(0),r=ho(0);return this._resolveElementType(e,i,t),io(i.shiftRight(16).equal(0),()=>{r.addAssign(16),i.shiftLeftAssign(16)}),io(i.shiftRight(24).equal(0),()=>{r.addAssign(8),i.shiftLeftAssign(8)}),io(i.shiftRight(28).equal(0),()=>{r.addAssign(4),i.shiftLeftAssign(4)}),io(i.shiftRight(30).equal(0),()=>{r.addAssign(2),i.shiftLeftAssign(2)}),io(i.shiftRight(31).equal(0),()=>{r.addAssign(1)}),s(r)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]});return i}_createOneBitsBaseLayout(e,t){const s=this._returnDataNode(t),i=eo(([e])=>{const i=ho(0);this._resolveElementType(e,i,t),i.assign(i.sub(i.shiftRight(ho(1)).bitAnd(ho(1431655765)))),i.assign(i.bitAnd(ho(858993459)).add(i.shiftRight(ho(2)).bitAnd(ho(858993459))));const r=i.add(i.shiftRight(ho(4))).bitAnd(ho(252645135)).mul(ho(16843009)).shiftRight(ho(24));return s(r)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]});return i}_createMainLayout(e,t,s,i){const r=this._returnDataNode(t),n=eo(([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}]});return n}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),a=e.getTypeLength(r),o=`${t}_base_${n}`,h=`${t}_${r}`;let l=ib[o];if(void 0===l){switch(t){case rb.COUNT_LEADING_ZEROS:l=this._createLeadingZerosBaseLayout(o,n);break;case rb.COUNT_TRAILING_ZEROS:l=this._createTrailingZerosBaseLayout(o,n);break;case rb.COUNT_ONE_BITS:l=this._createOneBitsBaseLayout(o,n)}ib[o]=l}let u=ib[h];void 0===u&&(u=this._createMainLayout(h,r,a,l),ib[h]=u);return eo(()=>u(s))()}}rb.COUNT_TRAILING_ZEROS="countTrailingZeros",rb.COUNT_LEADING_ZEROS="countLeadingZeros",rb.COUNT_ONE_BITS="countOneBits",new ns;const nb=new is;cc.flipX(),nb.depthTexture=new Fr(1,1);const ab=new pn(-1,1,1,-1,0,1);class ob extends Vi{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new Ri([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new Ri(t,2))}}const hb=new ob;class lb extends mr{constructor(e=null){super(hb,e),this.camera=ab,this.isQuadMesh=!0}async renderAsync(e){xt('QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await e.init(),e.render(this,ab)}render(e){e.render(this,ab)}}const ub=eo(([e])=>il(ao(52.9829189).mul(il(Il(e,uo(.06711056,.00583715)))))).setLayout({name:"interleavedGradientNoise",type:"float",inputs:[{name:"position",type:"vec2"}]}),cb=eo(([e,t,s])=>{const i=ao(2.399963229728653),r=Zh(ao(e).add(.5).div(ao(t))),n=ao(e).mul(i).add(s);return uo(al(n),rl(n)).mul(r)}).setLayout({name:"vogelDiskSample",type:"vec2",inputs:[{name:"sampleIndex",type:"int"},{name:"samplesCount",type:"int"},{name:"phi",type:"float"}]});class db extends sa{static get type(){return"EventNode"}constructor(e,t){super("void"),this.eventType=e,this.callback=t,e===db.OBJECT?this.updateType=qn:e===db.MATERIAL?this.updateType=Hn:e===db.FRAME?this.updateType=Wn:e===db.BEFORE_OBJECT?this.updateBeforeType=qn:e===db.BEFORE_MATERIAL?this.updateBeforeType=Hn:e===db.BEFORE_FRAME&&(this.updateBeforeType=Wn)}update(e){this.callback(e)}updateBefore(e){this.callback(e)}}db.OBJECT="object",db.MATERIAL="material",db.FRAME="frame",db.BEFORE_OBJECT="beforeObject",db.BEFORE_MATERIAL="beforeMaterial",db.BEFORE_FRAME="beforeFrame";const pb=new ns,mb=uh(0).setGroup(oh).onRenderUpdate(({scene:e})=>e.backgroundBlurriness),gb=uh(1).setGroup(oh).onRenderUpdate(({scene:e})=>e.backgroundIntensity),fb=uh(new ns).setGroup(oh).onRenderUpdate(({scene:e})=>{const t=e.background;return null!==t&&t.isTexture&&300!==t.mapping?pb.makeRotationFromEuler(e.backgroundRotation).transpose():pb.identity(),pb});eo(({texture:e,uv:t})=>{const s=1e-4,i=go().toVar();return io(t.x.lessThan(s),()=>{i.assign(go(1,0,0))}).ElseIf(t.y.lessThan(s),()=>{i.assign(go(0,1,0))}).ElseIf(t.z.lessThan(s),()=>{i.assign(go(0,0,1))}).ElseIf(t.x.greaterThan(.9999),()=>{i.assign(go(-1,0,0))}).ElseIf(t.y.greaterThan(.9999),()=>{i.assign(go(0,-1,0))}).ElseIf(t.z.greaterThan(.9999),()=>{i.assign(go(0,0,-1))}).Else(()=>{const s=.01,r=e.sample(t.add(go(-.01,0,0))).r.sub(e.sample(t.add(go(s,0,0))).r),n=e.sample(t.add(go(0,-.01,0))).r.sub(e.sample(t.add(go(0,s,0))).r),a=e.sample(t.add(go(0,0,-.01))).r.sub(e.sample(t.add(go(0,0,s))).r);i.assign(go(r,n,a))}),i.normalize()}),eo(([e,t])=>e.mul(t).floor().div(t));const yb=new Dt;class bb extends Qu{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.isPassTextureNode=!0,this.setUpdateMatrix(!1)}setup(e){return e.getNodeProperties(this).passNode=this.passNode,super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class _b extends bb{static get type(){return"PassMultipleTextureNode"}constructor(e,t,s=!1){super(e,null),this.textureName=t,this.previousTexture=s,this.isPassMultipleTextureNode=!0}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 xb extends na{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 Fr;r.isRenderTargetTexture=!0,r.name="depth";const n=new is(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:K,...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=uh(0),this._cameraFar=uh(0),this._mrt=null,this._layers=null,this._resolutionScale=1,this._viewport=null,this._scissor=null,this.isPassNode=!0,this.updateBeforeType=Wn,this.global=!0}setResolutionScale(e){return this._resolutionScale=e,this}getResolutionScale(){return this._resolutionScale}setResolution(e){return bt("PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead."),this.setResolutionScale(e)}getResolution(){return bt("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 _b(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 _b(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=bm(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=fm(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(),!0===e.reversedDepthBuffer&&(this.renderTarget.depthTexture.type=Y),this.scope===xb.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),yb.set(n.width,n.height)):(i=this.camera,r=t.getPixelRatio(),t.getSize(yb)),this._pixelRatio=r,this.setSize(yb.width,yb.height);const a=t.getRenderTarget(),o=t.getMRT(),h=t.autoClear,l=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:Jl({...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(a),t.setMRT(o),t.autoClear=h,t.transparent=l,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).multiplyScalar(this._pixelRatio*this._resolutionScale).floor(),this.renderTarget.scissorTest=!0):this.renderTarget.scissorTest=!1,null!==this._viewport&&this.renderTarget.viewport.copy(this._viewport).multiplyScalar(this._pixelRatio*this._resolutionScale).floor()}setScissor(e,t,s,i){null===e?this._scissor=null:(null===this._scissor&&(this._scissor=new ss),e.isVector4?this._scissor.copy(e):this._scissor.set(e,t,s,i))}setViewport(e,t,s,i){null===e?this._viewport=null:(null===this._viewport&&(this._viewport=new ss),e.isVector4?this._viewport.copy(e):this._viewport.set(e,t,s,i))}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}xb.COLOR="color",xb.DEPTH="depth";const vb=eo(([e,t])=>e.mul(t).clamp()).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),Tb=eo(([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"}]}),Sb=eo(([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"}]}),wb=eo(([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)}),Mb=eo(([e,t])=>{const s=wo(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),i=wo(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=s.mul(e),e=wb(e),(e=i.mul(e)).clamp()}).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),Nb=wo(go(1.6605,-.1246,-.0182),go(-.5876,1.1329,-.1006),go(-.0728,-.0083,1.1187)),Ab=wo(go(.6274,.0691,.0164),go(.3293,.9195,.088),go(.0433,.0113,.8956)),Eb=eo(([e])=>{const t=go(e).toVar(),s=go(t.mul(t)).toVar(),i=go(s.mul(s)).toVar();return ao(15.5).mul(i.mul(s)).sub(bh(40.14,i.mul(t))).add(bh(31.96,i).sub(bh(6.868,s.mul(t))).add(bh(.4298,s).add(bh(.1191,t).sub(.00232))))}),Rb=eo(([e,t])=>{const s=go(e).toVar(),i=wo(go(.856627153315983,.137318972929847,.11189821299995),go(.0951212405381588,.761241990602591,.0767994186031903),go(.0482516061458583,.101439036467562,.811302368396859)),r=wo(go(1.1271005818144368,-.1413297634984383,-.14132976349843826),go(-.11060664309660323,1.157823702216272,-.11060664309660294),go(-.016493938717834573,-.016493938717834257,1.2519364065950405)),n=ao(-12.47393),a=ao(4.026069);return s.mulAssign(t),s.assign(Ab.mul(s)),s.assign(i.mul(s)),s.assign(Pl(s,1e-10)),s.assign(Qh(s)),s.assign(s.sub(n).div(a.sub(n))),s.assign($l(s,0,1)),s.assign(Eb(s)),s.assign(r.mul(s)),s.assign(Ul(Pl(go(0),s),go(2.2))),s.assign(Nb.mul(s)),s.assign($l(s,0,1)),s}).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),Cb=eo(([e,t])=>{const s=ao(.76),i=ao(.15);e=e.mul(t);const r=Cl(e.r,Cl(e.g,e.b)),n=Ql(r.lessThan(.08),r.sub(bh(6.25,r.mul(r))),.04);e.subAssign(n);const a=Pl(e.r,Pl(e.g,e.b));io(a.lessThan(s),()=>e);const o=yh(1,s),h=yh(1,o.mul(o).div(a.add(o.sub(s))));e.mulAssign(h.div(a));const l=yh(1,_h(1,i.mul(a.sub(h)).add(1)));return jl(e,go(h),l)}).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class Pb extends sa{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}}class Bb extends Pb{static get type(){return"FunctionNode"}constructor(e="",t=[],s=""){super(e,t,s)}generateNodeType(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 a=e.getPropertyName(n),o=this.getNodeFunction(e).getCode(a);return n.code=o+"\n","property"===t?a:e.format(`${a}()`,r,t)}}function Fb(e){let t;const s=e.context.getViewZ;return void 0!==s&&(t=s(this)),(t||Hc.z).negate()}const Lb=eo(([e,t],s)=>{const i=Fb(s);return ql(e,t,i)}),Db=eo(([e],t)=>{const s=Fb(t);return e.mul(e,s,s).negate().exp().oneMinus()});eo(([e,t],s)=>{const i=Fb(s),r=t.sub($c.y).max(0).toConst().mul(i).toConst();return e.mul(e,r,r).negate().exp().oneMinus()});const Ib=eo(([e,t])=>_o(t.toFloat().mix(Yo.rgb,e.toVec3()),Yo.a));Ya(class extends sa{constructor(e){super(),this.scope=e,this.isBarrierNode=!0}setup(e){e.allowEarlyReturns=!1,e.allowGlobalVariables=!1}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 Ob extends sa{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)}generateNodeType(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),a=this.pointerNode,o=this.valueNode,h=[];h.push(`&${a.build(e,n)}`),null!==o&&h.push(o.build(e,n));const l=`${e.getMethod(i,r)}( ${h.join(", ")} )`;if(!(!!s&&(1===s.length&&!0===s[0].isStackNode)))return void 0===t.constNode&&(t.constNode=Iu(l,r).toConst()),t.constNode.build(e);e.addLineFlowCode(l,this)}}Ob.ATOMIC_LOAD="atomicLoad",Ob.ATOMIC_STORE="atomicStore",Ob.ATOMIC_ADD="atomicAdd",Ob.ATOMIC_SUB="atomicSub",Ob.ATOMIC_MAX="atomicMax",Ob.ATOMIC_MIN="atomicMin",Ob.ATOMIC_AND="atomicAnd",Ob.ATOMIC_OR="atomicOr",Ob.ATOMIC_XOR="atomicXor",Ya(Ob);class Ub extends na{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}generateNodeType(e){const t=this.method;return t===Ub.SUBGROUP_ELECT?"bool":t===Ub.SUBGROUP_BALLOT?"uvec4":this.getInputType(e)}generate(e,t){const s=this.method,i=this.getNodeType(e),r=this.getInputType(e),n=this.aNode,a=this.bNode,o=[];if(s===Ub.SUBGROUP_BROADCAST||s===Ub.SUBGROUP_SHUFFLE||s===Ub.QUAD_BROADCAST){const t=a.getNodeType(e);o.push(n.build(e,i),a.build(e,"float"===t?"int":i))}else s===Ub.SUBGROUP_SHUFFLE_XOR||s===Ub.SUBGROUP_SHUFFLE_DOWN||s===Ub.SUBGROUP_SHUFFLE_UP?o.push(n.build(e,i),a.build(e,"uint")):(null!==n&&o.push(n.build(e,r)),null!==a&&o.push(a.build(e,r)));const h=0===o.length?"()":`( ${o.join(", ")} )`;return e.format(`${e.getMethod(s,i)}${h}`,i,t)}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}let kb;function zb(e){kb=kb||new WeakMap;let t=kb.get(e);return void 0===t&&kb.set(e,t={}),t}function Vb(e){const t=zb(e);return t.shadowMatrix||(t.shadowMatrix=uh("mat4").setGroup(oh).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 Gb(e){const t=zb(e);return t.position||(t.position=uh(new Ot).setGroup(oh).onRenderUpdate((t,s)=>s.value.setFromMatrixPosition(e.matrixWorld)))}function jb(e){const t=zb(e);return t.viewPosition||(t.viewPosition=uh(new Ot).setGroup(oh).onRenderUpdate(({camera:t},s)=>{s.value=s.value||new Ot,s.value.setFromMatrixPosition(e.matrixWorld),s.value.applyMatrix4(t.matrixWorldInverse)}))}Ub.SUBGROUP_ELECT="subgroupElect",Ub.SUBGROUP_BALLOT="subgroupBallot",Ub.SUBGROUP_ADD="subgroupAdd",Ub.SUBGROUP_INCLUSIVE_ADD="subgroupInclusiveAdd",Ub.SUBGROUP_EXCLUSIVE_AND="subgroupExclusiveAdd",Ub.SUBGROUP_MUL="subgroupMul",Ub.SUBGROUP_INCLUSIVE_MUL="subgroupInclusiveMul",Ub.SUBGROUP_EXCLUSIVE_MUL="subgroupExclusiveMul",Ub.SUBGROUP_AND="subgroupAnd",Ub.SUBGROUP_OR="subgroupOr",Ub.SUBGROUP_XOR="subgroupXor",Ub.SUBGROUP_MIN="subgroupMin",Ub.SUBGROUP_MAX="subgroupMax",Ub.SUBGROUP_ALL="subgroupAll",Ub.SUBGROUP_ANY="subgroupAny",Ub.SUBGROUP_BROADCAST_FIRST="subgroupBroadcastFirst",Ub.QUAD_SWAP_X="quadSwapX",Ub.QUAD_SWAP_Y="quadSwapY",Ub.QUAD_SWAP_DIAGONAL="quadSwapDiagonal",Ub.SUBGROUP_BROADCAST="subgroupBroadcast",Ub.SUBGROUP_SHUFFLE="subgroupShuffle",Ub.SUBGROUP_SHUFFLE_XOR="subgroupShuffleXor",Ub.SUBGROUP_SHUFFLE_UP="subgroupShuffleUp",Ub.SUBGROUP_SHUFFLE_DOWN="subgroupShuffleDown",Ub.QUAD_BROADCAST="quadBroadcast";const $b=e=>Rc.transformDirection(Gb(e).sub(function(e){const t=zb(e);return t.targetPosition||(t.targetPosition=uh(new Ot).setGroup(oh).onRenderUpdate((t,s)=>s.value.setFromMatrixPosition(e.target.matrixWorld)))}(e))),Wb=(e,t)=>{for(const s of t)if(s.isAnalyticLightNode&&s.light.id===e)return s;return null},Hb=new WeakMap,qb=[];class Xb extends sa{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=Ao("vec3","totalDiffuse"),this.totalSpecularNode=Ao("vec3","totalSpecular"),this.outgoingLightNode=Ao("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(qb.push(s.id),qb.push(s.castShadow?1:0),!0===s.isSpotLight){const e=null!==s.map?s.map.id:-1,t=s.colorNode?s.colorNode.getCacheKey():-1;qb.push(e,t)}}const t=Dn(qb);return qb.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(Wa(e));else{let i=null;if(null!==s&&(i=Wb(e.id,s)),null===i){const t=r.getLightNodeClass(e.constructor);if(null===t){bt(`LightsNode.setupNodeLights: Light node not found for ${e.constructor.name}`);continue}!1===Hb.has(e)&&Hb.set(e,new t(e)),i=Hb.get(e)}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:a}=this;i.outgoingLight=s;const o=e.addStack();n.nodes=o.nodes,r.start(e);const{backdrop:h,backdropAlpha:l}=i,{directDiffuse:u,directSpecular:c,indirectDiffuse:d,indirectSpecular:p}=i.reflectedLight;let m=u.add(d);null!==h&&(m=go(null!==l?l.mix(m,h):h)),t.assign(m),a.assign(c.add(p)),s.assign(t.add(a)),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 Yb extends sa{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=Hn,this.isShadowBaseNode=!0}setupShadowPosition({context:e,material:t}){Kb.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||$c)}}const Kb=Ao("vec3","shadowPositionWorld");function Qb(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 zs),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 Zb=new WeakMap,Jb=eo(({depthTexture:e,shadowCoord:t,depthLayer:s})=>{let i=Ju(e,t.xy).setName("t_basic");return e.isArrayTexture&&(i=i.depth(s)),i.compare(t.z)}),e_=eo(({depthTexture:e,shadowCoord:t,shadow:s,depthLayer:i})=>{const r=(t,s)=>{let r=Ju(e,t);return e.isArrayTexture&&(r=r.depth(i)),r.compare(s)},n=vd("mapSize","vec2",s).setGroup(oh),a=vd("radius","float",s).setGroup(oh),o=uo(1).div(n),h=a.mul(o.x),l=ub(pc.xy).mul(6.28318530718);return fh(r(t.xy.add(cb(0,5,l).mul(h)),t.z),r(t.xy.add(cb(1,5,l).mul(h)),t.z),r(t.xy.add(cb(2,5,l).mul(h)),t.z),r(t.xy.add(cb(3,5,l).mul(h)),t.z),r(t.xy.add(cb(4,5,l).mul(h)),t.z)).mul(.2)}),t_=eo(({depthTexture:e,shadowCoord:t,shadow:s,depthLayer:i})=>{const r=(t,s)=>{let r=Ju(e,t);return e.isArrayTexture&&(r=r.depth(i)),r.compare(s)},n=vd("mapSize","vec2",s).setGroup(oh),a=uo(1).div(n),o=a.x,h=a.y,l=t.xy,u=il(l.mul(n).add(.5));return l.subAssign(u.mul(a)),fh(r(l,t.z),r(l.add(uo(o,0)),t.z),r(l.add(uo(0,h)),t.z),r(l.add(a),t.z),jl(r(l.add(uo(o.negate(),0)),t.z),r(l.add(uo(o.mul(2),0)),t.z),u.x),jl(r(l.add(uo(o.negate(),h)),t.z),r(l.add(uo(o.mul(2),h)),t.z),u.x),jl(r(l.add(uo(0,h.negate())),t.z),r(l.add(uo(0,h.mul(2))),t.z),u.y),jl(r(l.add(uo(o,h.negate())),t.z),r(l.add(uo(o,h.mul(2))),t.z),u.y),jl(jl(r(l.add(uo(o.negate(),h.negate())),t.z),r(l.add(uo(o.mul(2),h.negate())),t.z),u.x),jl(r(l.add(uo(o.negate(),h.mul(2))),t.z),r(l.add(uo(o.mul(2),h.mul(2))),t.z),u.x),u.y)).mul(1/9)}),s_=eo(({depthTexture:e,shadowCoord:t,depthLayer:s},i)=>{let r=Ju(e).sample(t.xy);e.isArrayTexture&&(r=r.depth(s)),r=r.rg;const n=r.x,a=Pl(1e-7,r.y.mul(r.y)),o=i.renderer.reversedDepthBuffer?Bl(n,t.z):Bl(t.z,n),h=ao(1).toVar();return io(o.notEqual(1),()=>{const e=t.z.sub(n);let s=a.div(a.add(e.mul(e)));s=$l(yh(s,.3).div(.65)),h.assign(Pl(o,s))}),h}),i_=new gy,r_=[],n_=eo(({samples:e,radius:t,size:s,shadowPass:i,depthLayer:r})=>{const n=ao(0).toVar("meanVertical"),a=ao(0).toVar("squareMeanVertical"),o=e.lessThanEqual(ao(1)).select(ao(0),ao(2).div(e.sub(1))),h=e.lessThanEqual(ao(1)).select(ao(0),ao(-1));Kp({start:oo(0),end:oo(e),type:"int",condition:"<"},({i:e})=>{const l=h.add(ao(e).mul(o));let u=i.sample(fh(pc.xy,uo(0,l).mul(t)).div(s));i.value.isArrayTexture&&(u=u.depth(r)),u=u.x,n.addAssign(u),a.addAssign(u.mul(u))}),n.divAssign(e),a.divAssign(e);const l=Zh(a.sub(n.mul(n)).max(0));return uo(n,l)}),a_=eo(({samples:e,radius:t,size:s,shadowPass:i,depthLayer:r})=>{const n=ao(0).toVar("meanHorizontal"),a=ao(0).toVar("squareMeanHorizontal"),o=e.lessThanEqual(ao(1)).select(ao(0),ao(2).div(e.sub(1))),h=e.lessThanEqual(ao(1)).select(ao(0),ao(-1));Kp({start:oo(0),end:oo(e),type:"int",condition:"<"},({i:e})=>{const l=h.add(ao(e).mul(o));let u=i.sample(fh(pc.xy,uo(l,0).mul(t)).div(s));i.value.isArrayTexture&&(u=u.depth(r)),n.addAssign(u.x),a.addAssign(fh(u.y.mul(u.y),u.x.mul(u.x)))}),n.divAssign(e),a.divAssign(e);const l=Zh(a.sub(n.mul(n)).max(0));return uo(n,l)}),o_=[Jb,e_,t_,s_];let h_;const l_=new lb;class u_ extends Yb{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 a=i.x.greaterThanEqual(0).and(i.x.lessThanEqual(1)).and(i.y.greaterThanEqual(0)).and(i.y.lessThanEqual(1)).and(i.z.lessThanEqual(1)),o=t({depthTexture:s,shadowCoord:i,shadow:r,depthLayer:n});return a.select(o,ao(1))}setupShadowCoord(e,t){const{shadow:s}=this,{renderer:i}=e,r=s.biasNode||vd("bias","float",s).setGroup(oh);let n,a=t;if(s.camera.isOrthographicCamera||!0!==i.logarithmicDepthBuffer)a=a.xyz.div(a.w),n=a.z;else{const e=a.w;a=a.xy.div(e);const t=vd("near","float",s.camera).setGroup(oh),i=vd("far","float",s.camera).setGroup(oh);n=_m(e.negate(),t,i)}return a=go(a.x,a.y.oneMinus(),i.reversedDepthBuffer?n.sub(r):n.add(r)),a}getShadowFilterFn(e){return o_[e]}setupRenderTarget(e,t){const s=new Fr(e.mapSize.width,e.mapSize.height);s.name="ShadowDepthTexture",s.compareFunction=t.renderer.reversedDepthBuffer?rt:tt;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,{depthTexture:n,shadowMap:a}=this.setupRenderTarget(r,e),o=t.shadowMap.type,h=t.hasCompatibility(dt);if(1!==o&&2!==o||!h?(n.minFilter=O,n.magFilter=O):(n.minFilter=z,n.magFilter=z),r.camera.coordinateSystem=s.coordinateSystem,r.camera.updateProjectionMatrix(),3===o&&!0!==r.isPointLightShadow){n.compareFunction=null,a.depth>1?(a._vsmShadowMapVertical||(a._vsmShadowMapVertical=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:le,type:K,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:le,type:K,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:le,type:K,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:le,type:K,depthBuffer:!1}));let t=Ju(n);n.isArrayTexture&&(t=t.depth(this.depthLayer));let s=Ju(this.vsmShadowMapVertical.texture);n.isArrayTexture&&(s=s.depth(this.depthLayer));const i=vd("blurSamples","float",r).setGroup(oh),o=vd("radius","float",r).setGroup(oh),h=vd("mapSize","vec2",r).setGroup(oh);let l=this.vsmMaterialVertical||(this.vsmMaterialVertical=new Em);l.fragmentNode=n_({samples:i,radius:o,size:h,shadowPass:t,depthLayer:this.depthLayer}).context(e.getSharedContext()),l.name="VSMVertical",l=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new Em),l.fragmentNode=a_({samples:i,radius:o,size:h,shadowPass:s,depthLayer:this.depthLayer}).context(e.getSharedContext()),l.name="VSMHorizontal"}const l=vd("intensity","float",r).setGroup(oh),u=vd("normalBias","float",r).setGroup(oh),c=Vb(i),d=id.mul(u);let p;if(!t.highPrecision||e.material.receivedShadowPositionNode||e.context.shadowPositionWorld)p=c.mul(Kb.add(d));else{p=uh("mat4").onObjectUpdate(({object:e},t)=>t.value.multiplyMatrices(c.value,e.matrixWorld)).mul(Gc).add(c.mul(_o(d,0)))}const m=this.setupShadowCoord(e,p),g=r.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(null===g)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const f=3===o&&!0!==r.isPointLightShadow?this.vsmShadowMapHorizontal.texture:n,y=this.setupShadowFilter(e,{filterFn:g,shadowTexture:a.texture,depthTexture:f,shadowCoord:m,shadow:r,depthLayer:this.depthLayer});let b,_;!0===t.shadowMap.transmitted&&(a.texture.isCubeTexture?b=bd(a.texture,m.xyz):(b=Ju(a.texture,m),n.isArrayTexture&&(b=b.depth(this.depthLayer)))),_=b?jl(1,y.rgb.mix(b,1),l.mul(b.a)).toVar():jl(1,y,l).toVar(),this.shadowMap=a,this.shadow.map=a;const x=`${this.light.type} Shadow [ ${this.light.name||"ID: "+this.light.id} ]`;return b&&_.toInspector(`${x} / Color`,()=>this.shadowMap.texture.isCubeTexture?bd(this.shadowMap.texture):Ju(this.shadowMap.texture)),_.toInspector(`${x} / Depth`,()=>this.shadowMap.texture.isCubeTexture?bd(this.shadowMap.texture).r.oneMinus():ec(this.shadowMap.depthTexture,$u().mul(Hu(Ju(this.shadowMap.depthTexture)))).r.oneMinus())}setup(e){if(!1!==e.renderer.shadowMap.enabled)return eo(()=>{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.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 a=n.name;n.name=`Shadow Map [ ${i.name||"ID: "+i.id} ]`,r.render(n,t.camera),n.name=a}updateShadow(e){const{shadowMap:t,light:s,shadow:i}=this,{renderer:r,scene:n,camera:a}=e,o=r.shadowMap.type,h=t.depthTexture.version;this._depthVersionCached=h;const l=i.camera.layers.mask;4294967294&i.camera.layers.mask||(i.camera.layers.mask=a.layers.mask);const u=r.getRenderObjectFunction(),c=r.getMRT(),d=!!c&&c.has("velocity");h_=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=Qb(e,s)),s}(r,n,h_),n.overrideMaterial=(e=>{let t=Zb.get(e);return void 0===t&&(t=new Em,t.colorNode=_o(0,0,0,1),t.isShadowPassMaterial=!0,t.name="ShadowMaterial",t.blending=0,t.fog=!1,Zb.set(e,t)),t})(s),r.setRenderObjectFunction(((e,t,s,i)=>{r_[0]=e,r_[1]=t;let r=i_.get(r_);return void 0!==r&&r.shadowType===s&&r.useVelocity===i||(r=(r,n,a,o,h,l,...u)=>{(!0===r.castShadow||r.receiveShadow&&3===s)&&(i&&(Gn(r).useVelocity=!0),r.onBeforeShadow(e,r,a,t.camera,o,n.overrideMaterial,l),e.renderObject(r,n,a,o,h,l,...u),r.onAfterShadow(e,r,a,t.camera,o,n.overrideMaterial,l))},r.shadowType=s,r.useVelocity=i,i_.set(r_,r)),r_[0]=null,r_[1]=null,r})(r,i,o,d)),r.setClearColor(0,0),r.setRenderTarget(t),this.renderShadow(e),r.setRenderObjectFunction(u),3===o&&!0!==i.isPointLightShadow&&this.vsmPass(r),i.camera.layers.mask=l,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,h_)}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),l_.material=this.vsmMaterialVertical,l_.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),l_.material=this.vsmMaterialHorizontal,l_.render(e)}dispose(){this._reset(),super.dispose()}_reset(){this._currentShadowType=null,(e=>{const t=Zb.get(e);void 0!==t&&(t.dispose(),Zb.delete(e))})(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 c_=new zs,d_=new ns,p_=new Ot,m_=new Ot,g_=[new Ot(1,0,0),new Ot(-1,0,0),new Ot(0,-1,0),new Ot(0,1,0),new Ot(0,0,1),new Ot(0,0,-1)],f_=[new Ot(0,-1,0),new Ot(0,-1,0),new Ot(0,0,-1),new Ot(0,0,1),new Ot(0,-1,0),new Ot(0,-1,0)],y_=[new Ot(1,0,0),new Ot(-1,0,0),new Ot(0,1,0),new Ot(0,-1,0),new Ot(0,0,1),new Ot(0,0,-1)],b_=[new Ot(0,-1,0),new Ot(0,-1,0),new Ot(0,0,1),new Ot(0,0,-1),new Ot(0,-1,0),new Ot(0,-1,0)],__=eo(({depthTexture:e,bd3D:t,dp:s})=>bd(e,t).compare(s)),x_=eo(({depthTexture:e,bd3D:t,dp:s,shadow:i})=>{const r=vd("radius","float",i).setGroup(oh),n=vd("mapSize","vec2",i).setGroup(oh),a=r.div(n.x),o=fl(t),h=sl(Ol(t,o.x.greaterThan(o.z).select(go(0,1,0),go(1,0,0)))),l=Ol(t,h),u=ub(pc.xy).mul(6.28318530718),c=cb(0,5,u),d=cb(1,5,u),p=cb(2,5,u),m=cb(3,5,u),g=cb(4,5,u);return bd(e,t.add(h.mul(c.x).add(l.mul(c.y)).mul(a))).compare(s).add(bd(e,t.add(h.mul(d.x).add(l.mul(d.y)).mul(a))).compare(s)).add(bd(e,t.add(h.mul(p.x).add(l.mul(p.y)).mul(a))).compare(s)).add(bd(e,t.add(h.mul(m.x).add(l.mul(m.y)).mul(a))).compare(s)).add(bd(e,t.add(h.mul(g.x).add(l.mul(g.y)).mul(a))).compare(s)).mul(.2)}),v_=eo(({filterFn:e,depthTexture:t,shadowCoord:s,shadow:i},r)=>{const n=s.xyz.toConst(),a=n.abs().toConst(),o=a.x.max(a.y).max(a.z),h=uh("float").setGroup(oh).onRenderUpdate(()=>i.camera.near),l=uh("float").setGroup(oh).onRenderUpdate(()=>i.camera.far),u=vd("bias","float",i).setGroup(oh),c=ao(1).toVar();return io(o.sub(l).lessThanEqual(0).and(o.sub(h).greaterThanEqual(0)),()=>{let s;r.renderer.reversedDepthBuffer?(s=((e,t,s)=>t.mul(e.add(s)).div(e.mul(t.sub(s))))(o.negate(),h,l),s.subAssign(u)):(s=ym(o.negate(),h,l),s.addAssign(u));const a=n.normalize();c.assign(e({depthTexture:t,bd3D:a,dp:s,shadow:i}))}),c});class T_ extends u_{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return 0===e?__:x_}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,depthTexture:s,shadowCoord:i,shadow:r}){return v_({filterFn:t,depthTexture:s,shadowCoord:i,shadow:r})}setupRenderTarget(e,t){const s=new Lr(e.mapSize.width);s.name="PointShadowDepthTexture",s.compareFunction=t.renderer.reversedDepthBuffer?rt:tt;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,a=t.camera,o=t.matrix,h=r.coordinateSystem===lt,l=h?g_:y_,u=h?f_:b_;s.setSize(t.mapSize.width,t.mapSize.width);const c=r.autoClear,d=r.getClearColor(c_),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 h=i.distance||a.far;h!==a.far&&(a.far=h,a.updateProjectionMatrix()),p_.setFromMatrixPosition(i.matrixWorld),a.position.copy(p_),m_.copy(a.position),m_.add(l[e]),a.up.copy(u[e]),a.lookAt(m_),a.updateMatrixWorld(),o.makeTranslation(-p_.x,-p_.y,-p_.z),d_.multiplyMatrices(a.projectionMatrix,a.matrixWorldInverse),t._frustum.setFromProjectionMatrix(d_,a.coordinateSystem,a.reversedDepth);const c=n.name;n.name=`Point Light Shadow [ ${i.name||"ID: "+i.id} ] - Face ${e+1}`,r.render(n,a),n.name=c}r.autoClear=c,r.setClearColor(d,p)}}class S_ extends sm{static get type(){return"AnalyticLightNode"}constructor(e=null){super(),this.light=e,this.color=new zs,this.colorNode=e&&e.colorNode||uh(this.color).setGroup(oh),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=Wn,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 jb(this.light).sub(e.context.positionView||Hc)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return((e,t)=>new u_(e,t))(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?Wa(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 w_=eo(({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)});class M_ extends S_{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=uh(0).setGroup(oh),this.decayExponentNode=uh(2).setGroup(oh)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return((e,t)=>new T_(e,t))(this.light)}setupDirect(e){return(({color:e,lightVector:t,cutoffDistance:s,decayExponent:i})=>{const r=t.normalize(),n=t.length(),a=w_({lightDistance:n,cutoffDistance:s,decayExponent:i});return{lightDirection:r,lightColor:e.mul(a)}})({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}}eo(([e=$u()],{renderer:t,material:s})=>{const i=Gl(e.mul(2).sub(1));let r;if(s.alphaToCoverage&&t.currentSamples>0){const e=ao(i.fwidth()).toVar();r=ql(e.oneMinus(),e.add(1),i).oneMinus()}else r=Ql(i.greaterThan(1),0,1);return r});const N_=eo(([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(bh(s,s).sub(bh(i,i)))),n}),A_=new Qy;class E_ extends xy{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(A_),A_.a=i._clearColor.a;else if(!0===r.isColor)r.getRGB(A_),A_.a=1,n=!0;else if(!0===r.isNode){const o=this.get(e),h=r;A_.copy(i._clearColor);let l=o.backgroundMesh;if(void 0===l){const c=_o(h).mul(gb).context({getUV:()=>fb.mul(td),getTextureLevel:()=>mb}),d=Ac.element(3).element(3).equal(1),p=_h(1,Ac.element(1).element(1)).mul(3),m=d.select(Gc.mul(p),Gc),g=Ic.mul(_o(m,0));let f=Ac.mul(_o(g.xyz,1));f=f.setZ(f.w);const y=new Em;function b(){r.removeEventListener("dispose",b),l.material.dispose(),l.geometry.dispose()}y.name="Background.material",y.side=1,y.depthTest=!1,y.depthWrite=!1,y.allowOverride=!1,y.fog=!1,y.lights=!1,y.vertexNode=f,y.colorNode=c,o.backgroundMeshNode=c,o.backgroundMesh=l=new mr(new Ur(1,32,32),y),l.frustumCulled=!1,l.name="Background.mesh",r.addEventListener("dispose",b)}const u=h.getCacheKey();o.backgroundCacheKey!==u&&(o.backgroundMeshNode.node=_o(h).mul(gb),o.backgroundMeshNode.needsUpdate=!0,l.material.needsUpdate=!0,o.backgroundCacheKey=u),t.unshift(l,l.geometry,l.material,0,0,null,null)}else _t("Renderer: Unsupported background configuration.",r);const a=i.xr.getEnvironmentBlendMode();if("additive"===a?A_.set(0,0,0,1):"alpha-blend"===a&&A_.set(0,0,0,0),!0===i.autoClear||!0===n){const _=s.clearColorValue;_.r=A_.r,_.g=A_.g,_.b=A_.b,_.a=A_.a,!0!==i.backend.isWebGLBackend&&!0!==i.alpha||(_.r*=_.a,_.g*=_.a,_.b*=_.a),s.depthClearValue=i.getClearDepth(),s.stencilClearValue=i.getClearStencil(),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 C_{constructor(e="",t=[]){this.name=e,this.bindings=t,this.id=R_++}}class P_{constructor(e,t,s,i,r,n,a,o,h,l=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=s,this.transforms=l,this.nodeAttributes=i,this.bindings=r,this.updateNodes=n,this.updateBeforeNodes=a,this.updateAfterNodes=o,this.observer=h,this.usedTimes=0}createBindings(){const e=[];for(const t of this.bindings){if(!0!==t.bindings[0].groupNode.shared){const s=new C_(t.name,[]);e.push(s);for(const e of t.bindings)s.bindings.push(e.clone())}else e.push(t)}return e}}class B_{constructor(e,t,s=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=s}}class F_{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 L_{constructor(e,t,s=!1,i=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=s,this.count=i}}class D_ extends L_{constructor(e,t,s=null,i=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=s,this.interpolationSampling=i}}class I_{constructor(e,t,s=""){this.name=e,this.type=t,this.code=s,Object.defineProperty(this,"isNodeCode",{value:!0})}}let O_=0;class U_{constructor(e=null){this.id=O_++,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 k_{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class z_{constructor(e,t){this.name=e,this.value=t,this.boundary=0,this.itemSize=0,this.offset=0,this.index=-1}setValue(e){this.value=e}getValue(){return this.value}}class V_ extends z_{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class G_ extends z_{constructor(e,t=new Dt){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class j_ extends z_{constructor(e,t=new Ot){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class $_ extends z_{constructor(e,t=new ss){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class W_ extends z_{constructor(e,t=new zs){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class H_ extends z_{constructor(e,t=new wn){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}}class q_ extends z_{constructor(e,t=new zt){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class X_ extends z_{constructor(e,t=new ns){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class Y_ extends V_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class K_ extends G_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Q_ extends j_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Z_ extends $_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class J_ extends W_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class ex extends H_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class tx extends q_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class sx extends X_{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}let ix=0;const rx=new WeakMap,nx=new WeakMap,ax=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),ox=e=>/e/g.test(e)?String(e).replace(/\+/g,""):(e=Number(e))+(e%1?"":".0");class hx{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=eb(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new U_,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:ix++})}isFlatShading(){return!0===this.material.flatShading||!1===this.geometry.hasAttribute("normal")}isOpaque(){const e=this.material;return!1===e.transparent&&1===e.blending&&!1===e.alphaToCoverage}createRenderTarget(e,t,s){return new is(e,t,s)}createCubeRenderTarget(e,t){return new Im(e,t)}includes(e){return this.nodes.includes(e)}getOutputStructName(){}_getBindGroup(e,t){const s=t[0].groupNode;let i,r=s.shared;if(r)for(let e=1;e<t.length;e++)s!==t[e].groupNode&&(r=!1);if(r){let s="";for(const e of t)if(e.isNodeUniformsGroup){e.uniforms.sort((e,t)=>e.nodeUniform.node.id-t.nodeUniform.node.id);for(const t of e.uniforms)s+=t.nodeUniform.node.id}else s+=e.nodeUniform.id;const r=this.renderer._currentRenderContext||this.renderer;let n=rx.get(r);void 0===n&&(n=new Map,rx.set(r,n));const a=Ln(s);i=n.get(a),void 0===i&&(i=new C_(e,t),n.set(a,i))}else i=new C_(e,t);return i}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 Zn)for(const i in s[e]){const r=s[e][i],n=t[i]||(t[i]=[]);for(const e of r)!1===n.includes(e)&&n.push(e)}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}}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){const t=e.getUpdateBeforeType(),s=e.getUpdateAfterType();t===$n&&s===$n||!1===this.sequentialNodes.includes(e)&&this.sequentialNodes.push(e)}buildUpdateNodes(){for(const e of this.nodes){e.getUpdateType()!==$n&&this.updateNodes.push(e)}for(const e of this.sequentialNodes){const t=e.getUpdateBeforeType(),s=e.getUpdateAfterType();t!==$n&&this.updateBeforeNodes.push(e),s!==$n&&this.updateAfterNodes.push(e)}}get currentNode(){return this.chaining[this.chaining.length-1]}isFilteredTexture(e){return e.magFilter===z||e.magFilter===V||e.magFilter===k||e.magFilter===G||e.minFilter===z||e.minFilter===V||e.minFilter===k||e.minFilter===G}getUniformBufferLimit(){return this.renderer.backend.capabilities.getUniformBufferLimit()}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 U_(t?this.getCache():null)),s.cache}isAvailable(){return!1}getVertexIndex(){bt("Abstract function.")}getInstanceIndex(){bt("Abstract function.")}getDrawIndex(){bt("Abstract function.")}getFrontFacing(){bt("Abstract function.")}getFragCoord(){bt("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(){bt("Abstract function.")}generateTextureLod(){bt("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 zs:"vec2"===e||"uvec2"===e||"ivec2"===e?t=new Dt:"vec3"===e||"uvec3"===e||"ivec3"===e?t=new Ot:"vec4"!==e&&"uvec4"!==e&&"ivec4"!==e||(t=new ss)),"float"===e)return ox(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")}( ${ox(t.r)}, ${ox(t.g)}, ${ox(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 B_(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===q)return"int";if(t===X)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=kn(e);const i="float"===t?"":t[0];return!0===/mat2/.test(t)&&(s=s.replace("vec","mat")),i+s}getTypeFromArray(e){return ax.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 Ei||!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=eb(this.stack);const e=so();return this.stacks.push(e),to(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,to(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,a=this.getClosestSubBuild(n);return a&&(void 0===r.subBuildsCache&&(r.subBuildsCache={}),r=r.subBuildsCache[a]||(r.subBuildsCache[a]={}),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 B_("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 a=this.structs.index++;null===s&&(s="StructType"+a),n=new k_(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 a=this.uniforms.index++;n=new F_(i||"nodeUniform"+a,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),a=this.getSubBuildProperty("variable",n.subBuilds);let o=n[a];if(void 0===o){const h=r?"_const":"_var",l=this.vars[i]||(this.vars[i]=[]),u=this.vars[h]||(this.vars[h]=0);null===t&&(t=(r?"nodeConst":"nodeVar")+u,this.vars[h]++),"variable"!==a&&(t=this.getSubBuildProperty(t,n.subBuilds));const c=e.getArrayCount(this);o=new L_(t,s,r,c),r||l.push(o),this.registerDeclaration(o),n[a]=o}return o}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"),a=this.getSubBuildProperty("varying",n.subBuilds);let o=n[a];if(void 0===o){const e=this.varyings,h=e.length;null===t&&(t="nodeVarying"+h),"varying"!==a&&(t=this.getSubBuildProperty(t,n.subBuilds)),o=new D_(t,s,i,r),e.push(o),this.registerDeclaration(o),n[a]=o}return o}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,bt(`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 I_("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 Bb,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 Zy(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,a=this.buildStage,o=this.stack,h={code:""};this.flow=h,this.vars={},this.declarations={},this.cache=new U_,this.stack=eb();for(const s of Qn)this.setBuildStage(s),h.result=e.build(this,t);return h.vars=this.getVars(this.shaderStage),this.flow=s,this.vars=i,this.declarations=r,this.cache=n,this.stack=o,this.setBuildStage(a),h}getFunctionOperator(){return null}buildFunctionCode(){bt("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,a=this.shaderStage,o=this.context;this.setShaderStage(e);const h={...this.context};delete h.nodeBlock,this.cache=this.globalCache,this.tab="\t",this.context=h;let l=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,l=r}else l=t.build(this);return this.setShaderStage(a),this.cache=n,this.tab=r,this.context=o,l}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){bt("Abstract function.")}getVaryings(){bt("Abstract function.")}getVar(e,t,s=null){return`${null!==s?this.generateArrayDeclaration(e,s):this.getType(e)} ${t}`}getVars(e,t=!1){const s=[],i=this.vars[e];if(void 0!==i)for(const e of i)s.push(`${this.getVar(e.type,e.name,e.count)};`);return s.join(t?"\n":"\n\t")}getUniforms(){bt("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(){bt("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}prebuild(){const{object:e,renderer:t,material:s}=this;if(!0===t.contextNode.isContextNode?this.context={...this.context,...t.contextNode.getFlowContextData()}:_t('NodeBuilder: "renderer.contextNode" must be an instance of `context()`.'),s&&s.contextNode&&(!0===s.contextNode.isContextNode?this.context={...this.context,...s.contextNode.getFlowContextData()}:_t('NodeBuilder: "material.contextNode" must be an instance of `context()`.')),null!==s){let e=t.library.fromMaterial(s);null===e&&(_t(`NodeBuilder: Material "${s.type}" is not compatible.`),e=new Em),e.build(this)}else this.addFlow("compute",e)}build(){this.prebuild();for(const e of Qn){this.setBuildStage(e),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage("vertex",this.context.position);for(const t of Zn){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}async buildAsync(){this.prebuild();for(const e of Qn){this.setBuildStage(e),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage("vertex",this.context.position);for(const t of Zn){this.setShaderStage(t);const s=this.flowNodes[t];for(const t of s)"generate"===e?this.flowNode(t):t.build(this);await vt()}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}getSharedDataFromNode(e){let t=nx.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 Y_(e);else if("vec2"===t||"ivec2"===t||"uvec2"===t)i=new K_(e);else if("vec3"===t||"ivec3"===t||"uvec3"===t)i=new Q_(e);else if("vec4"===t||"ivec4"===t||"uvec4"===t)i=new Z_(e);else if("color"===t)i=new J_(e);else if("mat2"===t)i=new ex(e);else if("mat3"===t)i=new tx(e);else{if("mat4"!==t)throw new Error(`Uniform "${t}" not implemented.`);i=new sx(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${a} - Node System\n`}needsPreviousData(){const e=this.renderer.getMRT();return e&&e.has("velocity")||!0===Gn(this.object).useVelocity}}class lx{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===Wn){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===Hn){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===qn&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),s=e.updateReference(this);if(t===Wn){const t=this._getMaps(this.updateAfterMap,s);t.frameId!==this.frameId&&!1!==e.updateAfter(this)&&(t.frameId=this.frameId)}else if(t===Hn){const t=this._getMaps(this.updateAfterMap,s);t.renderId!==this.renderId&&!1!==e.updateAfter(this)&&(t.renderId=this.renderId)}else t===qn&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),s=e.updateReference(this);if(t===Wn){const t=this._getMaps(this.updateMap,s);t.frameId!==this.frameId&&!1!==e.update(this)&&(t.frameId=this.frameId)}else if(t===Hn){const t=this._getMaps(this.updateMap,s);t.renderId!==this.renderId&&!1!==e.update(this)&&(t.renderId=this.renderId)}else t===qn&&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 ux{constructor(e,t,s=null,i="",r=!1){this.type=e,this.name=t,this.count=s,this.qualifier=i,this.isConst=r}}ux.isNodeFunctionInput=!0;class cx extends S_{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class dx extends S_{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:$b(this.light),lightColor:e}}}class px extends S_{static get type(){return"HemisphereLightNode"}constructor(e=null){super(e),this.lightPositionNode=Gb(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=uh(new zs).setGroup(oh)}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=id.dot(i).mul(.5).add(.5),n=jl(s,t,r);e.context.irradiance.addAssign(n)}}class mx extends S_{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=uh(0).setGroup(oh),this.penumbraCosNode=uh(0).setGroup(oh),this.cutoffDistanceNode=uh(0).setGroup(oh),this.decayExponentNode=uh(0).setGroup(oh),this.colorNode=uh(this.color).setGroup(oh)}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 ql(s,i,t)}getLightCoord(e){const t=e.getNodeProperties(this);let s=t.projectionUV;return void 0===s&&(s=function(e,t=$c){const s=Vb(e).mul(t);return s.xyz.div(s.w)}(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),a=n.normalize(),o=a.dot($b(r)),h=this.getSpotAttenuation(e,o),l=n.length(),u=w_({lightDistance:l,cutoffDistance:s,decayExponent:i});let c,d,p=t.mul(h).mul(u);if(r.colorNode?(d=this.getLightCoord(e),c=r.colorNode(d)):r.map&&(d=this.getLightCoord(e),c=Ju(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:a}}}class gx extends mx{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=Ju(s,uo(e,0),0).r}else i=super.getSpotAttenuation(t);return i}}class fx extends S_{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let e=0;e<9;e++)t.push(new Ot);this.lightProbe=nc(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=N_(id,this.lightProbe);e.context.irradiance.addAssign(t)}}const yx=eo(([e,t])=>{const s=e.abs().sub(t);return bl(Pl(s,0)).add(Cl(Pl(s.x,s.y),0))});class bx extends mx{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=ao(0),s=this.penumbraCosNode,i=Vb(this.light).mul(e.context.positionWorld||$c);return io(i.w.greaterThan(0),()=>{const e=i.xyz.div(i.w),r=yx(e.xy.sub(uo(.5)),uo(.5)),n=_h(-1,yh(1,dl(s)).sub(1));t.assign(Wl(r.mul(-2).mul(n)))}),t}}const _x=new ns,xx=new ns;let vx=null;class Tx extends S_{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=uh(new Ot).setGroup(oh),this.halfWidth=uh(new Ot).setGroup(oh),this.updateType=Hn}update(e){super.update(e);const{light:t}=this,s=e.camera.matrixWorldInverse;xx.identity(),_x.copy(t.matrixWorld),_x.premultiply(s),xx.extractRotation(_x),this.halfWidth.value.set(.5*t.width,0,0),this.halfHeight.value.set(0,.5*t.height,0),this.halfWidth.value.applyMatrix4(xx),this.halfHeight.value.applyMatrix4(xx)}setupDirectRectArea(e){let t,s;e.isAvailable("float32Filterable")?(t=Ju(vx.LTC_FLOAT_1),s=Ju(vx.LTC_FLOAT_2)):(t=Ju(vx.LTC_HALF_1),s=Ju(vx.LTC_HALF_2));const{colorNode:i,light:r}=this;return{lightColor:i,lightPosition:jb(r),halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:s}}static setLTC(e){vx=e}}class Sx{parseFunction(){bt("Abstract function.")}}class wx{constructor(e,t,s="",i=""){this.type=e,this.inputs=t,this.name=s,this.precision=i}getCode(){bt("Abstract function.")}}wx.isNodeFunction=!0;const Mx=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,Nx=/[a-z_0-9]+/gi,Ax="#pragma main";class Ex extends wx{constructor(e){const{type:t,inputs:s,name:i,precision:r,inputsCode:n,blockCode:a,headerCode:o}=(e=>{const t=(e=e.trim()).indexOf(Ax),s=-1!==t?e.slice(t+12):e,i=s.match(Mx);if(null!==i&&5===i.length){const r=i[4],n=[];let a=null;for(;null!==(a=Nx.exec(r));)n.push(a);const o=[];let h=0;for(;h<n.length;){const e="const"===n[h][0];!0===e&&h++;let t=n[h][0];"in"===t||"out"===t||"inout"===t?h++:t="";const s=n[h++][0];let i=Number.parseInt(n[h][0]);!1===Number.isNaN(i)?h++:i=null;const r=n[h++][0];o.push(new ux(s,r,i,t,e))}const l=s.substring(i[0].length),u=void 0!==i[3]?i[3]:"";return{type:i[2],inputs:o,name:u,precision:void 0!==i[1]?i[1]:"",inputsCode:r,blockCode:l,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=a,this.headerCode=o}getCode(e=this.name){let t;const s=this.blockCode;if(""!==s){const{type:i,inputsCode:r,headerCode:n,precision:a}=this;let o=`${i} ${e} ( ${r.trim()} )`;""!==a&&(o=`${a} ${o}`),t=n+o+s}else t="";return t}}class Rx extends Sx{parseFunction(e){return new Ex(e)}}const Cx=[],Px=[];class Bx extends xy{constructor(e,t){super(),this.renderer=e,this.backend=t,this.nodeFrame=new lx,this.nodeBuilderCache=new Map,this.callHashCache=new gy,this.groupsData=new gy,this._buildQueue=[],this._buildInProgress=!1,this.cacheLib={}}updateGroup(e){const t=e.groupNode;Cx[0]=t,Cx[1]=e;let s=this.groupsData.get(Cx);return void 0===s&&this.groupsData.set(Cx,s={}),Cx[0]=null,Cx[1]=null,s.version!==t.version&&(s.version=t.version,!0)}getForRenderCacheKey(e){return e.initialCacheKey}_createNodeBuilder(e,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}getForRender(e,t=!1){const s=this.get(e);let i=s.nodeBuilderState;if(void 0===i){const{nodeBuilderCache:r}=this,n=this.getForRenderCacheKey(e);if(i=r.get(n),void 0===i){const a=async()=>{let s=this._createNodeBuilder(e,e.material);try{t?await s.buildAsync():s.build()}catch(i){s=this._createNodeBuilder(e,new Em),t?await s.buildAsync():s.build(),_t("TSL: "+i)}return s};if(t)return a().then(e=>(i=this._createNodeBuilderState(e),r.set(n,i),i.usedTimes++,s.nodeBuilderState=i,i));{let t=this._createNodeBuilder(e,e.material);try{t.build()}catch(s){t=this._createNodeBuilder(e,new Em),t.build();let i=s.stackTrace;!i&&s.stack&&(i=new Bn(s.stack)),_t("TSL: "+s,i)}i=this._createNodeBuilderState(t),r.set(n,i)}}i.usedTimes++,s.nodeBuilderState=i}return i}getForRenderAsync(e){const t=this.getForRender(e,!0);return t.then?t:Promise.resolve(t)}getForRenderDeferred(e){const t=this.get(e);if(void 0!==t.nodeBuilderState)return t.nodeBuilderState;const s=this.getForRenderCacheKey(e),i=this.nodeBuilderCache.get(s);return void 0!==i?(i.usedTimes++,t.nodeBuilderState=i,i):(!0!==t.pendingBuild&&(t.pendingBuild=!0,this._buildQueue.push(()=>this.getForRenderAsync(e).then(()=>{t.pendingBuild=!1})),this._processBuildQueue()),null)}_processBuildQueue(){if(this._buildInProgress||0===this._buildQueue.length)return;this._buildInProgress=!0;this._buildQueue.shift()().then(()=>{this._buildInProgress=!1,this._processBuildQueue()})}delete(e){if(e.isRenderObject){const t=this.get(e).nodeBuilderState;void 0!==t&&(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 P_(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){Cx[0]=e,Cx[1]=t;const s=this.renderer.info.calls,i=this.callHashCache.get(Cx)||{};if(i.callId!==s){const r=this.getEnvironmentNode(e),n=this.getFogNode(e);t&&Px.push(t.getCacheKey(!0)),r&&Px.push(r.getCacheKey()),n&&Px.push(n.getCacheKey()),Px.push(this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview?1:0),Px.push(this.renderer.shadowMap.enabled?1:0),Px.push(this.renderer.shadowMap.type),i.callId=s,i.cacheKey=Dn(Px),this.callHashCache.set(Cx,i),Px.length=0}return Cx[0]=null,Cx[1]=null,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 Vf(s);{let e;return e=!0===s.isCubeTexture?bd(s):Ju(s),Vm(e)}}if(!0===s.isTexture)return Ju(s,cc.flipY()).setUpdateMatrix(!0);!0!==s.isColor&&_t("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=vd("color","color",s).setGroup(oh),t=vd("density","float",s).setGroup(oh);return Ib(e,Db(t))}if(s.isFog){const e=vd("color","color",s).setGroup(oh),t=vd("near","float",s).setGroup(oh),i=vd("far","float",s).setGroup(oh);return Ib(e,Lb(t,i))}_t("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?bd(s):!0===s.isTexture?Ju(s):void _t("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}getOutputNode(e){const t=this.renderer;return e.isArrayTexture?Ju(e,cc).depth(ac("gl_ViewID_OVR")).renderOutput(t.toneMapping,t.currentColorSpace):Ju(e,cc).renderOutput(t.toneMapping,t.currentColorSpace)}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 lx,this.nodeBuilderCache=new Map,this.cacheLib={}}}const Fx=new vr;class Lx{constructor(e=null){this.version=0,this.clipIntersection=null,this.cacheKey="",this.shadowPass=!1,this.viewNormalMatrix=new zt,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++){Fx.copy(e[r]).applyMatrix4(this.viewMatrix,this.viewNormalMatrix);const i=t[s+r],n=Fx.normal;i.x=-n.x,i.y=-n.y,i.z=-n.z,i.w=Fx.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,a;if(this.clipIntersection?(n=this.intersectionPlanes,a=e.intersectionPlanes.length):(n=this.unionPlanes,a=e.unionPlanes.length),n.length!==a+r){n.length=a+r;for(let e=0;e<r;e++)n[a+e]=new ss;s=!0}this.projectPlanes(i,n,a),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 Lx(this),this.clippingGroupContexts.set(e,t)),t.update(this,e),t}get unionClippingCount(){return this.unionPlanes.length}}class Dx{constructor(e,t,s){this.bundleGroup=e,this.camera=t,this.renderContext=s}}const Ix=[];class Ox{constructor(){this.bundles=new gy}get(e,t,s){const i=this.bundles;Ix[0]=e,Ix[1]=t,Ix[2]=s;let r=i.get(Ix);return void 0===r&&(r=new Dx(e,t,s),i.set(Ix,r)),Ix[0]=null,Ix[1]=null,Ix[2]=null,r}dispose(){this.bundles=new gy}}class Ux{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))bt(`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))bt(`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 kx=new Xb,zx=new WeakMap;class Vx{createNode(e=[]){return(new Xb).setLights(e)}getNode(e){if(e.isQuadMesh)return kx;let t=zx.get(e);return void 0===t&&(t=this.createNode(),zx.set(e,t)),t}}class Gx extends is{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 jx=new Ot,$x=new Ot,Wx=new WeakMap;class Hx extends St{constructor(e,t=!1){super(),this.enabled=!1,this.isPresenting=!1,this.cameraAutoUpdate=!0,this._renderer=e,this._cameraL=new hn,this._cameraL.viewport=new ss,this._cameraR=new hn,this._cameraR.viewport=new ss,this._cameras=[this._cameraL,this._cameraR],this._cameraXR=new Tn,this._currentDepthNear=null,this._currentDepthFar=null,this._controllers=[],this._controllerInputSources=[],this._xrRenderTarget=null,this._layers=[],this._sessionUsesLayers=!1,this._supportsGlBinding="undefined"!=typeof XRWebGLBinding,this._createXRLayer=Qx.bind(this),this._gl=null,this._currentAnimationContext=null,this._currentAnimationLoop=null,this._currentPixelRatio=null,this._currentSize=new Dt,this._onSessionEvent=Xx.bind(this),this._onSessionEnd=Yx.bind(this),this._onInputSourcesChange=Kx.bind(this),this._onAnimationFrame=Zx.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&&bt("XRManager: Cannot change framebuffer scale while presenting.")}getReferenceSpaceType(){return this._referenceSpaceType}setReferenceSpaceType(e){this._referenceSpaceType=e,!0===this.isPresenting&&bt("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,a,o={}){const h=new Or(e,t),l=new Gx(r,n,{format:re,type:j,depthTexture:new Fr(r,n,o.stencil?J:X,void 0,void 0,void 0,void 0,void 0,void 0,o.stencil?ae:ne),stencilBuffer:o.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});l._autoAllocateDepthBuffer=!0;const c=new sr({color:16777215,side:0});c.map=l.texture,c.map.offset.y=1,c.map.repeat.y=-1;const d=new mr(h,c);d.position.copy(s),d.quaternion.copy(i);const m={type:"quad",width:e,height:t,translation:s,quaternion:i,pixelwidth:r,pixelheight:n,plane:d,material:c,rendercall:a,renderTarget:l};if(this._layers.push(m),null!==this._session){m.plane.material=new sr({color:16777215,side:0}),m.plane.material.blending=5,m.plane.material.blendEquation=u,m.plane.material.blendSrc=p,m.plane.material.blendDst=p,m.xrlayer=this._createXRLayer(m);const e=this._session.renderState.layers;e.unshift(m.xrlayer),this._session.updateRenderState({layers:e})}else l.isXRRenderTarget=!1;return d}createCylinderLayer(e,t,s,i,r,n,a,o,h={}){const l=new Ir(e,e,e*t/s,64,64,!0,Math.PI-t/2,t),c=new Gx(n,a,{format:re,type:j,depthTexture:new Fr(n,a,h.stencil?J:X,void 0,void 0,void 0,void 0,void 0,void 0,h.stencil?ae:ne),stencilBuffer:h.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});c._autoAllocateDepthBuffer=!0;const d=new sr({color:16777215,side:1});d.map=c.texture,d.map.offset.y=1,d.map.repeat.y=-1;const m=new mr(l,d);m.position.copy(i),m.quaternion.copy(r);const g={type:"cylinder",radius:e,centralAngle:t,aspectratio:s,translation:i,quaternion:r,pixelwidth:n,pixelheight:a,plane:m,material:d,rendercall:o,renderTarget:c};if(this._layers.push(g),null!==this._session){g.plane.material=new sr({color:16777215,side:1}),g.plane.material.blending=5,g.plane.material.blendEquation=u,g.plane.material.blendSrc=p,g.plane.material.blendDst=p,g.xrlayer=this._createXRLayer(g);const e=this._session.renderState.layers;e.unshift(g.xrlayer),this._session.updateRenderState({layers:e})}else c.isXRRenderTarget=!1;return m}renderLayers(){const e=new Ot,t=new It,s=this._renderer,i=this.isPresenting;this.isPresenting=!1;const r=new Dt;s.getSize(r);const n=s.getRenderTarget();for(const i of this._layers){i.renderTarget.isXRRenderTarget=null!==this._session,i.renderTarget._hasExternalTextures=i.renderTarget.isXRRenderTarget;const r=s.contextNode;let n;if(i.renderTarget.isXRRenderTarget&&this._sessionUsesLayers){i.xrlayer.transform=new XRRigidTransform(i.plane.getWorldPosition(e),i.plane.getWorldQuaternion(t));const a=this._glBinding.getSubImage(i.xrlayer,this._xrFrame);s.backend.setXRRenderTargetTextures(i.renderTarget,a.colorTexture,void 0),s._setXRLayerSize(i.renderTarget.width,i.renderTarget.height),n=Wx.get(r),void 0===n&&(n=r.context({getOutput:e=>Uu(e,s.toneMapping,s.outputColorSpace)}),Wx.set(r,n))}else n=r;s.contextNode=n,s.setRenderTarget(i.renderTarget),i.rendercall(),s.contextNode=r}s.setRenderTarget(n),s._setXRLayerSize(r.x,r.y),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,a=null;t.depth&&(a=t.stencil?i.DEPTH24_STENCIL8:i.DEPTH_COMPONENT24,s=t.stencil?ae:ne,n=t.stencil?J:X);const o={colorFormat:i.RGBA8,depthFormat:a,scaleFactor:this._framebufferScaleFactor,clearOnAccess:!1};this._useMultiviewIfPossible&&t.hasFeature("OVR_multiview2")&&(o.textureType="texture-array",this._useMultiview=!0),this._glBinding=this.getBinding();const h=this._glBinding.createProjectionLayer(o),l=[h];this._glProjLayer=h,t.setPixelRatio(1),t._setXRLayerSize(h.textureWidth,h.textureHeight);const c=this._useMultiview?2:1,d=new Fr(h.textureWidth,h.textureHeight,n,void 0,void 0,void 0,void 0,void 0,void 0,s,c);if(this._xrRenderTarget=new Gx(h.textureWidth,h.textureHeight,{format:re,type:j,colorSpace:t.outputColorSpace,depthTexture:d,stencilBuffer:t.stencil,samples:r.antialias?4:0,resolveDepthBuffer:!1===h.ignoreDepthValues,resolveStencilBuffer:!1===h.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 sr({color:16777215,side:"cylinder"===e.type?1:0}),e.plane.material.blending=5,e.plane.material.blendEquation=u,e.plane.material.blendSrc=p,e.plane.material.blendDst=p,e.xrlayer=this._createXRLayer(e),l.unshift(e.xrlayer);e.updateRenderState({layers:l})}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 Gx(r.framebufferWidth,r.framebufferHeight,{format:re,type:j,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,a=this._cameraR;r.near=a.near=n.near=s,r.far=a.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=-5&r.layers.mask,a.layers.mask=-3&r.layers.mask;const o=e.parent,h=r.cameras;qx(r,o);for(let e=0;e<h.length;e++)qx(h[e],o);2===h.length?function(e,t,s){jx.setFromMatrixPosition(t.matrixWorld),$x.setFromMatrixPosition(s.matrixWorld);const i=jx.distanceTo($x),r=t.projectionMatrix.elements,n=s.projectionMatrix.elements,a=r[14]/(r[10]-1),o=r[14]/(r[10]+1),h=(r[9]+1)/r[5],l=(r[9]-1)/r[5],u=(r[8]-1)/r[0],c=(n[8]+1)/n[0],d=a*u,p=a*c,m=i/(-u+c),g=m*-u;if(t.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.translateX(g),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=a+m,s=o+m,r=d-g,n=p+(i-g),u=h*o/s*t,c=l*o/s*t;e.projectionMatrix.makePerspective(r,n,u,c,t,s),e.projectionMatrixInverse.copy(e.projectionMatrix).invert()}}(r,n,a):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*At*Math.atan(1/e.projectionMatrix.elements[5]),e.zoom=1)}(e,r,o)}_getController(e){let t=this._controllers[e];return void 0===t&&(t=new Ds,this._controllers[e]=t),t}}function qx(e,t){null===t?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}function Xx(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 Yx(){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 Gx(e.pixelwidth,e.pixelheight,{format:re,type:j,depthTexture:new Fr(e.pixelwidth,e.pixelheight,e.stencilBuffer?J:X,void 0,void 0,void 0,void 0,void 0,void 0,e.stencilBuffer?ae:ne),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 Kx(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 a=t[n];a&&a.connect(r)}}function Qx(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 Zx(e,t){if(void 0===t)return;const s=this._cameraXR,i=this._renderer,r=i.backend,n=this._glBaseLayer,a=this.getReferenceSpace(),o=t.getViewerPose(a);if(this._xrFrame=t,null!==o){const e=o.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 a=e[i];let o;if(!0===this._supportsLayers){const e=this._glBinding.getViewSubImage(this._glProjLayer,a);o=e.viewport,0===i&&r.setXRRenderTargetTextures(this._xrRenderTarget,e.colorTexture,this._glProjLayer.ignoreDepthValues&&!this._useMultiview?void 0:e.depthStencilTexture)}else o=n.getViewport(a);let h=this._cameras[i];void 0===h&&(h=new hn,h.layers.enable(i),h.viewport=new ss,this._cameras[i]=h),h.matrix.fromArray(a.transform.matrix),h.matrix.decompose(h.position,h.quaternion,h.scale),h.projectionMatrix.fromArray(a.projectionMatrix),h.projectionMatrixInverse.copy(h.projectionMatrix).invert(),h.viewport.set(o.x,o.y,o.width,o.height),0===i&&(s.matrix.copy(h.matrix),s.matrix.decompose(s.position,s.quaternion,s.scale)),!0===t&&s.cameras.push(h)}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,a)}this._currentAnimationLoop&&this._currentAnimationLoop(e,t),t.detectedPlanes&&this.dispatchEvent({type:"planesdetected",data:t}),this._xrFrame=null}class Jx extends St{constructor(e){super(),this.domElement=e,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new ss(0,0,this._width,this._height),this._scissor=new ss(0,0,this._width,this._height),this._scissorTest=!1,this.colorTexture=new Pr,this.depthTexture=new Fr}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 a=this._viewport;e.isVector4?a.copy(e):a.set(e,t,s,i),a.minDepth=r,a.maxDepth=n}_dispatchResize(){this.dispatchEvent({type:"resize"})}dispose(){this.dispatchEvent({type:"dispose"})}}const ev=new Gs,tv=new Dt,sv=new ss,iv=new Mr,rv=new Er,nv=new ns,av=new ss,ov={[o]:1,[h]:0,[l]:2};class hv{constructor(e,t={}){this.isRenderer=!0;const{logarithmicDepthBuffer:s=!1,reversedDepthBuffer:i=!1,alpha:r=!0,depth:n=!0,stencil:a=!1,antialias:o=!1,samples:h=0,getFallback:l=null,outputBufferType:u=K,multiview:c=!1}=t;this.backend=e,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.alpha=r,this.logarithmicDepthBuffer=s,this.reversedDepthBuffer=i,this.outputColorSpace=qe,this.toneMapping=0,this.toneMappingExposure=1,this.sortObjects=!0,this.depth=n,this.stencil=a,this.info=new Py,this.contextNode=Jl(),this.library=new Ux,this.lighting=new Vx,this._samples=h||!0===o?4:0,this._onCanvasTargetResize=this._onCanvasTargetResize.bind(this),this._canvasTarget=new Jx(e.getDomElement()),this._canvasTarget.addEventListener("resize",this._onCanvasTargetResize),this._canvasTarget.isDefaultCanvasTarget=!0,this._inspector=new zu,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._quadCache=new Map,this._currentRenderContext=null,this._opaqueSort=null,this._transparentSort=null,this._frameBufferTargets=new Map;const d=!0===this.alpha?0:1;this._clearColor=new Qy(0,0,0,d),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=u,this._cacheShadowNodes=new WeakMap,this._initialized=!1,this._callDepth=-1,this._initPromise=null,this._compilationPromises=null,this.transparent=!0,this.opaque=!0,this.shadowMap={enabled:!1,transmitted:!1,type:1},this.xr=new Hx(this,c),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(this._renderTarget,this._mrt),n=e.overrideMaterial||s.material,a=this._objects.get(s,n,e,t,i.lightsNode,r,r.clippingContext),{fragmentShader:o,vertexShader:h}=a.getNodeBuilderState();return{fragmentShader:o,vertexShader:h}}}}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 Bx(this,s),this._animation=new my(this,this._nodes,this.info),this._attributes=new Ny(s,this.info),this._background=new E_(this,this._nodes),this._geometries=new Cy(this._attributes,this.info),this._textures=new Ky(this,s,this.info),this._pipelines=new Oy(s,this._nodes,this.info),this._bindings=new Uy(s,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new _y(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new $y(this.lighting),this._bundles=new Ox,this._renderContexts=new Xy(this),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,a=this._currentRenderObjectFunction,o=this._handleObjectFunction,h=this._compilationPromises;null===s&&(s=e);const l=!0===e.isScene?e:!0===s.isScene?s:ev,u=this.needsFrameBufferTarget&&null===this._renderTarget?this._getFrameBufferTarget():this._renderTarget||this._outputRenderTarget,c=this._renderContexts.get(u,this._mrt),d=this._activeMipmapLevel,p=[];this._currentRenderContext=c,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=p,i.renderId++,i.update(),c.depth=this.depth,c.stencil=this.stencil,c.clippingContext||(c.clippingContext=new Lx),c.clippingContext.updateGlobal(l,t),l.onBeforeRender(this,e,t,u);const m=this._renderLists.get(l,t);if(m.begin(),this._projectObject(e,t,0,m,c.clippingContext),s!==e&&s.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&m.pushLight(e)}),m.finish(),null!==u){this._textures.updateRenderTarget(u,d);const e=this._textures.get(u);c.textures=e.textures,c.depthTexture=e.depthTexture}else c.textures=null,c.depthTexture=null;s!==e?this._background.update(s,m,c):this._background.update(l,m,c);const g=m.opaque,f=m.transparent,y=m.transparentDoublePass,b=m.lightsNode;!0===this.opaque&&g.length>0&&this._renderObjects(g,t,l,b),!0===this.transparent&&f.length>0&&this._renderTransparents(f,y,t,l,b),i.renderId=r,this._currentRenderContext=n,this._currentRenderObjectFunction=a,this._handleObjectFunction=o,this._compilationPromises=h;for(const e of p){const t=this._objects.get(e.object,e.material,e.scene,e.camera,e.lightsNode,e.renderContext,e.clippingContext,e.passId);t.drawRange=e.object.geometry.drawRange,t.group=e.group,this._geometries.updateForRender(t),await this._nodes.getForRenderAsync(t),this._nodes.updateBefore(t),this._nodes.updateForRender(t),this._bindings.updateForRender(t);const s=[];this._pipelines.getForRender(t,s),s.length>0&&await Promise.all(s),this._nodes.updateAfter(t),await vt()}}async renderAsync(e,t){xt('Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.render(e,t)}async waitForGPU(){_t("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=Uc,t.modelNormalViewMatrix=kc):this.highPrecision&&(delete t.modelViewMatrix,delete t.modelNormalViewMatrix)}get highPrecision(){const e=this.contextNode.value;return e.modelViewMatrix===Uc&&e.modelNormalViewMatrix===kc}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getOutputBufferType(){return this._outputBufferType}getColorBufferType(){return xt('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}`),_t(t),this._isDeviceLost=!0}_renderBundle(e,t,s){const{bundleGroup:i,camera:r,renderList:n}=e,a=this._currentRenderContext,o=this._bundles.get(i,r,a),h=this.backend.get(o),l=i.version!==h.version;if(l||void 0===h.bundleGPU){this.backend.beginBundle(a),(void 0===h.renderObjects||l)&&(h.renderObjects=[]),this._currentRenderBundle=o;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(a,o),h.version=i.version}else{const{renderObjects:e}=h;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(a,o)}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!==Wt.workingColorSpace;if(!1===s&&!1===i)return null;const{width:r,height:n}=this.getDrawingBufferSize(tv),{depth:a,stencil:o}=this,h=this._outputRenderTarget||this._canvasTarget;let l=this._frameBufferTargets.get(h);if(void 0===l){l=new is(r,n,{depthBuffer:a,stencilBuffer:o,type:this._outputBufferType,format:re,colorSpace:Wt.workingColorSpace,generateMipmaps:!1,minFilter:z,magFilter:z,samples:this.samples}),l.isPostProcessingRenderTarget=!0;const e=()=>{h.removeEventListener("dispose",e),l.dispose(),this._frameBufferTargets.delete(h)};h.addEventListener("dispose",e),this._frameBufferTargets.set(h,l)}const u=this.getOutputRenderTarget();l.depthBuffer=a,l.stencilBuffer=o,null!==u?l.setSize(u.width,u.height,u.depth):l.setSize(r,n,1);const c=this._outputRenderTarget?this._outputRenderTarget.viewport:h._viewport,d=this._outputRenderTarget?this._outputRenderTarget.scissor:h._scissor,p=this._outputRenderTarget?1:h._pixelRatio,m=this._outputRenderTarget?this._outputRenderTarget.scissorTest:h._scissorTest;return l.viewport.copy(c),l.scissor.copy(d),l.viewport.multiplyScalar(p),l.scissor.multiplyScalar(p),l.scissorTest=m,l.multiview=null!==u&&u.multiview,l.resolveDepthBuffer=null===u||u.resolveDepthBuffer,l._autoAllocateDepthBuffer=null!==u&&u._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,a=this._currentRenderContext,o=this._currentRenderObjectFunction,h=this._handleObjectFunction;this._callDepth++;const l=!0===e.isScene?e:ev,u=this._renderTarget||this._outputRenderTarget,c=this._activeCubeFace,d=this._activeMipmapLevel;let p;if(null!==i?(p=i,this.setRenderTarget(p)):p=u,null!==p&&!0===p.depthBuffer){const e=this._textures.get(p);!0!==e.depthInitialized&&((!1===this.autoClear||!0===this.autoClear&&!1===this.autoClearDepth)&&this.clearDepth(),e.depthInitialized=!0)}const m=this._renderContexts.get(p,this._mrt,this._callDepth);this._currentRenderContext=m,this._currentRenderObjectFunction=this._renderObjectFunction||this.renderObject,this._handleObjectFunction=this._renderObjectDirect,this.info.calls++,this.info.render.calls++,this.info.render.frameCalls++,r.renderId=this.info.calls,this.backend.updateTimeStampUID(m),this.inspector.beginRender(this.backend.getTimestampUID(m),e,t,p);const g=this.xr;if(!1===g.isPresenting){let e=!1;if(!0===this.reversedDepthBuffer&&!0!==t.reversedDepth){if(t._reversedDepth=!0,t.isArrayCamera)for(const e of t.cameras)e._reversedDepth=!0;e=!0}const s=this.coordinateSystem;if(t.coordinateSystem!==s){if(t.coordinateSystem=s,t.isArrayCamera)for(const e of t.cameras)e.coordinateSystem=s;e=!0}if(!0===e&&(t.updateProjectionMatrix(),t.isArrayCamera))for(const e of t.cameras)e.updateProjectionMatrix()}!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&!0===t.matrixWorldAutoUpdate&&t.updateMatrixWorld(),!0===g.enabled&&!0===g.isPresenting&&(!0===g.cameraAutoUpdate&&g.updateCamera(t),t=g.getCamera());const f=this._canvasTarget;let y=f._viewport,b=f._scissor,_=f._pixelRatio;null!==p&&(y=p.viewport,b=p.scissor,_=1),this.getDrawingBufferSize(tv),sv.set(0,0,tv.width,tv.height);const x=void 0===y.minDepth?0:y.minDepth,v=void 0===y.maxDepth?1:y.maxDepth;m.viewportValue.copy(y).multiplyScalar(_).floor(),m.viewportValue.width>>=d,m.viewportValue.height>>=d,m.viewportValue.minDepth=x,m.viewportValue.maxDepth=v,m.viewport=!1===m.viewportValue.equals(sv),m.scissorValue.copy(b).multiplyScalar(_).floor(),m.scissor=f._scissorTest&&!1===m.scissorValue.equals(sv),m.scissorValue.width>>=d,m.scissorValue.height>>=d,m.clippingContext||(m.clippingContext=new Lx),m.clippingContext.updateGlobal(l,t),l.onBeforeRender(this,e,t,p);const T=t.isArrayCamera?rv:iv;t.isArrayCamera||(nv.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),T.setFromProjectionMatrix(nv,t.coordinateSystem,t.reversedDepth));const S=this._renderLists.get(e,t);if(S.begin(),this._projectObject(e,t,0,S,m.clippingContext),S.finish(),!0===this.sortObjects&&S.sort(this._opaqueSort,this._transparentSort),null!==p){this._textures.updateRenderTarget(p,d);const e=this._textures.get(p);m.textures=e.textures,m.depthTexture=e.depthTexture,m.width=e.width,m.height=e.height,m.renderTarget=p,m.depth=p.depthBuffer,m.stencil=p.stencilBuffer}else m.textures=null,m.depthTexture=null,m.width=tv.width,m.height=tv.height,m.depth=this.depth,m.stencil=this.stencil;m.width>>=d,m.height>>=d,m.activeCubeFace=c,m.activeMipmapLevel=d,m.occlusionQueryCount=S.occlusionQueryCount,m.scissorValue.max(av.set(0,0,0,0)),m.scissorValue.x+m.scissorValue.width>m.width&&(m.scissorValue.width=Math.max(m.width-m.scissorValue.x,0)),m.scissorValue.y+m.scissorValue.height>m.height&&(m.scissorValue.height=Math.max(m.height-m.scissorValue.y,0)),this._background.update(l,S,m),m.camera=t,this.backend.beginRender(m);const{bundles:w,lightsNode:M,transparentDoublePass:N,transparent:A,opaque:E}=S;return w.length>0&&this._renderBundles(w,l,M),!0===this.opaque&&E.length>0&&this._renderObjects(E,t,l,M),!0===this.transparent&&A.length>0&&this._renderTransparents(A,N,t,l,M),this.backend.finishRender(m),r.renderId=n,this._currentRenderContext=a,this._currentRenderObjectFunction=o,this._handleObjectFunction=h,this._callDepth--,null!==i&&(this.setRenderTarget(u,c,d),this._renderOutput(p)),l.onAfterRender(this,e,t,p),this.inspector.finishRender(this.backend.getTimestampUID(m)),m}_setXRLayerSize(e,t){this._canvasTarget._width=e,this._canvasTarget._height=t,this.setViewport(0,0,e,t)}_renderOutput(e){const t=this._nodes.getOutputCacheKey();let s,i=this._quadCache.get(e.texture);if(void 0===i){s=new lb(new Em),s.name="Output Color Transform",s.material.name="outputColorTransform",s.material.fragmentNode=this._nodes.getOutputNode(e.texture),i={quad:s,cacheKey:t},this._quadCache.set(e.texture,i);const r=()=>{s.material.dispose(),this._quadCache.delete(e.texture),e.texture.removeEventListener("dispose",r)};e.texture.addEventListener("dispose",r)}else s=i.quad,i.cacheKey!==t&&(s.material.fragmentNode=this._nodes.getOutputNode(e.texture),s.material.needsUpdate=!0,i.cacheKey=t);const r=this.autoClear,n=this.xr.enabled;this.autoClear=!1,this.xr.enabled=!1,this._renderScene(s,s.camera,!1),this.autoClear=r,this.xr.enabled=n}getMaxAnisotropy(){return this.backend.capabilities.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,t=null,s=0,i=-1){if(null!==t&&t.isReadbackBuffer&&!1===this.info.memoryMap.has(t)){this.info.createReadbackBuffer(t);const e=()=>{t.removeEventListener("dispose",e),this.info.destroyReadbackBuffer(t)};t.addEventListener("dispose",e)}if(s%4!=0||i>0&&i%4!=0)throw new Error('THREE.Renderer: "getArrayBufferAsync()" offset and count must be a multiple of 4.');return await this.backend.getArrayBufferAsync(e,t,s,i)}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!0===this.reversedDepthBuffer?1-this._clearDepth: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.get(i,null,-1),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;const t=this.backend.getClearColor();r.clearColorValue.r=t.r,r.clearColorValue.g=t.g,r.clearColorValue.b=t.b,r.clearColorValue.a=t.a,r.clearDepthValue=this.getClearDepth(),r.clearStencilValue=this.getClearStencil(),r.activeCubeFace=this.getActiveCubeFace(),r.activeMipmapLevel=this.getActiveMipmapLevel(),!0===i.depthBuffer&&(e.depthInitialized=!0)}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){xt('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(){xt('Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.'),this.clear(!0,!1,!1)}async clearDepthAsync(){xt('Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!0,!1)}async clearStencilAsync(){xt('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!==Wt.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:Wt.workingColorSpace}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||null===this._renderTarget}dispose(){if(!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();for(const e of this._frameBufferTargets.keys())e.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);for(const e of this._frameBufferTargets.keys())e.dispose()}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}compute(e,t=null){if(!0===this._isDeviceLost)return;if(!1===this._initialized)return bt("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,a=this._bindings,o=this._nodes,h=Array.isArray(e)?e:[e];if(void 0===h[0]||!0!==h[0].isComputeNode)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");r.beginCompute(e);for(const s of h){if(!1===n.has(s)){const e=()=>{s.removeEventListener("dispose",e),n.delete(s),a.deleteForCompute(s),o.delete(s)};s.addEventListener("dispose",e);const t=s.onInitFunction;null!==t&&t.call(s,{renderer:this})}o.updateForCompute(s),a.updateForCompute(s);const i=a.getForCompute(s),h=n.getForCompute(s,i);r.compute(e,s,i,h,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 xt('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){xt('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)}initRenderTarget(e){if(!1===this._initialized)throw new Error('Renderer: .initRenderTarget() called before the backend is initialized. Use "await renderer.init();" before before using this method.');this._textures.updateRenderTarget(e);const t=this._textures.get(e),s=this._renderContexts.get(e);s.textures=t.textures,s.depthTexture=t.depthTexture,s.width=t.width,s.height=t.height,s.renderTarget=e,s.depth=e.depthBuffer,s.stencil=e.stencilBuffer,this.backend.initRenderTarget(s)}copyFramebufferToTexture(e,t=null){if(null!==t)if(t.isVector2)t=av.set(t.x,t.y,e.image.width,e.image.height).floor();else{if(!t.isVector4)return void _t("Renderer.copyFramebufferToTexture: Invalid rectangle.");t=av.copy(t).floor()}else t=av.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,a=0){return this.backend.copyTextureToBuffer(e.textures[n],t,s,i,r,a)}_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?rv:iv;if(!e.frustumCulled||n.intersectsSprite(e,t)){!0===this.sortObjects&&av.setFromMatrixPosition(e.matrixWorld).applyMatrix4(nv);const{geometry:t,material:n}=e;n.visible&&i.push(e,t,n,s,av.z,null,r)}}else if(e.isLineLoop)_t("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?rv:iv;if(!e.frustumCulled||n.intersectsObject(e,t)){const{geometry:t,material:n}=e;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),av.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(nv)),Array.isArray(n)){const a=t.groups;for(let o=0,h=a.length;o<h;o++){const h=a[o],l=n[h.materialIndex];l&&l.visible&&i.push(e,t,l,s,av.z,h,r)}}else n.visible&&i.push(e,t,n,s,av.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,a=n.length;e<a;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,a=e.length;n<a;n++){const{object:a,geometry:o,material:h,group:l,clippingContext:u}=e[n];this._currentRenderObjectFunction(a,s,t,o,h,l,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,a=e.maskShadowNode&&e.maskShadowNode.isNode||e.maskNode&&e.maskNode.isNode;let o=null,h=null,l=null;if(i||r||n||a){let t,s;if(n?(t=e.castShadowNode.rgb,s=e.castShadowNode.a,!0!==this.shadowMap.transmitted&&xt("Renderer: `shadowMap.transmitted` needs to be set to `true` when using `material.castShadowNode`.")):(t=go(0),s=ao(1)),i&&(s=s.mul(vd("map","texture",e).a)),r&&(s=s.mul(e.colorNode.a)),h=_o(t,s),a){const t=e.maskShadowNode||e.maskNode;h=eo(([e])=>(t.not().discard(),e))(h)}}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:h,depthNode:l,positionNode:o},this._cacheShadowNodes.set(e,s)}return s}renderObject(e,t,s,i,r,n,a,o=null,h=null){let l,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,l=e.isNodeMaterial?e.colorNode:null,u=e.isNodeMaterial?e.depthNode:null,c=e.isNodeMaterial?e.positionNode:null,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);3===this.shadowMap.type?e.side=null!==r.shadowSide?r.shadowSide:r.side:e.side=null!==r.shadowSide?r.shadowSide:ov[r.side],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,a,n,o,"backSide"),r.side=0,this._handleObjectFunction(e,r,t,s,a,n,o,h),r.side=2):this._handleObjectFunction(e,r,t,s,a,n,o,h),p&&(t.overrideMaterial.colorNode=l,t.overrideMaterial.depthNode=u,t.overrideMaterial.positionNode=c,t.overrideMaterial.side=d),e.onAfterRender(this,t,s,i,r,n)}hasCompatibility(e){if(!1===this._initialized)throw new Error('Renderer: .hasCompatibility() called before the backend is initialized. Use "await renderer.init();" before using this method.');return this.backend.hasCompatibility(e)}_renderObjectDirect(e,t,s,i,r,n,a,o){const h=this._objects.get(e,t,s,i,r,this._currentRenderContext,a,o);if(h.drawRange=e.geometry.drawRange,h.group=n,null!==this._currentRenderBundle){this.backend.get(this._currentRenderBundle).renderObjects.push(h),h.bundle=this._currentRenderBundle.bundleGroup}const l=this._nodes.needsRefresh(h);l&&(this._nodes.updateBefore(h),this._geometries.updateForRender(h),this._nodes.updateForRender(h),this._bindings.updateForRender(h)),this._pipelines.updateForRender(h),this._pipelines.isReady(h)&&(this.backend.draw(h,this.info),l&&this._nodes.updateAfter(h))}_createObjectPipeline(e,t,s,i,r,n,a,o){if(null!==this._compilationPromises)return void this._compilationPromises.push({object:e,material:t,scene:s,camera:i,lightsNode:r,group:n,clippingContext:a,passId:o,renderContext:this._currentRenderContext});const h=this._objects.get(e,t,s,i,r,this._currentRenderContext,a,o);h.drawRange=e.geometry.drawRange,h.group=n,this._nodes.updateBefore(h),this._geometries.updateForRender(h),this._nodes.updateForRender(h),this._bindings.updateForRender(h),this._pipelines.getForRender(h,this._compilationPromises),this._nodes.updateAfter(h)}_onCanvasTargetResize(){this._initialized&&this.backend.updateSize()}get compile(){return this.compileAsync}}class lv{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)}}class uv extends lv{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)+(My-e%My)%My;var e}get buffer(){return this._buffer}update(){return!0}}class cv extends uv{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let dv=0;class pv extends cv{constructor(e,t){super("UniformBuffer_"+dv++,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 mv extends cv{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[],this._updateRangeCache=new Map}addUniformUpdateRange(e){const t=e.index;if(!0!==this._updateRangeCache.has(t)){const s=this.updateRanges,i={start:e.offset,count:e.itemSize};s.push(i),this._updateRangeCache.set(t,i)}}clearUpdateRanges(){this._updateRangeCache.clear(),super.clearUpdateRanges()}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,a=t%My,o=a%r,h=a+o;t+=o,0!==h&&My-h<n&&(t+=My-h),i.offset=t/e,i.index=s,t+=n}return Math.ceil(t/My)*My}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 _t("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,this.addUniformUpdateRange(e)}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 a=this._getBufferForType(n);a[r+0]=s[r+0]=i.x,a[r+1]=s[r+1]=i.y,t=!0,this.addUniformUpdateRange(e)}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 a=this._getBufferForType(n);a[r+0]=s[r+0]=i.x,a[r+1]=s[r+1]=i.y,a[r+2]=s[r+2]=i.z,t=!0,this.addUniformUpdateRange(e)}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+3]!==i.w){const a=this._getBufferForType(n);a[r+0]=s[r+0]=i.x,a[r+1]=s[r+1]=i.y,a[r+2]=s[r+2]=i.z,a[r+3]=s[r+3]=i.w,t=!0,this.addUniformUpdateRange(e)}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 n=this.buffer;n[r+0]=s[r+0]=i.r,n[r+1]=s[r+1]=i.g,n[r+2]=s[r+2]=i.b,t=!0,this.addUniformUpdateRange(e)}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 n=this.buffer;n[r+0]=s[r+0]=i[0],n[r+1]=s[r+1]=i[1],n[r+2]=s[r+2]=i[2],n[r+4]=s[r+4]=i[3],n[r+5]=s[r+5]=i[4],n[r+6]=s[r+6]=i[5],n[r+8]=s[r+8]=i[6],n[r+9]=s[r+9]=i[7],n[r+10]=s[r+10]=i[8],t=!0,this.addUniformUpdateRange(e)}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,this.addUniformUpdateRange(e)}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 gv=0;class fv extends mv{constructor(e,t){super(e),this.id=gv++,this.groupNode=t,this.isNodeUniformsGroup=!0}}class yv extends lv{constructor(e,t){super(e),this._texture=null,this._onTextureDispose=()=>{this.generation=null,this.version=-1},this.texture=t,this.version=t?t.version:-1,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=-1,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=-1},e.texture=this.texture,e}}let bv=0;class _v extends yv{constructor(e,t){super(e,t),this.id=bv++,this.store=!1,this.mipLevel=0,this.isSampledTexture=!0}}class xv extends _v{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 vv extends xv{constructor(e,t,s,i=null){super(e,t,s,i),this.isSampledCubeTexture=!0}}class Tv extends xv{constructor(e,t,s,i=null){super(e,t,s,i),this.isSampledTexture3D=!0}}const Sv={bitcast_int_uint:new Pb("uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }"),bitcast_uint_int:new Pb("uint tsl_bitcast_uint_to_int ( uint x ) { return floatBitsToInt( uintBitsToFloat ( x ) ); }")},wv={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"},Mv={low:"lowp",medium:"mediump",high:"highp"},Nv={swizzleAssign:!0,storageBuffer:!1},Av={perspective:"smooth",linear:"noperspective"},Ev={centroid:"centroid"},Rv="\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 highp sampler2DShadow;\nprecision highp sampler2DArrayShadow;\nprecision highp samplerCubeShadow;\n";class Cv extends hx{constructor(e,t){super(e,t,new Rx),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]}}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==He}_include(e){const t=Sv[e];return t.build(this),this.addInclude(t),t}getMethod(e){return void 0!==Sv[e]&&this._include(e),wv[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?he:oe;2===i?n=r?ue:le:3===i?n=r?1032:ie:4===i&&(n=r?ce:re);const a={Float32Array:Y,Uint8Array:j,Uint16Array:H,Uint32Array:X,Int8Array:$,Int16Array:W,Int32Array:q,Uint8ClampedArray:j},o=Math.pow(2,Math.ceil(Math.log2(Math.sqrt(s/i))));let h=Math.ceil(s/i/o);o*h*i<s&&h++;const l=o*h*i,u=new e.constructor(l);u.set(e,0),t.array=u;const c=new fr(t.array,o,h,n,a[t.array.constructor.name]||Y);c.needsUpdate=!0,c.isPBOTexture=!0;const d=new Qu(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?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 a=s.build(this,"uint"),o=this.getDataFromNode(e);let h=o.propertyName;if(void 0===h){const s=this.getVarFromNode(e);h=this.getPropertyName(s);const r=this.getDataFromNode(t);let l=r.propertySizeName;void 0===l&&(l=h+"Size",this.getVarFromNode(t,l,"uint"),this.addLineFlowCode(`${l} = uint( textureSize( ${n}, 0 ).x )`,e),r.propertySizeName=l);const{itemSize:u}=i,c="."+Jn.join("").slice(0,u),d=`ivec2(${a} % ${l}, ${a} / ${l})`,p=this.generateTextureLoad(null,n,d,"0",null,null);let m="vec4";i.pbo.type===X?m="uvec4":i.pbo.type===q&&(m="ivec4"),this.addLineFlowCode(`${h} = ${m}(${p})${c}`,e),o.propertyName=h}return h}generateTextureLoad(e,t,s,i,r,n){let a;return null===i&&(i="0"),a=r?n?`texelFetchOffset( ${t}, ivec3( ${s}, ${r} ), int( ${i} ), ${n} )`:`texelFetch( ${t}, ivec3( ${s}, ${r} ), int( ${i} ) )`:n?`texelFetchOffset( ${t}, ${s}, int( ${i} ), ${n} )`:`texelFetch( ${t}, ${s}, int( ${i} ) )`,null!==e&&e.isDepthTexture&&(a+=".x"),a}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,n){return r&&(s=`vec3( ${s}, ${r} )`),n?`textureLodOffset( ${t}, ${s}, ${i}, ${n} )`:`textureLod( ${t}, ${s}, ${i} )`}generateTextureBias(e,t,s,i,r,n){return r&&(s=`vec3( ${s}, ${r} )`),n?`textureOffset( ${t}, ${s}, ${n}, ${i} )`:`texture( ${t}, ${s}, ${i} )`}generateTextureGrad(e,t,s,i,r,n){return r&&(s=`vec3( ${s}, ${r} )`),n?`textureGradOffset( ${t}, ${s}, ${i[0]}, ${i[1]}, ${n} )`:`textureGrad( ${t}, ${s}, ${i[0]}, ${i[1]} )`}generateTextureCompare(e,t,s,i,r,n,a=this.shaderStage){if("fragment"===a)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} ) )`;_t(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${a} shader.`)}getUniforms(e){const t=this.uniforms[e],s=[],i={};for(const e of t){let t=null,r=!1;if("texture"===e.type||"texture3D"===e.type){const s=e.node.value;let i="";!0!==s.isDataTexture&&!0!==s.isData3DTexture||(s.type===X?i="u":s.type===q&&(i="i")),t="texture3D"===e.type&&!1===s.isArrayTexture?`${i}sampler3D ${e.name};`:s.compareFunction?!0===s.isArrayTexture?`sampler2DArrayShadow ${e.name};`:`sampler2DShadow ${e.name};`:!0===s.isArrayTexture||!0===s.isDataArrayTexture||!0===s.isCompressedArrayTexture?`${i}sampler2DArray ${e.name};`:`${i}sampler2D ${e.name};`}else if("cubeTexture"===e.type)t=`samplerCube ${e.name};`;else if("cubeDepthTexture"===e.type){t=e.node.value.compareFunction?`samplerCubeShadow ${e.name};`:`samplerCube ${e.name};`}else if("buffer"===e.type){const s=e.node,i=this.getType(s.bufferType),r=s.bufferCount,n=r>0?r:"";t=`${s.name} {\n\t${i} ${e.name}[${n}];\n};\n`}else{const t=e.groupNode.name;if(void 0===i[t]){const e=this.uniformGroups[t];if(void 0!==e){const s=[];for(const t of e.uniforms){const e=t.getType(),i=this.getVectorType(e),r=t.nodeUniform.node.precision;let n=`${i} ${t.name};`;null!==r&&(n=Mv[r]+" "+n),s.push("\t"+n)}i[t]=s}}r=!0}if(!r){const i=e.node.precision;null!==i&&(t=Mv[i]+" "+t),t="uniform "+t,s.push(t)}}let r="";for(const e in i){const t=i[e];r+=this._getGLSLUniformStruct(e,t.join("\n"))+"\n"}return r+=s.join("\n"),r}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==q){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+=`${Av[i.interpolationType]||i.interpolationType} ${Ev[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+=`${Av[e.interpolationType]||e.interpolationType} ${Ev[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(){_t("GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node")}getInvocationSubgroupIndex(){_t("GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node")}getSubgroupIndex(){_t("GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node")}getDrawIndex(){return this.renderer.backend.extensions.has("WEBGL_multi_draw")?"uint( gl_DrawID )":"nodeUniformDrawId"}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=Nv[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)}Nv[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${Rv}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\n\n// attributes\n${e.attributes}\n\n// vars\n${e.vars}\n\n// codes\n${e.codes}\n\nvoid main() {\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${Rv}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\n\n// vars\n${e.vars}\n\n// codes\n${e.codes}\n\nvoid main() {\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];if(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,!0),n.structs=this.getStructs(t),n.codes=this.getCodes(t),n.transforms=this.getTransforms(t),n.flow=s,"vertex"===t){const e=this.renderer.backend.extensions;this.object.isBatchedMesh&&!1===e.has("WEBGL_multi_draw")&&(n.uniforms+="\nuniform uint nodeUniformDrawId;\n")}}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 a=n.uniformGPU;if(void 0===a){const i=e.groupNode,o=i.name,h=this.getBindGroupArray(o,s);if("texture"===t)a=new xv(r.name,r.node,i),h.push(a);else if("cubeTexture"===t||"cubeDepthTexture"===t)a=new vv(r.name,r.node,i),h.push(a);else if("texture3D"===t)a=new Tv(r.name,r.node,i),h.push(a);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 pv(e,i),s.name=e.name,t.buffer=s),h.push(s),a=s}else{let e=this.uniformGroups[o];void 0===e?(e=new fv(o,i),this.uniformGroups[o]=e,h.push(e)):-1===h.indexOf(e)&&h.push(e),a=this.getNodeUniform(r,t);const s=a.name,n=e.uniforms.some(e=>e.name===s);n||e.addUniform(a)}n.uniformGPU=a}return r}}let Pv=null,Bv=null;class Fv{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={[ct]:null,[ut]: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:")?ut:ct;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 xt("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(){}getDrawingBufferSize(){return Pv=Pv||new Dt,this.renderer.getDrawingBufferSize(Pv)}setScissorTest(){}getClearColor(){const e=this.renderer;return Bv=Bv||new Qy,e.getClearColor(Bv),Bv.getRGB(Bv),Bv}getDomElement(){let e=this.domElement;return null===e&&(e=void 0!==this.parameters.canvas?this.parameters.canvas:function(){const e=mt("canvas");return e.style.display="block",e}(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${a} webgpu`),this.domElement=e),e}hasCompatibility(){return!1}initRenderTarget(){}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 Lv,Dv,Iv=0;class Ov{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 Uv{constructor(e){this.backend=e}createAttribute(e,t){const s=this.backend,{gl:i}=s,r=e.array,n=e.usage||i.STATIC_DRAW,a=e.isInterleavedBufferAttribute?e.data:e,o=s.get(a);let h,l=o.bufferGPU;if(void 0===l&&(l=this._createBuffer(i,t,r,n),o.bufferGPU=l,o.bufferType=t,o.version=a.version),r instanceof Float32Array)h=i.FLOAT;else if("undefined"!=typeof Float16Array&&r instanceof Float16Array)h=i.HALF_FLOAT;else if(r instanceof Uint16Array)h=e.isFloat16BufferAttribute?i.HALF_FLOAT:i.UNSIGNED_SHORT;else if(r instanceof Int16Array)h=i.SHORT;else if(r instanceof Uint32Array)h=i.UNSIGNED_INT;else if(r instanceof Int32Array)h=i.INT;else if(r instanceof Int8Array)h=i.BYTE;else if(r instanceof Uint8Array)h=i.UNSIGNED_BYTE;else{if(!(r instanceof Uint8ClampedArray))throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+r);h=i.UNSIGNED_BYTE}let u={bufferGPU:l,bufferType:t,type:h,byteLength:r.byteLength,bytesPerElement:r.BYTES_PER_ELEMENT,version:e.version,pbo:e.pbo,isInteger:h===i.INT||h===i.UNSIGNED_INT||e.gpuType===q,id:Iv++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(i,t,r,n);u=new Ov(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),a=n.bufferType,o=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(s.bindBuffer(a,n.bufferGPU),0===o.length)s.bufferSubData(a,0,i);else{for(let e=0,t=o.length;e<t;e++){const t=o[e];s.bufferSubData(a,t.start*i.BYTES_PER_ELEMENT,i,t.start,t.count)}r.clearUpdateRanges()}s.bindBuffer(a,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,t=null,s=0,i=-1){const r=this.backend,{gl:n}=r,a=e.isInterleavedBufferAttribute?e.data:e,o=r.get(a),{bufferGPU:h}=o,l=-1===i?o.byteLength-s:i;let u;if(null===t)u=new Uint8Array(new ArrayBuffer(l));else if(t.isReadbackBuffer){if(!0===t._mapped)throw new Error("WebGPURenderer: ReadbackBuffer must be released before being used again.");const e=()=>{t.buffer=null,t._mapped=!1,t.removeEventListener("release",e),t.removeEventListener("dispose",e)};t.addEventListener("release",e),t.addEventListener("dispose",e),u=new Uint8Array(new ArrayBuffer(l)),t.buffer=u.buffer}else u=new Uint8Array(t);return n.bindBuffer(n.COPY_READ_BUFFER,h),n.getBufferSubData(n.COPY_READ_BUFFER,s,u),n.bindBuffer(n.COPY_READ_BUFFER,null),n.bindBuffer(n.COPY_WRITE_BUFFER,null),t&&t.isReadbackBuffer?t:u.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 kv{constructor(e){this.backend=e,this.gl=this.backend.gl,this.enabled={},this.parameters={},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.currentDepthReversed=!1,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;Lv={[u]:e.FUNC_ADD,[c]:e.FUNC_SUBTRACT,[d]:e.FUNC_REVERSE_SUBTRACT},Dv={[p]:e.ZERO,[m]:e.ONE,[g]:e.SRC_COLOR,[y]:e.SRC_ALPHA,[S]:e.SRC_ALPHA_SATURATE,[v]:e.DST_COLOR,[_]:e.DST_ALPHA,[f]:e.ONE_MINUS_SRC_COLOR,[b]:e.ONE_MINUS_SRC_ALPHA,[T]:e.ONE_MINUS_DST_COLOR,[x]:e.ONE_MINUS_DST_ALPHA};const t=e.getParameter(e.SCISSOR_BOX),s=e.getParameter(e.VIEWPORT);this.currentScissor=(new ss).fromArray(t),this.currentViewport=(new ss).fromArray(s),this._tempVec4=new ss}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,t,s){const i=this.gl,r=this.backend.drawBuffersIndexedExt;if(r)for(let n=0;n<e.length;n++){const a=e[n];let o=null;if(null!==t){const e=t.getBlendMode(a.name);6===e.blending?o=s:0!==e.blending&&(o=e)}else o=s;null!==o?this._setMRTBlendingIndex(n,o):r.blendFuncSeparateiOES(n,i.ONE,i.ZERO,i.ONE,i.ZERO)}else xt("WebGPURenderer: Multiple Render Targets (MRT) blending configuration is not fully supported in compatibility mode. The material blending will be used for all render targets.")}_setMRTBlendingIndex(e,t){const{gl:s}=this,i=this.backend.drawBuffersIndexedExt,r=t.blending,n=t.blendSrc,a=t.blendDst,o=t.blendEquation,h=t.premultipliedAlpha;if(5===r){const s=null!==t.blendSrcAlpha?t.blendSrcAlpha:n,r=null!==t.blendDstAlpha?t.blendDstAlpha:a,h=null!==t.blendEquationAlpha?t.blendEquationAlpha:o;i.blendEquationSeparateiOES(e,Lv[o],Lv[h]),i.blendFuncSeparateiOES(e,Dv[n],Dv[a],Dv[s],Dv[r])}else if(i.blendEquationSeparateiOES(e,s.FUNC_ADD,s.FUNC_ADD),h)switch(r){case 1:default:i.blendFuncSeparateiOES(e,s.ONE,s.ONE_MINUS_SRC_ALPHA,s.ONE,s.ONE_MINUS_SRC_ALPHA);break;case 2:i.blendFuncSeparateiOES(e,s.ONE,s.ONE,s.ONE,s.ONE);break;case 3:i.blendFuncSeparateiOES(e,s.ZERO,s.ONE_MINUS_SRC_COLOR,s.ZERO,s.ONE);break;case 4:i.blendFuncSeparateiOES(e,s.DST_COLOR,s.ONE_MINUS_SRC_ALPHA,s.ZERO,s.ONE)}else switch(r){case 1:default:i.blendFuncSeparateiOES(e,s.SRC_ALPHA,s.ONE_MINUS_SRC_ALPHA,s.ONE,s.ONE_MINUS_SRC_ALPHA);break;case 2:i.blendFuncSeparateiOES(e,s.SRC_ALPHA,s.ONE,s.ONE,s.ONE);break;case 3:i.blendFuncSeparateiOES(e,s.ZERO,s.ONE_MINUS_SRC_COLOR,s.ZERO,s.ONE);break;case 4:i.blendFuncSeparateiOES(e,s.DST_COLOR,s.ONE_MINUS_SRC_ALPHA,s.ZERO,s.ONE)}}setBlending(e,t,s,i,r,n,a,o){const{gl:h}=this;if(0!==e){if(!1===this.currentBlendingEnabled&&(this.enable(h.BLEND),this.currentBlendingEnabled=!0),5===e)r=r||t,n=n||s,a=a||i,t===this.currentBlendEquation&&r===this.currentBlendEquationAlpha||(h.blendEquationSeparate(Lv[t],Lv[r]),this.currentBlendEquation=t,this.currentBlendEquationAlpha=r),s===this.currentBlendSrc&&i===this.currentBlendDst&&n===this.currentBlendSrcAlpha&&a===this.currentBlendDstAlpha||(h.blendFuncSeparate(Dv[s],Dv[i],Dv[n],Dv[a]),this.currentBlendSrc=s,this.currentBlendDst=i,this.currentBlendSrcAlpha=n,this.currentBlendDstAlpha=a),this.currentBlending=e,this.currentPremultipledAlpha=!1;else if(e!==this.currentBlending||o!==this.currentPremultipledAlpha){if(this.currentBlendEquation===u&&this.currentBlendEquationAlpha===u||(h.blendEquation(h.FUNC_ADD),this.currentBlendEquation=u,this.currentBlendEquationAlpha=u),o)switch(e){case 1:h.blendFuncSeparate(h.ONE,h.ONE_MINUS_SRC_ALPHA,h.ONE,h.ONE_MINUS_SRC_ALPHA);break;case 2:h.blendFunc(h.ONE,h.ONE);break;case 3:h.blendFuncSeparate(h.ZERO,h.ONE_MINUS_SRC_COLOR,h.ZERO,h.ONE);break;case 4:h.blendFuncSeparate(h.DST_COLOR,h.ONE_MINUS_SRC_ALPHA,h.ZERO,h.ONE);break;default:_t("WebGLState: Invalid blending: ",e)}else switch(e){case 1:h.blendFuncSeparate(h.SRC_ALPHA,h.ONE_MINUS_SRC_ALPHA,h.ONE,h.ONE_MINUS_SRC_ALPHA);break;case 2:h.blendFuncSeparate(h.SRC_ALPHA,h.ONE,h.ONE,h.ONE);break;case 3:_t("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case 4:_t("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:_t("WebGLState: Invalid blending: ",e)}this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentBlending=e,this.currentPremultipledAlpha=o}}else!0===this.currentBlendingEnabled&&(this.disable(h.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)}setReversedDepth(e){if(this.currentDepthReversed!==e){const t=this.backend.extensions.get("EXT_clip_control");e?t.clipControlEXT(t.LOWER_LEFT_EXT,t.ZERO_TO_ONE_EXT):t.clipControlEXT(t.LOWER_LEFT_EXT,t.NEGATIVE_ONE_TO_ONE_EXT),this.currentDepthReversed=e}}setDepthMask(e){this.currentDepthMask!==e&&(this.gl.depthMask(e),this.currentDepthMask=e)}setDepthFunc(e){if(this.currentDepthReversed&&(e=Tt[e]),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:a}=this;void 0===s&&(s=null===r?i.TEXTURE0+a-1:r);let o=n[s];void 0===o&&(o={type:void 0,texture:void 0},n[s]=o),o.type===e&&o.texture===t||(r!==s&&(i.activeTexture(s),this.currentTextureSlot=s),i.bindTexture(e,t),o.type=e,o.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)}getParameter(e){const{gl:t,parameters:s}=this;return void 0!==s[e]?s[e]:t.getParameter(e)}pixelStorei(e,t){const{gl:s,parameters:i}=this;i[e]!==t&&(s.pixelStorei(e,t),i[e]=t)}}class zv{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=Wt.getTransfer(t);if(e===j)return s.UNSIGNED_BYTE;if(e===Q)return s.UNSIGNED_SHORT_4_4_4_4;if(e===Z)return s.UNSIGNED_SHORT_5_5_5_1;if(e===ee)return s.UNSIGNED_INT_5_9_9_9_REV;if(e===te)return s.UNSIGNED_INT_10F_11F_11F_REV;if(e===$)return s.BYTE;if(e===W)return s.SHORT;if(e===H)return s.UNSIGNED_SHORT;if(e===q)return s.INT;if(e===X)return s.UNSIGNED_INT;if(e===Y)return s.FLOAT;if(e===K)return s.HALF_FLOAT;if(e===se)return s.ALPHA;if(e===ie)return s.RGB;if(e===re)return s.RGBA;if(e===ne)return s.DEPTH_COMPONENT;if(e===ae)return s.DEPTH_STENCIL;if(e===oe)return s.RED;if(e===he)return s.RED_INTEGER;if(e===le)return s.RG;if(e===ue)return s.RG_INTEGER;if(e===ce)return s.RGBA_INTEGER;if(e===de||e===pe||e===me||e===ge)if(n===Ke){if(r=i.get("WEBGL_compressed_texture_s3tc_srgb"),null===r)return null;if(e===de)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(e===pe)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(e===me)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(e===ge)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(r=i.get("WEBGL_compressed_texture_s3tc"),null===r)return null;if(e===de)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(e===pe)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(e===me)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(e===ge)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(e===fe||e===ye||e===be||e===_e){if(r=i.get("WEBGL_compressed_texture_pvrtc"),null===r)return null;if(e===fe)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(e===ye)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(e===be)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(e===_e)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(e===xe||e===ve||e===Te||e===Se||e===we||e===Me||e===Ne){if(r=i.get("WEBGL_compressed_texture_etc"),null===r)return null;if(e===xe||e===ve)return n===Ke?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(e===Te)return n===Ke?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC;if(e===Se)return r.COMPRESSED_R11_EAC;if(e===we)return r.COMPRESSED_SIGNED_R11_EAC;if(e===Me)return r.COMPRESSED_RG11_EAC;if(e===Ne)return r.COMPRESSED_SIGNED_RG11_EAC}if(e===Ae||e===Ee||e===Re||e===Ce||e===Pe||e===Be||e===Fe||e===Le||e===De||e===Ie||e===Oe||e===Ue||e===ke||e===ze){if(r=i.get("WEBGL_compressed_texture_astc"),null===r)return null;if(e===Ae)return n===Ke?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(e===Ee)return n===Ke?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(e===Re)return n===Ke?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(e===Ce)return n===Ke?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(e===Pe)return n===Ke?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(e===Be)return n===Ke?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(e===Fe)return n===Ke?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(e===Le)return n===Ke?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(e===De)return n===Ke?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(e===Ie)return n===Ke?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(e===Oe)return n===Ke?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(e===Ue)return n===Ke?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(e===ke)return n===Ke?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(e===ze)return n===Ke?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}if(e===Ve){if(r=i.get("EXT_texture_compression_bptc"),null===r)return null;if(e===Ve)return n===Ke?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT}if(e===Ge||e===je||e===$e||e===We){if(r=i.get("EXT_texture_compression_rgtc"),null===r)return null;if(e===Ge)return r.COMPRESSED_RED_RGTC1_EXT;if(e===je)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(e===$e)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(e===We)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}return e===J?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 Vv,Gv,jv,$v=!1;class Wv{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},this._srcFramebuffer=null,this._dstFramebuffer=null,!1===$v&&(this._init(),$v=!0)}_init(){const e=this.gl;Vv={[L]:e.REPEAT,[D]:e.CLAMP_TO_EDGE,[I]:e.MIRRORED_REPEAT},Gv={[O]:e.NEAREST,[U]:e.NEAREST_MIPMAP_NEAREST,[k]:e.NEAREST_MIPMAP_LINEAR,[z]:e.LINEAR,[V]:e.LINEAR_MIPMAP_NEAREST,[G]:e.LINEAR_MIPMAP_LINEAR},jv={[Ze]:e.NEVER,[nt]:e.ALWAYS,[Je]:e.LESS,[tt]:e.LEQUAL,[et]:e.EQUAL,[rt]:e.GEQUAL,[st]:e.GREATER,[it]: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,n=!1){const{gl:a,extensions:o}=this;if(null!==e){if(void 0!==a[e])return a[e];bt("WebGLBackend: Attempt to use non-existing WebGL internal format '"+e+"'")}let h=null;i&&(h=o.get("EXT_texture_norm16"),h||bt("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let l=t;if(t===a.RED&&(s===a.FLOAT&&(l=a.R32F),s===a.HALF_FLOAT&&(l=a.R16F),s===a.UNSIGNED_BYTE&&(l=a.R8),s===a.BYTE&&(l=a.R8_SNORM),s===a.UNSIGNED_SHORT&&h&&(l=h.R16_EXT),s===a.SHORT&&h&&(l=h.R16_SNORM_EXT)),t===a.RED_INTEGER&&(s===a.UNSIGNED_BYTE&&(l=a.R8UI),s===a.UNSIGNED_SHORT&&(l=a.R16UI),s===a.UNSIGNED_INT&&(l=a.R32UI),s===a.BYTE&&(l=a.R8I),s===a.SHORT&&(l=a.R16I),s===a.INT&&(l=a.R32I)),t===a.RG&&(s===a.FLOAT&&(l=a.RG32F),s===a.HALF_FLOAT&&(l=a.RG16F),s===a.UNSIGNED_BYTE&&(l=a.RG8),s===a.BYTE&&(l=a.RG8_SNORM),s===a.UNSIGNED_SHORT&&h&&(l=h.RG16_EXT),s===a.SHORT&&h&&(l=h.RG16_SNORM_EXT)),t===a.RG_INTEGER&&(s===a.UNSIGNED_BYTE&&(l=a.RG8UI),s===a.UNSIGNED_SHORT&&(l=a.RG16UI),s===a.UNSIGNED_INT&&(l=a.RG32UI),s===a.BYTE&&(l=a.RG8I),s===a.SHORT&&(l=a.RG16I),s===a.INT&&(l=a.RG32I)),t===a.RGB){const e=n?Ye:Wt.getTransfer(r);s===a.FLOAT&&(l=a.RGB32F),s===a.HALF_FLOAT&&(l=a.RGB16F),s===a.UNSIGNED_BYTE&&(l=e===Ke?a.SRGB8:a.RGB8),s===a.BYTE&&(l=a.RGB8_SNORM),s===a.UNSIGNED_SHORT&&h&&(l=h.RGB16_EXT),s===a.SHORT&&h&&(l=h.RGB16_SNORM_EXT),s===a.UNSIGNED_SHORT_5_6_5&&(l=a.RGB565),s===a.UNSIGNED_SHORT_5_5_5_1&&(l=a.RGB5_A1),s===a.UNSIGNED_SHORT_4_4_4_4&&(l=a.RGB4),s===a.UNSIGNED_INT_5_9_9_9_REV&&(l=a.RGB9_E5),s===a.UNSIGNED_INT_10F_11F_11F_REV&&(l=a.R11F_G11F_B10F)}if(t===a.RGB_INTEGER&&(s===a.UNSIGNED_BYTE&&(l=a.RGB8UI),s===a.UNSIGNED_SHORT&&(l=a.RGB16UI),s===a.UNSIGNED_INT&&(l=a.RGB32UI),s===a.BYTE&&(l=a.RGB8I),s===a.SHORT&&(l=a.RGB16I),s===a.INT&&(l=a.RGB32I)),t===a.RGBA){const e=n?Ye:Wt.getTransfer(r);s===a.FLOAT&&(l=a.RGBA32F),s===a.HALF_FLOAT&&(l=a.RGBA16F),s===a.UNSIGNED_BYTE&&(l=e===Ke?a.SRGB8_ALPHA8:a.RGBA8),s===a.BYTE&&(l=a.RGBA8_SNORM),s===a.UNSIGNED_SHORT&&h&&(l=h.RGBA16_EXT),s===a.SHORT&&h&&(l=h.RGBA16_SNORM_EXT),s===a.UNSIGNED_SHORT_4_4_4_4&&(l=a.RGBA4),s===a.UNSIGNED_SHORT_5_5_5_1&&(l=a.RGB5_A1)}return t===a.RGBA_INTEGER&&(s===a.UNSIGNED_BYTE&&(l=a.RGBA8UI),s===a.UNSIGNED_SHORT&&(l=a.RGBA16UI),s===a.UNSIGNED_INT&&(l=a.RGBA32UI),s===a.BYTE&&(l=a.RGBA8I),s===a.SHORT&&(l=a.RGBA16I),s===a.INT&&(l=a.RGBA32I)),t===a.DEPTH_COMPONENT&&(s===a.UNSIGNED_SHORT&&(l=a.DEPTH_COMPONENT16),s===a.UNSIGNED_INT&&(l=a.DEPTH_COMPONENT24),s===a.FLOAT&&(l=a.DEPTH_COMPONENT32F)),t===a.DEPTH_STENCIL&&s===a.UNSIGNED_INT_24_8&&(l=a.DEPTH24_STENCIL8),l!==a.R16F&&l!==a.R32F&&l!==a.RG16F&&l!==a.RG32F&&l!==a.RGBA16F&&l!==a.RGBA32F||o.get("EXT_color_buffer_float"),l}setTextureParameters(e,t){const{gl:s,extensions:i,backend:r}=this,{state:n}=this.backend,a=Wt.getPrimaries(Wt.workingColorSpace),o=t.colorSpace===He?null:Wt.getPrimaries(t.colorSpace),h=t.colorSpace===He||a===o?s.NONE:s.BROWSER_DEFAULT_WEBGL;n.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,t.flipY),n.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),n.pixelStorei(s.UNPACK_ALIGNMENT,t.unpackAlignment),n.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,h),s.texParameteri(e,s.TEXTURE_WRAP_S,Vv[t.wrapS]),s.texParameteri(e,s.TEXTURE_WRAP_T,Vv[t.wrapT]),e!==s.TEXTURE_3D&&e!==s.TEXTURE_2D_ARRAY||t.isArrayTexture||s.texParameteri(e,s.TEXTURE_WRAP_R,Vv[t.wrapR]),s.texParameteri(e,s.TEXTURE_MAG_FILTER,Gv[t.magFilter]);const l=void 0!==t.mipmaps&&t.mipmaps.length>0,u=t.minFilter===z&&l?G:t.minFilter;if(s.texParameteri(e,s.TEXTURE_MIN_FILTER,Gv[u]),t.compareFunction&&(s.texParameteri(e,s.TEXTURE_COMPARE_MODE,s.COMPARE_REF_TO_TEXTURE),s.texParameteri(e,s.TEXTURE_COMPARE_FUNC,jv[t.compareFunction])),!0===i.has("EXT_texture_filter_anisotropic")){if(t.magFilter===O)return;if(t.minFilter!==k&&t.minFilter!==G)return;if(t.type===Y&&!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.capabilities.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:a,depth:o}=t,h=i.utils.convert(e.format,e.colorSpace),l=i.utils.convert(e.type),u=this.getInternalFormat(e.internalFormat,h,l,e.normalized,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,a,o):e.isData3DTexture?s.texStorage3D(s.TEXTURE_3D,r,u,n,a,o):e.isVideoTexture||s.texStorage2D(d,r,u,n,a),i.set(e,{textureGPU:c,glTextureType:d,glFormat:h,glType:l,glInternalFormat:u})}copyBufferToTexture(e,t){const{gl:s,backend:i}=this,{state:r}=i,{textureGPU:n,glTextureType:a,glFormat:o,glType:h}=i.get(t),{width:l,height:u}=t.source.data;s.bindBuffer(s.PIXEL_UNPACK_BUFFER,e),i.state.bindTexture(a,n),r.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,!1),r.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),s.texSubImage2D(a,0,0,0,l,u,o,h,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:a,glFormat:o,glType:h,glInternalFormat:l}=this.backend.get(e);if(!e.isRenderTargetTexture&&void 0!==n)if(this.backend.state.bindTexture(a,n),this.setTextureParameters(a,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!==o?s.compressedTexSubImage3D(s.TEXTURE_2D_ARRAY,t,0,0,0,n.width,n.height,r.depth,o,n.data):bt("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,o,h,n.data):null!==o?s.compressedTexSubImage2D(s.TEXTURE_2D,t,0,0,n.width,n.height,o,n.data):bt("WebGLBackend: Unsupported compressed texture format")}}else if(e.isCubeTexture){const n=t.images,a=e.mipmaps;for(let e=0;e<6;e++){const t=Hv(n[e]);s.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,0,0,i,r,o,h,t);for(let t=0;t<a.length;t++){const i=Hv(a[t].images[e]);s.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+e,t+1,0,0,i.width,i.height,o,h,i)}}}else if(e.isDataArrayTexture||e.isArrayTexture){const i=t.image;if(e.layerUpdates.size>0){const t=Mn(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,o,h,e)}e.clearLayerUpdates()}else s.texSubImage3D(s.TEXTURE_2D_ARRAY,0,0,0,0,i.width,i.height,i.depth,o,h,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,o,h,e.data)}else if(e.isVideoTexture)e.update(),s.texImage2D(a,0,l,o,h,t.image);else if(e.isHTMLTexture)"function"==typeof s.texElementImage2D&&s.texElementImage2D(s.TEXTURE_2D,0,s.RGBA,s.RGBA,s.UNSIGNED_BYTE,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=Hv(t);s.texSubImage2D(a,e,0,0,t.width,t.height,o,h,i)}else{const e=Hv(t.image);s.texSubImage2D(a,0,0,0,i,r,o,h,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:a,backend:o}=this,{state:h}=this.backend,{textureGPU:l,glTextureType:u,glType:c,glFormat:d}=o.get(t);let p,m,g,f,y,b,_,x,v;h.bindTexture(u,l);const T=e.isCompressedTexture?e.mipmaps[n]:e.image;if(null!==s)p=s.max.x-s.min.x,m=s.max.y-s.min.y,g=s.isBox3?s.max.z-s.min.z:1,f=s.min.x,y=s.min.y,b=s.isBox3?s.min.z:0;else{const t=Math.pow(2,-r);p=Math.floor(T.width*t),m=Math.floor(T.height*t),g=e.isDataArrayTexture||e.isArrayTexture?T.depth:e.isData3DTexture?Math.floor(T.depth*t):1,f=0,y=0,b=0}null!==i?(_=i.x,x=i.y,v=i.z):(_=0,x=0,v=0),h.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,t.flipY),h.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),h.pixelStorei(a.UNPACK_ALIGNMENT,t.unpackAlignment);const S=h.getParameter(a.UNPACK_ROW_LENGTH),w=h.getParameter(a.UNPACK_IMAGE_HEIGHT),M=h.getParameter(a.UNPACK_SKIP_PIXELS),N=h.getParameter(a.UNPACK_SKIP_ROWS),A=h.getParameter(a.UNPACK_SKIP_IMAGES);h.pixelStorei(a.UNPACK_ROW_LENGTH,T.width),h.pixelStorei(a.UNPACK_IMAGE_HEIGHT,T.height),h.pixelStorei(a.UNPACK_SKIP_PIXELS,f),h.pixelStorei(a.UNPACK_SKIP_ROWS,y),h.pixelStorei(a.UNPACK_SKIP_IMAGES,b);const E=e.isDataArrayTexture||e.isData3DTexture||t.isArrayTexture,R=t.isDataArrayTexture||t.isData3DTexture||t.isArrayTexture;if(e.isDepthTexture){const s=o.get(e),i=o.get(t),u=o.get(s.renderTarget),c=o.get(i.renderTarget),d=u.framebuffers[s.cacheKey],T=c.framebuffers[i.cacheKey];h.bindFramebuffer(a.READ_FRAMEBUFFER,d),h.bindFramebuffer(a.DRAW_FRAMEBUFFER,T);for(let e=0;e<g;e++)E&&(a.framebufferTextureLayer(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,s.textureGPU,r,b+e),a.framebufferTextureLayer(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,l,n,v+e)),a.blitFramebuffer(f,y,p,m,_,x,p,m,a.DEPTH_BUFFER_BIT,a.NEAREST);h.bindFramebuffer(a.READ_FRAMEBUFFER,null),h.bindFramebuffer(a.DRAW_FRAMEBUFFER,null)}else if(0!==r||e.isRenderTargetTexture||o.has(e)){const t=o.get(e);null===this._srcFramebuffer&&(this._srcFramebuffer=a.createFramebuffer()),null===this._dstFramebuffer&&(this._dstFramebuffer=a.createFramebuffer()),h.bindFramebuffer(a.READ_FRAMEBUFFER,this._srcFramebuffer),h.bindFramebuffer(a.DRAW_FRAMEBUFFER,this._dstFramebuffer);for(let e=0;e<g;e++)E?a.framebufferTextureLayer(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,t.textureGPU,r,b+e):a.framebufferTexture2D(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,t.textureGPU,r),R?a.framebufferTextureLayer(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,l,n,v+e):a.framebufferTexture2D(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,l,n),0!==r?a.blitFramebuffer(f,y,p,m,_,x,p,m,a.COLOR_BUFFER_BIT,a.NEAREST):R?a.copyTexSubImage3D(u,n,_,x,v+e,f,y,p,m):a.copyTexSubImage2D(u,n,_,x,f,y,p,m);h.bindFramebuffer(a.READ_FRAMEBUFFER,null),h.bindFramebuffer(a.DRAW_FRAMEBUFFER,null)}else R?e.isDataTexture||e.isData3DTexture?a.texSubImage3D(u,n,_,x,v,p,m,g,d,c,T.data):t.isCompressedArrayTexture?a.compressedTexSubImage3D(u,n,_,x,v,p,m,g,d,T.data):a.texSubImage3D(u,n,_,x,v,p,m,g,d,c,T):e.isDataTexture?a.texSubImage2D(a.TEXTURE_2D,n,_,x,p,m,d,c,T.data):e.isCompressedTexture?a.compressedTexSubImage2D(a.TEXTURE_2D,n,_,x,T.width,T.height,d,T.data):a.texSubImage2D(a.TEXTURE_2D,n,_,x,p,m,d,c,T);h.pixelStorei(a.UNPACK_ROW_LENGTH,S),h.pixelStorei(a.UNPACK_IMAGE_HEIGHT,w),h.pixelStorei(a.UNPACK_SKIP_PIXELS,M),h.pixelStorei(a.UNPACK_SKIP_ROWS,N),h.pixelStorei(a.UNPACK_SKIP_IMAGES,A),0===n&&t.generateMipmaps&&a.generateMipmap(u),h.unbindTexture()}copyFramebufferToTexture(e,t,s){const{gl:i}=this,{state:r}=this.backend,{textureGPU:n}=this.backend.get(e),{x:a,y:o,z:h,w:l}=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!==a||0!==o;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-o-l;i.blitFramebuffer(a,p,a+h,p+l,a,p,a+h,p+l,u,i.NEAREST),r.bindFramebuffer(i.READ_FRAMEBUFFER,s),r.bindTexture(i.TEXTURE_2D,n),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,a,p,h,l),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,h,l,0,0,h,l,u,i.NEAREST),i.deleteFramebuffer(e)}}else r.bindTexture(i.TEXTURE_2D,n),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,a,c-l-o,h,l),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:a,depthBuffer:o,stencilBuffer:h,width:l,height:u}=n;if(r.bindRenderbuffer(r.RENDERBUFFER,e),o&&!h){let t=r.DEPTH_COMPONENT24;if(!0===i){this.extensions.get("WEBGL_multisampled_render_to_texture").renderbufferStorageMultisampleEXT(r.RENDERBUFFER,n.samples,t,l,u)}else s>0?(a&&a.isDepthTexture&&a.type===r.FLOAT&&(t=r.DEPTH_COMPONENT32F),r.renderbufferStorageMultisample(r.RENDERBUFFER,s,t,l,u)):r.renderbufferStorage(r.RENDERBUFFER,t,l,u);r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.RENDERBUFFER,e)}else o&&h&&(s>0?r.renderbufferStorageMultisample(r.RENDERBUFFER,s,r.DEPTH24_STENCIL8,l,u):r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,l,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:a,gl:o}=this,{textureGPU:h,glFormat:l,glType:u}=this.backend.get(e),c=o.createFramebuffer();a.state.bindFramebuffer(o.READ_FRAMEBUFFER,c);const d=e.isCubeTexture?o.TEXTURE_CUBE_MAP_POSITIVE_X+n:o.TEXTURE_2D;o.framebufferTexture2D(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,d,h,0);const p=this._getTypedArrayType(u),m=i*r*this._getBytesPerTexel(u,l),g=o.createBuffer();o.bindBuffer(o.PIXEL_PACK_BUFFER,g),o.bufferData(o.PIXEL_PACK_BUFFER,m,o.STREAM_READ),o.readPixels(t,s,i,r,l,u,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),await a.utils._clientWaitAsync();const f=new p(m/p.BYTES_PER_ELEMENT);return o.bindBuffer(o.PIXEL_PACK_BUFFER,g),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,f),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),a.state.bindFramebuffer(o.READ_FRAMEBUFFER,null),o.deleteFramebuffer(c),f}_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 Hv(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 qv{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 Xv{constructor(e){this.backend=e,this.maxAnisotropy=null,this.maxUniformBlockSize=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}getUniformBufferLimit(){if(null!==this.maxUniformBlockSize)return this.maxUniformBlockSize;const e=this.backend.gl;return this.maxUniformBlockSize=e.getParameter(e.MAX_UNIFORM_BLOCK_SIZE),this.maxUniformBlockSize}}const Yv={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 Kv{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:a,index:o}=this;0!==o?s.drawElements(i,t,n,e):s.drawArrays(i,e,t),a.update(r,t,1)}renderInstances(e,t,s){const{gl:i,mode:r,type:n,index:a,object:o,info:h}=this;0!==s&&(0!==a?i.drawElementsInstanced(r,t,n,e,s):i.drawArraysInstanced(r,e,t,s),h.update(o,t,s))}renderMultiDraw(e,t,s){const{extensions:i,mode:r,object:n,info:a}=this;if(0===s)return;const o=i.get("WEBGL_multi_draw");if(null===o)for(let i=0;i<s;i++)this.render(e[i],t[i]);else{0!==this.index?o.multiDrawElementsWEBGL(r,t,0,this.type,e,0,s):o.multiDrawArraysWEBGL(r,e,0,t,0,s);let i=0;for(let e=0;e<s;e++)i+=t[e];a.update(n,i,1)}}}class Qv{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&&(bt(`TimestampQueryPool: No timestamp available for uid ${e}.`),t=0),t}hasTimestamp(e){return this.timestamps.has(e)}allocateQueriesForContext(){}async resolveQueriesAsync(){}dispose(){}}class Zv extends Qv{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 bt("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 xt(`WebGLTimestampQueryPool [${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){_t("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){_t("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 a=await r;this.timestamps.set(i,a),t[n]+=a}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 _t("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){_t("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 Jv extends Fv{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 qv(this),this.capabilities=new Xv(this),this.attributeUtils=new Uv(this),this.textureUtils=new Wv(this),this.bufferRenderer=new Kv(this),this.state=new kv(this),this.utils=new zv(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.extensions.get("EXT_clip_control"),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"),t.reversedDepthBuffer&&(this.extensions.has("EXT_clip_control")?e.reversedDepthBuffer=!0:(bt("WebGPURenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer."),e.reversedDepthBuffer=!1)),e.reversedDepthBuffer&&this.state.setReversedDepth(!0)}get coordinateSystem(){return ht}async getArrayBufferAsync(e,t=null,s=0,i=-1){return await this.attributeUtils.getArrayBufferAsync(e,t,s,i)}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&&bt("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 Zv(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)this.updateScissor(e);else{const{width:e,height:s}=this.getDrawingBufferSize();t.scissor(0,0,e,s)}this.initTimestampQuery(ct,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 a=e.textures;if(null!==a)for(let e=0;e<a.length;e++){const t=a[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)}if(r.scissor)this.updateScissor(r);else{const{width:e,height:t}=this.getDrawingBufferSize();s.scissor(0,0,e,t)}}this.prepareTimestampBuffer(ct,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 a=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),a++))}a<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)}updateScissor(e){const{state:t}=this,{x:s,y:i,width:r,height:n}=e.scissorValue;t.scissor(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:a,renderer:o}=this;if(null===i){i={textures:null,clearColorValue:this.getClearColor()}}let h=0;if(e&&(h|=a.COLOR_BUFFER_BIT),t&&(h|=a.DEPTH_BUFFER_BIT),s&&(h|=a.STENCIL_BUFFER_BIT),0!==h){let l;l=i.clearColorValue?i.clearColorValue:this.getClearColor();const u=o.getClearDepth(),c=o.getClearStencil();if(t&&this.state.setDepthMask(!0),null===i.textures)a.clearColor(l.r,l.g,l.b,l.a),a.clear(h);else{if(r&&this._setFramebuffer(i),e)for(let e=0;e<i.textures.length;e++)0===e?a.clearBufferfv(a.COLOR,e,[l.r,l.g,l.b,l.a]):a.clearBufferfv(a.COLOR,e,[0,0,0,1]);t&&s?a.clearBufferfi(a.DEPTH_STENCIL,0,u,c):t?a.clearBufferfv(a.DEPTH,0,[u]):s&&a.clearBufferiv(a.STENCIL,0,[c]),r&&n&&this._resolveRenderTarget(i)}}}beginCompute(e){const{state:t,gl:s}=this;t.bindFramebuffer(s.FRAMEBUFFER,null),this.initTimestampQuery(ut,this.getTimestampUID(e))}compute(e,t,s,i,r=null){const{state:n,gl:a}=this;!1===this.discard&&(n.enable(a.RASTERIZER_DISCARD),this.discard=!0);const{programGPU:o,transformBuffers:h,attributes:l}=this.get(i),u=this._getVaoKey(l),c=this.vaoCache[u];void 0===c?this.vaoCache[u]=this._createVao(l):n.setVertexState(c),n.useProgram(o),this._bindUniforms(s);const d=this._getTransformFeedback(h);a.bindTransformFeedback(a.TRANSFORM_FEEDBACK,d),a.beginTransformFeedback(a.POINTS),r=null!==r?r:t.count,Array.isArray(r)?(xt("WebGLBackend.compute(): The count parameter must be a single number, not an array."),r=r[0]):r&&"object"==typeof r&&r.isIndirectStorageBufferAttribute&&(xt("WebGLBackend.compute(): The count parameter must be a single number, not IndirectStorageBufferAttribute"),r=t.count),l[0].isStorageInstancedBufferAttribute?a.drawArraysInstanced(a.POINTS,0,1,r):a.drawArrays(a.POINTS,0,r),a.endTransformFeedback(),a.bindTransformFeedback(a.TRANSFORM_FEEDBACK,null);for(let e=0;e<h.length;e++){const t=h[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(ut,this.getTimestampUID(e)),this._currentContext&&this._setFramebuffer(this._currentContext)}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.isArrayTexture&&e.camera.isArrayCamera}_draw(e,t,s,i,r,n){if(e.isBatchedMesh)if(!1===this.hasFeature("WEBGL_multi_draw")){const{gl:s}=this,i=s.getUniformLocation(n,"nodeUniformDrawId"),r=e._multiDrawStarts,a=e._multiDrawCounts,o=e._multiDrawCount;for(let e=0;e<o;e++)s.uniform1ui(i,e),t.render(r[e],a[e])}else t.renderMultiDraw(e._multiDrawStarts,e._multiDrawCounts,e._multiDrawCount);else r>1?t.renderInstances(s,i,r):t.render(s,i)}draw(e){const{object:t,pipeline:s,material:i,context:r,hardwareClippingPlanes:n}=e,{programGPU:a}=this.get(s),{gl:o,state:h}=this,l=this.get(r),u=e.getDrawParameters();if(null===u)return;this._bindUniforms(e.getBindings());const c=t.isMesh&&t.matrixWorld.determinant()<0;h.setMaterial(i,c,n),null!==r.mrt&&null!==r.textures&&h.setMRTBlending(r.textures,r.mrt,i),h.useProgram(a);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 g=e.getIndex(),f=null!==g?this.get(g).bufferGPU:null;h.setVertexState(m,f);const y=l.lastOcclusionObject;if(y!==t&&void 0!==y){if(null!==y&&!0===y.occlusionTest&&(o.endQuery(o.ANY_SAMPLES_PASSED),l.occlusionQueryIndex++),!0===t.occlusionTest){const e=o.createQuery();o.beginQuery(o.ANY_SAMPLES_PASSED,e),l.occlusionQueries[l.occlusionQueryIndex]=e,l.occlusionQueryObjects[l.occlusionQueryIndex]=t}l.lastOcclusionObject=t}const b=this.bufferRenderer;t.isPoints?b.mode=o.POINTS:t.isLineSegments?b.mode=o.LINES:t.isLine?b.mode=o.LINE_STRIP:t.isLineLoop?b.mode=o.LINE_LOOP:!0===i.wireframe?(h.setLineWidth(i.wireframeLinewidth*this.renderer.getPixelRatio()),b.mode=o.LINES):b.mode=o.TRIANGLES;const{vertexCount:_,instanceCount:x}=u;let{firstVertex:v}=u;if(b.object=t,null!==g){v*=g.array.BYTES_PER_ELEMENT;const e=this.get(g);b.index=g.count,b.type=e.type}else b.index=0;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=o.createBuffer();e[0]=s,o.bindBuffer(o.UNIFORM_BUFFER,i),o.bufferData(o.UNIFORM_BUFFER,e,o.STATIC_DRAW),t.push(i)}s.indexesGPU=t}let n=0;e:for(const t of e.getBindings())for(const e of t.bindings){if(e===r)break e;(e.isUniformsGroup||e.isUniformBuffer)&&n++}const l=this.renderer.getPixelRatio(),u=this._currentContext.renderTarget,c=this._isRenderCameraDepthArray(this._currentContext),d=this._currentContext.activeCubeFace;if(c){const e=this.get(u.depthTexture);if(e.clearedRenderId!==this.renderer._nodes.nodeFrame.renderId){e.clearedRenderId=this.renderer._nodes.nodeFrame.renderId;const{stencilBuffer:t}=u;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=d,this._currentContext.activeCubeFace=d}}for(let r=0,u=i.length;r<u;r++){const u=i[r];if(t.layers.test(u.layers)){c&&(this.renderer._activeCubeFace=r,this._currentContext.activeCubeFace=r,this._setFramebuffer(this._currentContext));const i=u.viewport;if(void 0!==i){const t=i.x*l,s=i.y*l,r=i.width*l,n=i.height*l;h.viewport(Math.floor(t),Math.floor(e.context.height-n-s),Math.floor(r),Math.floor(n))}h.bindBufferBase(o.UNIFORM_BUFFER,n,s.indexesGPU[r]),this._draw(t,b,v,_,x,a)}this._currentContext.activeCubeFace=d,this.renderer._activeCubeFace=d}}else this._draw(t,b,v,_,x,a)}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 Cv(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,a=s.createProgram(),o=this.get(r).shaderGPU,h=this.get(n).shaderGPU;if(s.attachShader(a,o),s.attachShader(a,h),s.linkProgram(a),this.set(i,{programGPU:a,fragmentShader:o,vertexShader:h}),null!==t&&this.parallel){const r=new Promise(t=>{const r=this.parallel,n=()=>{s.getProgramParameter(a,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"),a=this._getShaderErrors(i,t,"fragment");_t("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(e,i.VALIDATE_STATUS)+"\n\nProgram Info Log: "+r+"\n"+n+"\n"+a)}else""!==r&&bt("WebGLProgram: Program Info Log:",r)}}_completeCompile(e,t){const{state:s,gl:i}=this,r=this.get(t),{programGPU:n,fragmentShader:a,vertexShader:o}=r;!1===i.getProgramParameter(n,i.LINK_STATUS)&&this._logProgramError(n,a,o),s.useProgram(n);const h=e.getBindings();this._setupBindings(h,n),this.set(t,{programGPU:n,pipeline: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,a=i.createProgram(),o=this.get(r).shaderGPU,h=this.get(n).shaderGPU,l=n.transforms,u=[],c=[];for(let e=0;e<l.length;e++){const t=l[e];u.push(t.varyingName),c.push(t.attributeNode)}i.attachShader(a,o),i.attachShader(a,h),i.transformFeedbackVaryings(a,u,i.SEPARATE_ATTRIBS),i.linkProgram(a),!1===i.getProgramParameter(a,i.LINK_STATUS)&&this._logProgramError(a,o,h),s.useProgram(a),this._setupBindings(t,a);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:a,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;for(const s of e.bindings){const e=this.get(s);if(s.isUniformsGroup||s.isUniformBuffer){const i=s.buffer;let{bufferGPU:r}=this.get(i);void 0===r?(r=t.createBuffer(),t.bindBuffer(t.UNIFORM_BUFFER,r),t.bufferData(t.UNIFORM_BUFFER,i.byteLength,t.DYNAMIC_DRAW),this.set(i,{bufferGPU:r})):t.bindBuffer(t.UNIFORM_BUFFER,r);const n=s.updateRanges;if(t.bindBuffer(t.UNIFORM_BUFFER,r),0===n.length)t.bufferData(t.UNIFORM_BUFFER,i,t.DYNAMIC_DRAW);else{const e=pt(i),s=e?1:i.BYTES_PER_ELEMENT;for(let r=0,a=n.length;r<a;r++){const a=n[r],o=a.start*s,h=a.count*s,l=o*(e?i.BYTES_PER_ELEMENT:1);t.bufferSubData(t.UNIFORM_BUFFER,l,i,o,h)}}e.bufferGPU=r,this.set(s,e)}else if(s.isSampledTexture){const{textureGPU:t,glTextureType:i}=this.get(s.texture);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=pt(i),s=e?1:i.BYTES_PER_ELEMENT;for(let n=0,a=r.length;n<a;n++){const a=r[n],o=a.start*s,h=a.count*s,l=o*(e?i.BYTES_PER_ELEMENT:1);t.bufferSubData(t.UNIFORM_BUFFER,l,i,o,h)}}}}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(Yv).filter(t=>Yv[t]===e),s=this.extensions;for(let e=0;e<t.length;e++)if(s.has(t[e]))return!0;return!1}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)}hasCompatibility(e){return e===dt||super.hasCompatibility(e)}initRenderTarget(e){const{gl:t,state:s}=this;this._setFramebuffer(e),s.bindFramebuffer(t.FRAMEBUFFER,null)}_setFramebuffer(e){const{gl:t,state:s}=this;let i=null;if(null!==e.textures){const r=e.renderTarget,n=this.get(r),{samples:a,depthBuffer:o,stencilBuffer:h}=r,l=!0===r.isCubeRenderTarget,u=!0===r.isRenderTarget3D,c=r.depth>1,d=!0===r.isXRRenderTarget,p=!0===d&&!0===r._hasExternalTextures;let m=n.msaaFrameBuffer,g=n.depthRenderbuffer;const f=this.extensions.get("WEBGL_multisampled_render_to_texture"),y=this.extensions.get("OVR_multiview2"),b=this._useMultisampledExtension(r),_=qy(e);let x;if(l?(n.cubeFramebuffers||(n.cubeFramebuffers={}),x=n.cubeFramebuffers[_]):d&&!1===p?x=this._xrFramebuffer:(n.framebuffers||(n.framebuffers={}),x=n.framebuffers[_]),void 0===x){x=t.createFramebuffer(),s.bindFramebuffer(t.FRAMEBUFFER,x);const i=e.textures,o=[];if(l){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],o=this.get(n);o.renderTarget=e.renderTarget,o.cacheKey=_;const h=t.COLOR_ATTACHMENT0+s;if(r.multiview)y.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,h,o.textureGPU,0,a,0,2);else if(u||c){const e=this.renderer._activeCubeFace,s=this.renderer._activeMipmapLevel;t.framebufferTextureLayer(t.FRAMEBUFFER,h,o.textureGPU,s,e)}else if(b)f.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,h,t.TEXTURE_2D,o.textureGPU,0,a);else{const e=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,h,t.TEXTURE_2D,o.textureGPU,e)}}}const d=h?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,o.push(h?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){o.push(h?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT);const s=this.get(e.depthTexture);if(s.renderTarget=e.renderTarget,s.cacheKey=_,r.multiview)y.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,d,s.textureGPU,0,a,0,2);else if(p&&b)f.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,d,t.TEXTURE_2D,s.textureGPU,0,a);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=o}else{if(this._isRenderCameraDepthArray(e)){s.bindFramebuffer(t.FRAMEBUFFER,x);const i=this.renderer._activeCubeFace,r=this.get(e.depthTexture),n=h?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,x);const i=this.get(e.textures[0]);r.multiview?y.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,i.textureGPU,0,a,0,2):b?f.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,i.textureGPU,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,i.textureGPU,0);const o=h?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(!0===r._autoAllocateDepthBuffer){const e=n.xrDepthRenderbuffer;t.bindRenderbuffer(t.RENDERBUFFER,e),t.framebufferRenderbuffer(t.FRAMEBUFFER,o,t.RENDERBUFFER,e)}else{const s=this.get(e.depthTexture);r.multiview?y.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,o,s.textureGPU,0,a,0,2):b?f.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,o,t.TEXTURE_2D,s.textureGPU,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,o,t.TEXTURE_2D,s.textureGPU,0)}}}if(a>0&&!1===b&&!r.multiview){if(void 0===m){const i=[];m=t.createFramebuffer(),s.bindFramebuffer(t.FRAMEBUFFER,m);const r=[],l=e.textures;for(let s=0;s<l.length;s++){r[s]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,r[s]),i.push(t.COLOR_ATTACHMENT0+s);const n=e.textures[s],o=this.get(n);t.renderbufferStorageMultisample(t.RENDERBUFFER,a,o.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,o&&void 0===g){g=t.createRenderbuffer(),this.textureUtils.setupRenderBufferStorage(g,e,a),n.depthRenderbuffer=g;const s=h?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;i.push(s)}n.invalidationArray=i}i=n.msaaFrameBuffer}else i=x;s.drawBuffers(e,x)}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,a;t.bindBuffer(t.ARRAY_BUFFER,r.bufferGPU),t.enableVertexAttribArray(s),!0===i.isInterleavedBufferAttribute?(n=i.data.stride*r.bytesPerElement,a=i.offset*r.bytesPerElement):(n=0,a=0),r.isInteger?t.vertexAttribIPointer(s,i.itemSize,r.type,n,a):t.vertexAttribPointer(s,i.itemSize,r.type,i.normalized,n,a),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;let i=0,r=0;for(const n of e)for(const e of n.bindings)if(e.isUniformsGroup||e.isUniformBuffer){const r=i++,n=s.getUniformBlockIndex(t,e.name);s.uniformBlockBinding(t,n,r)}else if(e.isSampledTexture){const i=r++,n=s.getUniformLocation(t,e.name);s.uniform1i(n,i)}}_bindUniforms(e){const{gl:t,state:s}=this;let i=0,r=0;for(const n of e)for(const e of n.bindings){const n=this.get(e);if(e.isUniformsGroup||e.isUniformBuffer){const e=i++;s.bindBufferBase(t.UNIFORM_BUFFER,e,n.bufferGPU)}else if(e.isSampledTexture){const e=r++;s.bindTexture(n.glTextureType,n.textureGPU,t.TEXTURE0+e)}}}_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 a=t.COLOR_BUFFER_BIT;i.resolveDepthBuffer&&(i.depthBuffer&&(a|=t.DEPTH_BUFFER_BIT),i.stencilBuffer&&i.resolveStencilBuffer&&(a|=t.STENCIL_BUFFER_BIT));const o=r.msaaFrameBuffer,h=r.msaaRenderbuffers,l=e.textures,u=l.length>1;if(s.bindFramebuffer(t.READ_FRAMEBUFFER,o),s.bindFramebuffer(t.DRAW_FRAMEBUFFER,n),u)for(let e=0;e<l.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<l.length;s++){if(u){const{textureGPU:e}=this.get(l[s]);t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,h[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,o=e.height-n-i;t.blitFramebuffer(s,o,s+r,o+n,s,o,s+r,o+n,a,t.NEAREST)}else t.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,a,t.NEAREST)}if(u)for(let e=0;e<l.length;e++){const{textureGPU:s}=this.get(l[e]);t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.RENDERBUFFER,h[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 eT="point-list",tT="line-list",sT="line-strip",iT="triangle-list",rT="undefined"!=typeof self&&self.GPUShaderStage?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},nT="never",aT="less",oT="equal",hT="less-equal",lT="greater",uT="not-equal",cT="greater-equal",dT="always",pT="store",mT="load",gT="clear",fT="ccw",yT="cw",bT="none",_T="back",xT="uint16",vT="uint32",TT="r8unorm",ST="r8snorm",wT="r8uint",MT="r8sint",NT="r16uint",AT="r16sint",ET="r16float",RT="rg8unorm",CT="rg8snorm",PT="rg8uint",BT="rg8sint",FT="r16unorm",LT="r16snorm",DT="r32uint",IT="r32sint",OT="r32float",UT="rg16uint",kT="rg16sint",zT="rg16float",VT="rgba8unorm",GT="rgba8unorm-srgb",jT="rgba8snorm",$T="rgba8uint",WT="rgba8sint",HT="bgra8unorm",qT="bgra8unorm-srgb",XT="rg16unorm",YT="rg16snorm",KT="rgb9e5ufloat",QT="rgb10a2unorm",ZT="rg11b10ufloat",JT="rg32uint",eS="rg32sint",tS="rg32float",sS="rgba16uint",iS="rgba16sint",rS="rgba16float",nS="rgba16unorm",aS="rgba16snorm",oS="rgba32uint",hS="rgba32sint",lS="rgba32float",uS="depth16unorm",cS="depth24plus",dS="depth24plus-stencil8",pS="depth32float",mS="depth32float-stencil8",gS="bc1-rgba-unorm",fS="bc1-rgba-unorm-srgb",yS="bc2-rgba-unorm",bS="bc2-rgba-unorm-srgb",_S="bc3-rgba-unorm",xS="bc3-rgba-unorm-srgb",vS="bc4-r-unorm",TS="bc4-r-snorm",SS="bc5-rg-unorm",wS="bc5-rg-snorm",MS="bc6h-rgb-ufloat",NS="bc6h-rgb-float",AS="bc7-rgba-unorm",ES="bc7-rgba-unorm-srgb",RS="etc2-rgb8unorm",CS="etc2-rgb8unorm-srgb",PS="etc2-rgb8a1unorm",BS="etc2-rgb8a1unorm-srgb",FS="etc2-rgba8unorm",LS="etc2-rgba8unorm-srgb",DS="eac-r11unorm",IS="eac-r11snorm",OS="eac-rg11unorm",US="eac-rg11snorm",kS="astc-4x4-unorm",zS="astc-4x4-unorm-srgb",VS="astc-5x4-unorm",GS="astc-5x4-unorm-srgb",jS="astc-5x5-unorm",$S="astc-5x5-unorm-srgb",WS="astc-6x5-unorm",HS="astc-6x5-unorm-srgb",qS="astc-6x6-unorm",XS="astc-6x6-unorm-srgb",YS="astc-8x5-unorm",KS="astc-8x5-unorm-srgb",QS="astc-8x6-unorm",ZS="astc-8x6-unorm-srgb",JS="astc-8x8-unorm",ew="astc-8x8-unorm-srgb",tw="astc-10x5-unorm",sw="astc-10x5-unorm-srgb",iw="astc-10x6-unorm",rw="astc-10x6-unorm-srgb",nw="astc-10x8-unorm",aw="astc-10x8-unorm-srgb",ow="astc-10x10-unorm",hw="astc-10x10-unorm-srgb",lw="astc-12x10-unorm",uw="astc-12x10-unorm-srgb",cw="astc-12x12-unorm",dw="astc-12x12-unorm-srgb",pw="clamp-to-edge",mw="repeat",gw="mirror-repeat",fw="linear",yw="nearest",bw="zero",_w="one",xw="src",vw="one-minus-src",Tw="src-alpha",Sw="one-minus-src-alpha",ww="dst",Mw="one-minus-dst",Nw="dst-alpha",Aw="one-minus-dst-alpha",Ew="src-alpha-saturated",Rw="constant",Cw="one-minus-constant",Pw="add",Bw="subtract",Fw="reverse-subtract",Lw="min",Dw="max",Iw=0,Ow=15,Uw="keep",kw="zero",zw="replace",Vw="invert",Gw="increment-clamp",jw="decrement-clamp",$w="increment-wrap",Ww="decrement-wrap",Hw="storage",qw="read-only-storage",Xw="write-only",Yw="read-only",Kw="read-write",Qw="non-filtering",Zw="comparison",Jw="float",eM="unfilterable-float",tM="depth",sM="sint",iM="uint",rM="2d",nM="3d",aM="2d",oM="2d-array",hM="cube",lM="3d",uM="all",cM="vertex",dM="instance",pM={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"},mM={"texture-compression-s3tc":"texture-compression-bc","texture-compression-etc1":"texture-compression-etc2"};class gM extends yv{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 fM extends uv{constructor(e,t){super(e,t?t.array:null),this._attribute=t,this.isStorageBuffer=!0}get attribute(){return this._attribute}}let yM=0;class bM extends fM{constructor(e,t){super("StorageBuffer_"+yM++,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:Kn,this.groupNode=t}get attribute(){return this.nodeUniform.value}get buffer(){return this.nodeUniform.value.array}}class _M extends xy{constructor(e){super(),this.device=e;this.mipmapSampler=e.createSampler({minFilter:fw}),this.flipYSampler=e.createSampler({minFilter:yw}),this.flipUniformBuffer=e.createBuffer({size:4,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),e.queue.writeBuffer(this.flipUniformBuffer,0,new Uint32Array([1])),this.noFlipUniformBuffer=e.createBuffer({size:4,usage:GPUBufferUsage.UNIFORM}),this.transferPipelines={},this.mipmapShaderModule=e.createShaderModule({label:"mipmap",code:"\nstruct VarysStruct {\n\t@builtin( position ) Position: vec4f,\n\t@location( 0 ) vTex : vec2f,\n\t@location( 1 ) @interpolate(flat, either) vBaseArrayLayer: u32,\n};\n\n@group( 0 ) @binding ( 2 )\nvar<uniform> flipY: u32;\n\n@vertex\nfn mainVS(\n\t\t@builtin( vertex_index ) vertexIndex : u32,\n\t\t@builtin( instance_index ) instanceIndex : u32 ) -> VarysStruct {\n\n\tvar Varys : VarysStruct;\n\n\tvar pos = array(\n\t\tvec2f( -1, -1 ),\n\t\tvec2f( -1, 3 ),\n\t\tvec2f( 3, -1 ),\n\t);\n\n\tlet p = pos[ vertexIndex ];\n\tlet mult = select( vec2f( 0.5, -0.5 ), vec2f( 0.5, 0.5 ), flipY != 0 );\n\tVarys.vTex = p * mult + vec2f( 0.5 );\n\tVarys.Position = vec4f( p, 0, 1 );\n\tVarys.vBaseArrayLayer = instanceIndex;\n\n\treturn Varys;\n\n}\n\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img2d : texture_2d<f32>;\n\n@fragment\nfn main_2d( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {\n\n\treturn textureSample( img2d, imgSampler, Varys.vTex );\n\n}\n\n@group( 0 ) @binding( 1 )\nvar img2dArray : texture_2d_array<f32>;\n\n@fragment\nfn main_2d_array( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {\n\n\treturn textureSample( img2dArray, imgSampler, Varys.vTex, Varys.vBaseArrayLayer );\n\n}\n\nconst faceMat = array(\n mat3x3f( 0, 0, -2, 0, -2, 0, 1, 1, 1 ), // pos-x\n mat3x3f( 0, 0, 2, 0, -2, 0, -1, 1, -1 ), // neg-x\n mat3x3f( 2, 0, 0, 0, 0, 2, -1, 1, -1 ), // pos-y\n mat3x3f( 2, 0, 0, 0, 0, -2, -1, -1, 1 ), // neg-y\n mat3x3f( 2, 0, 0, 0, -2, 0, -1, 1, 1 ), // pos-z\n mat3x3f( -2, 0, 0, 0, -2, 0, 1, 1, -1 ), // neg-z\n);\n\n@group( 0 ) @binding( 1 )\nvar imgCube : texture_cube<f32>;\n\n@fragment\nfn main_cube( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {\n\n\treturn textureSample( imgCube, imgSampler, faceMat[ Varys.vBaseArrayLayer ] * vec3f( fract( Varys.vTex ), 1 ) );\n\n}\n"})}getTransferPipeline(e,t){const s=`${e}-${t=t||"2d-array"}`;let i=this.transferPipelines[s];return void 0===i&&(i=this.device.createRenderPipeline({label:`mipmap-${e}-${t}`,vertex:{module:this.mipmapShaderModule},fragment:{module:this.mipmapShaderModule,entryPoint:`main_${t.replace("-","_")}`,targets:[{format:e}]},layout:"auto"}),this.transferPipelines[s]=i),i}flipY(e,t,s=0){const i=t.format,{width:r,height:n}=t.size,a=this.device.createTexture({size:{width:r,height:n},format:i,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),o=this.getTransferPipeline(i,e.textureBindingViewDimension),h=this.getTransferPipeline(i,a.textureBindingViewDimension),l=this.device.createCommandEncoder({}),u=(e,t,s,i,r,n)=>{const a=e.getBindGroupLayout(0),o=this.device.createBindGroup({layout:a,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:t.createView({dimension:t.textureBindingViewDimension||"2d-array",baseMipLevel:0,mipLevelCount:1})},{binding:2,resource:{buffer:n?this.flipUniformBuffer:this.noFlipUniformBuffer}}]}),h=l.beginRenderPass({colorAttachments:[{view:i.createView({dimension:"2d",baseMipLevel:0,mipLevelCount:1,baseArrayLayer:r,arrayLayerCount:1}),loadOp:gT,storeOp:pT}]});h.setPipeline(e),h.setBindGroup(0,o),h.draw(3,1,0,s),h.end()};u(o,e,s,a,0,!1),u(h,a,0,e,s,!0),this.device.queue.submit([l.finish()]),a.destroy()}generateMipmaps(e,t=null){const s=this.get(e),i=s.layers||this._mipmapCreateBundles(e),r=t||this.device.createCommandEncoder({label:"mipmapEncoder"});this._mipmapRunBundles(r,i),null===t&&this.device.queue.submit([r.finish()]),s.layers=i}_mipmapCreateBundles(e){const t=e.textureBindingViewDimension||"2d-array",s=this.getTransferPipeline(e.format,t),i=s.getBindGroupLayout(0),r=[];for(let n=1;n<e.mipLevelCount;n++)for(let a=0;a<e.depthOrArrayLayers;a++){const o=this.device.createBindGroup({layout:i,entries:[{binding:0,resource:this.mipmapSampler},{binding:1,resource:e.createView({dimension:t,baseMipLevel:n-1,mipLevelCount:1})},{binding:2,resource:{buffer:this.noFlipUniformBuffer}}]}),h={colorAttachments:[{view:e.createView({dimension:"2d",baseMipLevel:n,mipLevelCount:1,baseArrayLayer:a,arrayLayerCount:1}),loadOp:gT,storeOp:pT}]},l=this.device.createRenderBundleEncoder({colorFormats:[e.format]});l.setPipeline(s),l.setBindGroup(0,o),l.draw(3,1,0,a),r.push({renderBundles:[l.finish()],passDescriptor:h})}return r}_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 xM={[Ze]:"never",[Je]:"less",[et]:"equal",[tt]:"less-equal",[st]:"greater",[rt]:"greater-equal",[nt]:"always",[it]:"not-equal"},vM=[0,1,3,2,4,5];class TM{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};e.isDepthTexture&&null===e.compareFunction&&(r.magFilter=yw,r.minFilter=yw,r.mipmapFilter=yw),r.magFilter===fw&&r.minFilter===fw&&r.mipmapFilter===fw&&(r.maxAnisotropy=e.anisotropy),e.isDepthTexture&&null!==e.compareFunction&&t.hasCompatibility(dt)&&(r.compare=xM[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=SM(e,this.backend.device);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:a,levels:o}=t;e.isFramebufferTexture&&(t.renderTarget?t.format=this.backend.utils.getCurrentColorFormat(t.renderTarget):t.format=this.backend.utils.getPreferredCanvasFormat());const h=this._getDimension(e),l=e.internalFormat||t.format||SM(e,s.device);i.format=l;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&&l!==KT&&(p|=GPUTextureUsage.RENDER_ATTACHMENT);const m={label:e.name,size:{width:r,height:n,depthOrArrayLayers:a},mipLevelCount:o,sampleCount:c,dimension:h,format:l,usage:p};if(void 0===l)return bt("WebGPURenderer: Texture format not supported."),void this.createDefaultTexture(e);e.isCubeTexture&&(m.textureBindingViewDimension=hM);try{i.texture=s.device.createTexture(m)}catch(t){return bt("WebGPURenderer: Failed to create texture with descriptor:",m),void this.createDefaultTexture(e)}if(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);this._generateMipmaps(s.texture,t)}getColorBuffer(){const e=this.backend,t=e.renderer.getCanvasTarget(),{width:s,height:i}=e.getDrawingBufferSize(),r=e.renderer.currentSamples,n=t.colorTexture,a=e.get(n);if(n.width===s&&n.height===i&&n.samples===r)return a.texture;let o=a.texture;return o&&o.destroy(),o=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,a.texture=o,o}getDepthBuffer(e=!0,t=!1){const s=this.backend,i=s.renderer.getCanvasTarget(),{width:r,height:n}=s.getDrawingBufferSize(),a=s.renderer.currentSamples,o=i.depthTexture;if(o.width===r&&o.height===n&&o.samples===a&&o.depth===e&&o.stencil===t)return s.get(o).texture;const h=s.get(o).texture;let l,u;if(t?(l=ae,u=!0===s.renderer.reversedDepthBuffer?Y:J):e&&(l=ne,u=!0===s.renderer.reversedDepthBuffer?Y:X),void 0!==h){if(o.image.width===r&&o.image.height===n&&o.format===l&&o.type===u&&o.samples===a)return h;this.destroyTexture(o)}return o.name="depthBuffer",o.format=l,o.type=u,o.image.width=r,o.image.height=n,o.samples=a,this.createTexture(o,{width:r,height:n}),s.get(o).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)if(e.layerUpdates&&e.layerUpdates.size>0){for(const i of e.layerUpdates)this._copyBufferToTexture(t.image,s.texture,r,i,e.flipY,i);e.clearLayerUpdates()}else 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(e.isHTMLTexture){const t=this.backend.device,i=this.backend.renderer.domElement,n=e.image;if("function"!=typeof t.queue.copyElementImageToTexture)return;if(!s.hasPaintCallback)return s.hasPaintCallback=!0,void i.requestPaint();const a=r.size.width,o=r.size.height;t.queue.copyElementImageToTexture(n,a,o,{texture:s.texture}),e.flipY&&this._flipY(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 a=this.backend.device,o=this.backend.get(e),h=o.texture,l=o.textureDescriptorGPU.format,u=this._getBytesPerTexel(l);let c=i*u;c=256*Math.ceil(c/256);const d=a.createBuffer({size:(r-1)*c+i*u,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),p=a.createCommandEncoder();p.copyTextureToBuffer({texture:h,origin:{x:t,y:s,z:n}},{buffer:d,bytesPerRow:c},{width:i,height:r});const m=this._getTypedArrayType(l);a.queue.submit([p.finish()]),await d.mapAsync(GPUMapMode.READ);const g=d.getMappedRange().slice();return d.destroy(),new m(g)}dispose(){this._samplerCache.clear()}_getDefaultTextureGPU(e){let t=this.defaultTexture[e];if(void 0===t){const s=new ts;s.minFilter=O,s.magFilter=O,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 Br;s.minFilter=O,s.magFilter=O,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 a=i[n],o=!0===e.flipY?vM[n]:n;a.isDataTexture?this._copyBufferToTexture(a.image,t,s,o,e.flipY):this._copyImageToTexture(a,t,s,o,e.flipY,e.premultiplyAlpha);for(let i=0;i<r.length;i++){const a=r[i].images[n];a.isDataTexture?this._copyBufferToTexture(a.image,t,s,o,e.flipY,0,i+1):this._copyImageToTexture(a,t,s,o,e.flipY,e.premultiplyAlpha,i+1)}}}_copyImageToTexture(e,t,s,i,r,n,a=0){const o=this.backend.device,h=a>0?e.width:s.size.width,l=a>0?e.height:s.size.height;try{o.queue.copyExternalImageToTexture({source:e,flipY:r},{texture:t,mipLevel:a,origin:{x:0,y:0,z:i},premultipliedAlpha:n},{width:h,height:l,depthOrArrayLayers:1})}catch(e){}}_getPassUtils(){let e=this._passUtils;return null===e&&(this._passUtils=e=new _M(this.backend.device)),e}_generateMipmaps(e,t=null){this._getPassUtils().generateMipmaps(e,t)}_flipY(e,t,s=0){this._getPassUtils().flipY(e,t,s)}_copyBufferToTexture(e,t,s,i,r,n=0,a=0){const o=this.backend.device,h=e.data,l=this._getBytesPerTexel(s.format),u=e.width*l;o.queue.writeTexture({texture:t,mipLevel:a,origin:{x:0,y:0,z:i}},h,{offset:e.width*e.height*l*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 a=0;a<e.length;a++){const o=e[a],h=o.width,l=o.height,u=n?s.size.depthOrArrayLayers:1,c=Math.ceil(h/r.width)*r.byteLength,d=c*Math.ceil(l/r.height);for(let e=0;e<u;e++)i.queue.writeTexture({texture:t,mipLevel:a,origin:{x:0,y:0,z:e}},o.data,{offset:e*d,bytesPerRow:c,rowsPerImage:Math.ceil(l/r.height)},{width:Math.ceil(h/r.width)*r.width,height:Math.ceil(l/r.height)*r.height,depthOrArrayLayers:1})}}_getBlockData(e){return e===gS||e===fS?{byteLength:8,width:4,height:4}:e===yS||e===bS||e===_S||e===xS?{byteLength:16,width:4,height:4}:e===vS||e===TS?{byteLength:8,width:4,height:4}:e===SS||e===wS||e===MS||e===NS||e===AS||e===ES?{byteLength:16,width:4,height:4}:e===RS||e===CS||e===PS||e===BS?{byteLength:8,width:4,height:4}:e===FS||e===LS?{byteLength:16,width:4,height:4}:e===DS||e===IS?{byteLength:8,width:4,height:4}:e===OS||e===US||e===kS||e===zS?{byteLength:16,width:4,height:4}:e===VS||e===GS?{byteLength:16,width:5,height:4}:e===jS||e===$S?{byteLength:16,width:5,height:5}:e===WS||e===HS?{byteLength:16,width:6,height:5}:e===qS||e===XS?{byteLength:16,width:6,height:6}:e===YS||e===KS?{byteLength:16,width:8,height:5}:e===QS||e===ZS?{byteLength:16,width:8,height:6}:e===JS||e===ew?{byteLength:16,width:8,height:8}:e===tw||e===sw?{byteLength:16,width:10,height:5}:e===iw||e===rw?{byteLength:16,width:10,height:6}:e===nw||e===aw?{byteLength:16,width:10,height:8}:e===ow||e===hw?{byteLength:16,width:10,height:10}:e===lw||e===uw?{byteLength:16,width:12,height:10}:e===cw||e===dw?{byteLength:16,width:12,height:12}:void 0}_convertAddressMode(e){let t=pw;return e===L?t=mw:e===I&&(t=gw),t}_convertFilterMode(e){let t=fw;return e!==O&&1004!==e&&e!==k||(t=yw),t}_getBytesPerTexel(e){return e===TT||e===ST||e===wT||e===MT?1:e===NT||e===AT||e===ET||e===RT||e===CT||e===PT||e===BT||e===FT||e===LT?2:e===DT||e===IT||e===OT||e===UT||e===kT||e===zT||e===VT||e===GT||e===jT||e===$T||e===WT||e===HT||e===qT||e===XT||e===YT||e===KT||e===QT||e===ZT||e===pS||e===cS||e===dS||e===mS?4:e===JT||e===eS||e===tS||e===sS||e===iS||e===rS||e===nS||e===aS?8:e===oS||e===hS||e===lS?16:void 0}_getTypedArrayType(e){return e===wT?Uint8Array:e===MT?Int8Array:e===TT?Uint8Array:e===ST?Int8Array:e===PT?Uint8Array:e===BT?Int8Array:e===RT?Uint8Array:e===CT?Int8Array:e===$T?Uint8Array:e===WT?Int8Array:e===VT||e===GT?Uint8Array:e===jT?Int8Array:e===NT?Uint16Array:e===AT?Int16Array:e===UT?Uint16Array:e===kT?Int16Array:e===sS?Uint16Array:e===iS?Int16Array:e===ET||e===zT||e===rS||e===FT?Uint16Array:e===LT?Int16Array:e===XT?Uint16Array:e===YT?Int16Array:e===nS?Uint16Array:e===aS?Int16Array:e===DT?Uint32Array:e===IT?Int32Array:e===OT?Float32Array:e===JT?Uint32Array:e===eS?Int32Array:e===tS?Float32Array:e===oS?Uint32Array:e===hS?Int32Array:e===lS?Float32Array:e===HT||e===qT?Uint8Array:e===QT||e===KT||e===ZT?Uint32Array:e===pS?Float32Array:e===cS||e===dS?Uint32Array:e===mS?Float32Array:void 0}_getDimension(e){let t;return t=e.is3DTexture||e.isData3DTexture?nM:rM,t}}function SM(e,t){const s=e.format,i=e.type,r=e.normalized,n=e.colorSpace,a=Wt.getTransfer(n);let o,h=!1;if(r&&(h=t.features.has(pM.TextureFormatsTier1),!1===h&&bt("WebGPURenderer: Unable to use normalized textures without texture-formats-tier1 feature.")),!0===e.isCompressedTexture||!0===e.isCompressedArrayTexture)switch(s){case de:case pe:o=a===Ke?fS:gS;break;case me:o=a===Ke?bS:yS;break;case ge:o=a===Ke?xS:_S;break;case Ge:o=vS;break;case je:o=TS;break;case $e:o=SS;break;case We:o=wS;break;case Ve:o=a===Ke?ES:AS;break;case ve:case xe:o=a===Ke?CS:RS;break;case Te:o=a===Ke?LS:FS;break;case Se:o=DS;break;case we:o=IS;break;case Me:o=OS;break;case Ne:o=US;break;case Ae:o=a===Ke?zS:kS;break;case Ee:o=a===Ke?GS:VS;break;case Re:o=a===Ke?$S:jS;break;case Ce:o=a===Ke?HS:WS;break;case Pe:o=a===Ke?XS:qS;break;case Be:o=a===Ke?KS:YS;break;case Fe:o=a===Ke?ZS:QS;break;case Le:o=a===Ke?ew:JS;break;case De:o=a===Ke?sw:tw;break;case Ie:o=a===Ke?rw:iw;break;case Oe:o=a===Ke?aw:nw;break;case Ue:o=a===Ke?hw:ow;break;case ke:o=a===Ke?uw:lw;break;case ze:o=a===Ke?dw:cw;break;case re:o=a===Ke?GT:VT;break;default:_t("WebGPURenderer: Unsupported texture format.",s)}else switch(s){case re:switch(i){case $:o=jT;break;case W:o=h?aS:iS;break;case H:o=h?nS:sS;break;case X:o=oS;break;case q:o=hS;break;case j:o=a===Ke?GT:VT;break;case K:o=rS;break;case Y:o=lS;break;default:_t("WebGPURenderer: Unsupported texture type with RGBAFormat.",i)}break;case ie:switch(i){case ee:o=KT;break;case te:o=ZT;break;default:_t("WebGPURenderer: Unsupported texture type with RGBFormat.",i)}break;case oe:switch(i){case $:o=ST;break;case W:o=h?LT:AT;break;case H:o=h?FT:NT;break;case X:o=DT;break;case q:o=IT;break;case j:o=TT;break;case K:o=ET;break;case Y:o=OT;break;default:_t("WebGPURenderer: Unsupported texture type with RedFormat.",i)}break;case le:switch(i){case $:o=CT;break;case W:o=h?YT:kT;break;case H:o=h?XT:UT;break;case X:o=JT;break;case q:o=eS;break;case j:o=RT;break;case K:o=zT;break;case Y:o=tS;break;default:_t("WebGPURenderer: Unsupported texture type with RGFormat.",i)}break;case ne:switch(i){case H:o=uS;break;case X:o=cS;break;case Y:o=pS;break;default:_t("WebGPURenderer: Unsupported texture type with DepthFormat.",i)}break;case ae:switch(i){case J:o=dS;break;case Y:t&&!1===t.features.has(pM.Depth32FloatStencil8)&&_t('WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.'),o=mS;break;default:_t("WebGPURenderer: Unsupported texture type with DepthStencilFormat.",i)}break;case he:switch(i){case q:o=IT;break;case X:o=DT;break;default:_t("WebGPURenderer: Unsupported texture type with RedIntegerFormat.",i)}break;case ue:switch(i){case q:o=eS;break;case X:o=JT;break;default:_t("WebGPURenderer: Unsupported texture type with RGIntegerFormat.",i)}break;case ce:switch(i){case q:o=hS;break;case X:o=oS;break;default:_t("WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.",i)}break;default:_t("WebGPURenderer: Unsupported texture format.",s)}return o}const wM=/^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,MM=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,NM={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 AM extends wx{constructor(e){const{type:t,inputs:s,name:i,inputsCode:r,blockCode:n,outputType:a}=(e=>{const t=(e=e.trim()).match(wM);if(null!==t&&4===t.length){const s=t[2],i=[];let r=null;for(;null!==(r=MM.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=NM[r]),n.push(new ux(r,t))}const a=e.substring(t[0].length),o=t[3]||"void",h=void 0!==t[1]?t[1]:"";return{type:NM[o]||o,inputs:n,name:h,inputsCode:s,blockCode:a,outputType:o}}throw new Error("FunctionNode: Function is not a WGSL code.")})(e);super(t,s,i),this.inputsCode=r,this.blockCode=n,this.outputType=a}getCode(e=this.name){const t="void"!==this.outputType?"-> "+this.outputType:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class EM extends Sx{parseFunction(e){return new AM(e)}}const RM={[Xn]:"read",[Yn]:"write",[Kn]:"read_write"},CM={[L]:"repeat",[D]:"clamp",[I]:"mirror"},PM={vertex:rT.VERTEX,fragment:rT.FRAGMENT,compute:rT.COMPUTE},BM={instance:!0,swizzleAssign:!1,storageBuffer:!0},FM={"^^":"tsl_xor"},LM={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>"},DM={},IM={tsl_xor:new Pb("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new Pb("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new Pb("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new Pb("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new Pb("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new Pb("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new Pb("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new Pb("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 Pb("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 Pb("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new Pb("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 Pb("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),biquadraticTexture:new Pb("\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"),biquadraticTextureArray:new Pb("\nfn tsl_biquadraticTexture_array( map : texture_2d_array<f32>, coord : vec2f, iRes : vec2u, layer : u32, 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, layer, level );\n\tlet rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, layer, level );\n\tlet rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, layer, level );\n\tlet rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, layer, level );\n\n\treturn mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );\n\n}\n")},OM={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 UM="";!0!==("undefined"!=typeof navigator&&/Firefox|Deno/g.test(navigator.userAgent))&&(UM+="diagnostic( off, derivative_uniformity );\n");class kM extends hx{constructor(e,t){super(e,t,new EM),this.uniformGroups={},this.uniformGroupsBindings={},this.builtins={},this.directives={},this.scopedArrays=new Map,this.allowEarlyReturns=!0,this.allowGlobalVariables=!0}_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)?r?n?`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${r}, ${i}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${r}, ${i} )`:n?`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,s,n,i,r):this.generateTextureLod(e,t,s,r,n,i)}generateWrapFunction(e){const t=`tsl_coord_${CM[e.wrapS]}S_${CM[e.wrapT]}_${e.is3DTexture||e.isData3DTexture?"3d":"2d"}T`;let s=DM[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 a=(e,t)=>{e===L?(i.push(IM.repeatWrapping_float),n+=`\t\ttsl_repeatWrapping_float( coord.${t} )`):e===D?(i.push(IM.clampWrapping_float),n+=`\t\ttsl_clampWrapping_float( coord.${t} )`):e===I?(i.push(IM.mirrorWrapping_float),n+=`\t\ttsl_mirrorWrapping_float( coord.${t} )`):(n+=`\t\tcoord.${t}`,bt(`WebGPURenderer: Unsupported texture wrap type "${e}" for vertex shader.`))};a(e.wrapS,"x"),n+=",\n",a(e.wrapT,"y"),(e.is3DTexture||e.isData3DTexture)&&(n+=",\n",a(e.wrapR,"z")),n+="\n\t);\n\n}\n",DM[t]=s=new Pb(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.cache);void 0===i.dimensionsSnippet&&(i.dimensionsSnippet={});let r=i.dimensionsSnippet[s];if(void 0===i.dimensionsSnippet[s]){let n,a;const{primarySamples:o}=this.renderer.backend.utils.getTextureSampleData(e),h=o>1;a=e.is3DTexture||e.isData3DTexture?"vec3<u32>":"vec2<u32>",n=h||e.isStorageTexture?t:`${t}${s?`, u32( ${s} )`:""}`,r=new tu(new Du(`textureDimensions( ${n} )`,a)),i.dimensionsSnippet[s]=r,(e.isArrayTexture||e.isDataArrayTexture||e.is3DTexture||e.isData3DTexture)&&(i.arrayLayerCount=new tu(new Du(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(i.cubeFaceCount=new tu(new Du("6u","u32")))}return r.build(this)}generateFilteredTexture(e,t,s,i,r="0u",n){const a=this.generateWrapFunction(e),o=this.generateTextureDimension(e,t,r);return i&&(s=`${s} + vec2<f32>(${i}) / ${o}`),n?(this._include("biquadraticTextureArray"),`tsl_biquadraticTexture_array( ${t}, ${a}( ${s} ), ${o}, u32( ${n} ), u32( ${r} ) )`):(this._include("biquadraticTexture"),`tsl_biquadraticTexture( ${t}, ${a}( ${s} ), ${o}, u32( ${r} ) )`)}generateTextureLod(e,t,s,i,r,n="0u"){if(!0===e.isCubeTexture){r&&(s=`${s} + vec3<f32>(${r})`);return`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${e.isDepthTexture?"u32":"f32"}( ${n} ) )`}const a=this.generateWrapFunction(e),o=this.generateTextureDimension(e,t,n),h=e.is3DTexture||e.isData3DTexture?"vec3":"vec2";r&&(s=`${s} + ${h}<f32>(${r}) / ${h}<f32>( ${o} )`);return s=`${h}<u32>( clamp( floor( ${a}( ${s} ) * ${h}<f32>( ${o} ) ), ${`${h}<f32>( 0 )`}, ${`${h}<f32>( ${o} - ${"vec3"===h?"vec3<u32>( 1, 1, 1 )":"vec2<u32>( 1, 1 )"} )`} ) )`,this.generateTextureLoad(e,t,s,n,i,null)}generateStorageTextureLoad(e,t,s,i,r,n){let a;return n&&(s=`${s} + ${n}`),a=r?`textureLoad( ${t}, ${s}, ${r} )`:`textureLoad( ${t}, ${s} )`,a}generateTextureLoad(e,t,s,i,r,n){let a;return null===i&&(i="0u"),n&&(s=`${s} + ${n}`),r?a=`textureLoad( ${t}, ${s}, ${r}, u32( ${i} ) )`:(a=`textureLoad( ${t}, ${s}, u32( ${i} ) )`,this.renderer.backend.compatibilityMode&&e.isDepthTexture&&(a+=".x")),a}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&&this.renderer.hasCompatibility(dt)}isUnfilterable(e){return"float"!==this.getComponentTypeFromTexture(e)||!this.isAvailable("float32Filterable")&&e.type===Y||!1===this.isSampleCompare(e)&&e.minFilter===O&&e.magFilter===O||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1}generateTexture(e,t,s,i,r,n=this.shaderStage){let a=null;return a=this.isUnfilterable(e)?this.generateTextureLod(e,t,s,i,r,"0",n):this._generateTextureSample(e,t,s,i,r,n),a}generateTextureGrad(e,t,s,i,r,n,a=this.shaderStage){if("fragment"===a)return r?n?`textureSampleGrad( ${t}, ${t}_sampler, ${s}, ${r}, ${i[0]}, ${i[1]}, ${n} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${s}, ${r}, ${i[0]}, ${i[1]} )`:n?`textureSampleGrad( ${t}, ${t}_sampler, ${s}, ${i[0]}, ${i[1]}, ${n} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${s}, ${i[0]}, ${i[1]} )`;_t(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${a} shader.`)}generateTextureCompare(e,t,s,i,r,n,a=this.shaderStage){if("fragment"===a)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} )`;_t(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${a} shader.`)}generateTextureLevel(e,t,s,i,r,n){return!1===this.isUnfilterable(e)?r?n?`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${r}, ${i}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${r}, ${i} )`:n?`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,s,n,i,r):this.generateTextureLod(e,t,s,r,n,i)}generateTextureBias(e,t,s,i,r,n,a=this.shaderStage){if("fragment"===a)return r?n?`textureSampleBias( ${t}, ${t}_sampler, ${s}, ${r}, ${i}, ${n} )`:`textureSampleBias( ${t}, ${t}_sampler, ${s}, ${r}, ${i} )`:n?`textureSampleBias( ${t}, ${t}_sampler, ${s}, ${i}, ${n} )`:`textureSampleBias( ${t}, ${t}_sampler, ${s}, ${i} )`;_t(`WebGPURenderer: THREE.TextureNode.biasNode does not support ${a} 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=FM[e];return void 0!==t?(this._include(t),t):null}getNodeAccess(e,t){return"compute"!==t?!0===e.isAtomic?(bt("WebGPURenderer: Atomic operations are only supported in compute shaders."),Kn):Xn:e.access}getStorageAccess(e,t){return RM[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 a;const o=e.groupNode,h=o.name,l=this.getBindGroupArray(h,s);if("texture"===t||"cubeTexture"===t||"cubeDepthTexture"===t||"storageTexture"===t||"texture3D"===t){let i=null;const n=this.getNodeAccess(e,s);"texture"===t||"storageTexture"===t?i=!0===e.value.is3DTexture?new Tv(r.name,r.node,o,n):new xv(r.name,r.node,o,n):"cubeTexture"===t||"cubeDepthTexture"===t?i=new vv(r.name,r.node,o,n):"texture3D"===t&&(i=new Tv(r.name,r.node,o,n)),i.store=!0===e.isStorageTextureNode,i.mipLevel=i.store?e.mipLevel:0,i.setVisibility(PM[s]);if(!0===e.value.isCubeTexture||!1===this.isUnfilterable(e.value)&&!1===i.store){const e=new gM(`${r.name}_sampler`,r.node,o);e.setVisibility(PM[s]),l.push(e,i),a=[e,i]}else l.push(i),a=[i]}else if("buffer"===t||"storageBuffer"===t||"indirectStorageBuffer"===t){const n=this.getSharedDataFromNode(e);let h=n.buffer;if(void 0===h){h=new("buffer"===t?pv:bM)(e,o),n.buffer=h}h.setVisibility(h.getVisibility()|PM[s]),l.push(h),a=h,r.name=i||"NodeBuffer_"+r.id}else{let e=this.uniformGroups[h];void 0===e&&(e=new fv(h,o),e.setVisibility(rT.VERTEX|rT.FRAGMENT|rT.COMPUTE),this.uniformGroups[h]=e),-1===l.indexOf(e)&&l.push(e),a=this.getNodeUniform(r,t);const s=a.name,i=e.uniforms.some(e=>e.name===s);i||e.addUniform(a)}n.uniformGPU=a}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,i=""){let r=`var${i} ${t} : `;return r+=null!==s?this.generateArrayDeclaration(e,s):this.getType(e),r}getVars(e,t=!1){let s="";t&&(s="<private>");const i=[],r=this.vars[e];if(void 0!==r)for(const e of r)i.push(`${this.getVar(e.type,e.name,e.count,s)};`);return t?i.join("\n"):`\n\t${i.join("\n\t")}\n`}getVaryings(e){const t=[];if("vertex"===e&&this.getBuiltin("position","builtinClipSpace","vec4<f32>","vertex"),"vertex"===e||"fragment"===e){const s=this.varyings,i=this.vars[e];let r=0;for(let n=0;n<s.length;n++){const a=s[n];if(a.needsInterpolation){let e=`@location( ${r++} )`;if(a.interpolationType){const t=null!==a.interpolationSampling?`, ${a.interpolationSampling} )`:" )";e+=` @interpolate( ${a.interpolationType}${t}`}else/^(int|uint|ivec|uvec)/.test(a.type)&&(e+=" @interpolate(flat, either)");t.push(`${e} ${a.name} : ${this.getType(a.type)}`)}else"vertex"===e&&!1===i.includes(a)&&i.push(a)}}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.renderer.backend,s=this.uniforms[e],i=[],r=[],n=[],a={};for(const n of s){const s=n.groupNode.name,o=this.bindingsIndexes[s];if("texture"===n.type||"cubeTexture"===n.type||"cubeDepthTexture"===n.type||"storageTexture"===n.type||"texture3D"===n.type){const s=n.node.value;let r;(!0===s.isCubeTexture||!1===this.isUnfilterable(s)&&!0!==n.node.isStorageTextureNode)&&(this.isSampleCompare(s)?i.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${n.name}_sampler : sampler_comparison;`):i.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${n.name}_sampler : sampler;`));let a="";const{primarySamples:h}=t.utils.getTextureSampleData(s);if(h>1&&(a="_multisampled"),!0===s.isCubeTexture&&!0===s.isDepthTexture)r="texture_depth_cube";else if(!0===s.isCubeTexture)r="texture_cube<f32>";else if(!0===s.isDepthTexture)r=t.compatibilityMode&&null===s.compareFunction?`texture${a}_2d<f32>`:`texture_depth${a}_2d${!0===s.isArrayTexture?"_array":""}`;else if(!0===n.node.isStorageTextureNode){const i=SM(s,t.device),a=this.getStorageAccess(n.node,e),o=n.node.value.is3DTexture,h=n.node.value.isArrayTexture;r=`texture_storage_${o?"3d":"2d"+(h?"_array":"")}<${i}, ${a}>`}else if(!0===s.isArrayTexture||!0===s.isDataArrayTexture||!0===s.isCompressedArrayTexture)r="texture_2d_array<f32>";else if(!0===s.is3DTexture||!0===s.isData3DTexture)r="texture_3d<f32>";else{r=`texture${a}_2d<${this.getComponentTypeFromTexture(s).charAt(0)}32>`}i.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${n.name} : ${r};`)}else if("buffer"===n.type||"storageBuffer"===n.type||"indirectStorageBuffer"===n.type){const t=n.node,s=this.getType(t.getNodeType(this)),i=t.bufferCount,a=i>0&&"buffer"===n.type?", "+i:"",h=t.isStorageBufferNode?`storage, ${this.getStorageAccess(t,e)}`:"uniform";if(this.isCustomStruct(n))r.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var<${h}> ${n.name} : ${s};`);else{const e=`\tvalue : array< ${t.isAtomic?`atomic<${s}>`:`${s}`}${a} >`;r.push(this._getWGSLStructBinding(n.name,e,h,o.binding++,o.group))}}else{const e=n.groupNode.name;if(void 0===a[e]){const t=this.uniformGroups[e];if(void 0!==t){const s=[];for(const e of t.uniforms){const t=e.getType(),i=this.getType(this.getVectorType(t));s.push(`\t${e.name} : ${i}`)}let i=this.uniformGroupsBindings[e];void 0===i&&(i={index:o.binding++,id:o.group},this.uniformGroupsBindings[e]=i),a[e]={index:i.index,id:i.id,snippets:s}}}}}for(const e in a){const t=a[e];n.push(this._getWGSLStructBinding(e,t.snippets.join(",\n"),"uniform",t.index,t.id))}return[...i,...r,...n].join("\n")}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){this.shaderStage=t;const s=this.allowGlobalVariables,i=e[t];i.uniforms=this.getUniforms(t),i.attributes=this.getAttributes(t),i.varyings=this.getVaryings(t),i.structs=this.getStructs(t),i.vars=this.getVars(t,s),i.codes=this.getCodes(t),i.directives=this.getDirectives(t),i.scopedArrays=this.getScopedArrays(t);let r="// code\n\n";r+=this.flowCode[t];const n=this.flowNodes[t],a=n[n.length-1],o=a.outputNode,h=void 0!==o&&!0===o.isOutputStructNode;for(const e of n){const s=this.getFlowData(e),n=e.name;if(n&&(r.length>0&&(r+="\n"),r+=`\t// flow -> ${n}\n`),r+=`${s.code}\n\t`,e===a&&"compute"!==t)if(r+="// result\n\n\t","vertex"===t)r+=`varyings.builtinClipSpace = ${s.result};`;else if("fragment"===t)if(h)i.returnType=o.getNodeType(this),i.structs+="var<private> output : "+i.returnType+";",r+=`return ${s.result};`;else{let e="\t@location( 0 ) color: vec4<f32>";const t=this.getBuiltins("output");t&&(e+=",\n\t"+t),i.returnType="OutputStruct",i.structs+=this._getWGSLStruct("OutputStruct",e),i.structs+="\nvar<private> output : OutputStruct;",r+=`output.color = ${s.result};\n\n\treturn output;`}}i.flow=r}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 LM[e]||e}isAvailable(e){let t=BM[e];return void 0===t&&("float32Filterable"===e?t=this.renderer.hasFeature("float32-filterable"):"clipDistance"===e&&(t=this.renderer.hasFeature("clip-distances")),BM[e]=t),t}_getWGSLMethod(e){return void 0!==IM[e]&&this._include(e),OM[e]}_include(e){const t=IM[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// vars\n${e.vars}\n\n// codes\n${e.codes}\n\n@vertex\nfn main( ${e.attributes} ) -> VaryingsStruct {\n\n\t// flow\n\t${e.flow}\n\n\treturn varyings;\n\n}\n`}_getWGSLFragmentCode(e){return`${this.getSignature()}\n// global\n${UM}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// vars\n${e.vars}\n\n// codes\n${e.codes}\n\n@fragment\nfn main( ${e.varyings} ) -> ${e.returnType} {\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// vars\n${this.allowGlobalVariables?e.vars:""}\n\n// codes\n${e.codes}\n\n@compute @workgroup_size( ${s}, ${i}, ${r} )\nfn main( ${e.attributes} ) {\n\n\t// local vars\n\t${this.allowGlobalVariables?"":e.vars}\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// 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 zM{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return e.depth&&(t=null!==e.depthTexture?this.getTextureFormatGPU(e.depthTexture):e.stencil?!0===this.backend.renderer.reversedDepthBuffer?mS:dS:!0===this.backend.renderer.reversedDepthBuffer?pS:cS),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?eT:e.isLineSegments||e.isMesh&&!0===t.wireframe?tT:e.isLine?sT:e.isMesh?iT: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===j)return HT;if(e===K)return rS;throw new Error("Unsupported output buffer type.")}}const VM=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&&VM.set(Float16Array,["float16"]);const GM=new Map([[Ei,["float16"]]]),jM=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class $M{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 a=i.device;let o=s.array;if(!1===e.normalized)if(o.constructor===Int16Array||o.constructor===Int8Array)o=new Int32Array(o);else if((o.constructor===Uint16Array||o.constructor===Uint8Array)&&(o=new Uint32Array(o),t&GPUBufferUsage.INDEX))for(let e=0;e<o.length;e++)65535===o[e]&&(o[e]=4294967295);if(s.array=o,(s.isStorageBufferAttribute||s.isStorageInstancedBufferAttribute)&&3===s.itemSize){o=new o.constructor(4*s.count);for(let e=0;e<s.count;e++)o.set(s.array.subarray(3*e,3*e+3),4*e);s.itemSize=4,s.array=o,r._force3to4BytesAlignment=!0}const h=o.byteLength,l=h+(4-h%4)%4;n=a.createBuffer({label:s.name,size:l,usage:t,mappedAtCreation:!0}),new o.constructor(n.getMappedRange()).set(o),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 a=t.array;if(!0===r._force3to4BytesAlignment){a=new a.constructor(4*t.count);for(let e=0;e<t.count;e++)a.set(t.array.subarray(3*e,3*e+3),4*e);t.array=a}const o=t.updateRanges;if(0===o.length)i.queue.writeBuffer(n,0,a,0);else{const e=pt(a),s=e?1:a.BYTES_PER_ELEMENT;for(let t=0,h=o.length;t<h;t++){const h=o[t];let l,u;if(!0===r._force3to4BytesAlignment){l=4*Math.floor(h.start/3)*s,u=4*Math.ceil(h.count/3)*s}else l=h.start*s,u=h.count*s;const c=l*(e?a.BYTES_PER_ELEMENT:1);i.queue.writeBuffer(n,c,a,l,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 a=s.get(n);if(void 0===a){let e,t;!0===i.isInterleavedBufferAttribute?(e=i.data.stride*r,t=i.data.isInstancedInterleavedBuffer?dM:cM):(e=i.itemSize*r,t=i.isInstancedBufferAttribute?dM:cM),!1!==i.normalized||i.array.constructor!==Int16Array&&i.array.constructor!==Uint16Array||(e=4),a={arrayStride:e,attributes:[],stepMode:t},s.set(n,a)}const o=this._getVertexFormat(i),h=!0===i.isInterleavedBufferAttribute?i.offset*r:0;a.attributes.push({shaderLocation:e,offset:h,format:o})}return Array.from(s.values())}destroyAttribute(e){const t=this.backend;t.get(this._getBufferAttribute(e)).buffer.destroy(),t.delete(e)}async getArrayBufferAsync(e,t=null,s=0,i=-1){const r=this.backend,n=r.device,a=r.get(this._getBufferAttribute(e)).buffer,o=-1===i?a.size-s:i;let h;if(null!==t&&t.isReadbackBuffer){const e=r.get(t);if(!0===t._mapped)throw new Error("WebGPURenderer: ReadbackBuffer must be released before being used again.");if(t._mapped=!0,void 0===e.readBufferGPU){h=n.createBuffer({label:`${t.name}_readback`,size:t.maxByteLength,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});const s=()=>{t.buffer=null,t._mapped=!1,h.unmap()},i=()=>{t.buffer=null,t._mapped=!1,h.destroy(),r.delete(t),t.removeEventListener("release",s),t.removeEventListener("dispose",i)};t.addEventListener("release",s),t.addEventListener("dispose",i),e.readBufferGPU=h}else h=e.readBufferGPU}else h=n.createBuffer({label:`${e.name}_readback`,size:o,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});const l=n.createCommandEncoder({label:`readback_encoder_${e.name}`});l.copyBufferToBuffer(a,s,h,0,o);const u=l.finish();if(n.queue.submit([u]),await h.mapAsync(GPUMapMode.READ,0,o),null===t){const e=h.getMappedRange(0,o).slice();return h.destroy(),e}if(t.isReadbackBuffer)return t.buffer=h.getMappedRange(0,o),t;{const e=h.getMappedRange(0,o);return new Uint8Array(t).set(new Uint8Array(e)),h.destroy(),t}}_getVertexFormat(e){const{itemSize:t,normalized:s}=e,i=e.array.constructor,r=e.constructor;let n;if(1===t)n=jM.get(i);else{const e=(GM.get(r)||VM.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||_t("WebGPUAttributeUtils: Vertex format not supported yet."),n}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}class WM{constructor(e){this.layoutGPU=e,this.usedTimes=0}}class HM{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=Ln(JSON.stringify(r));let a=this._bindGroupLayoutCache.get(n);return void 0===a&&(a=new WM(s.createBindGroupLayout({entries:r})),this._bindGroupLayoutCache.set(n,a)),a.usedTimes++,i.layout=a,i.layoutKey=n,a.layoutGPU}createBindings(e,t,s,i=0){const{backend:r}=this,n=r.get(e),a=this.createBindingsLayout(e);let o;s>0&&(void 0===n.groups&&(n.groups=[],n.versions=[]),n.versions[s]===i&&(o=n.groups[s])),void 0===o&&(o=this.createBindGroup(e,a),s>0&&(n.groups[s]=o,n.versions[s]=i)),n.group=o}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 e=pt(i),t=e?1:i.BYTES_PER_ELEMENT;for(let a=0,o=n.length;a<o;a++){const o=n[a],h=o.start*t,l=o.count*t,u=h*(e?i.BYTES_PER_ELEMENT:1);s.queue.writeBuffer(r,u,i,h,l)}}}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 a=[{binding:0,resource:{buffer:n}}];return s.createBindGroup({label:"bindGroupCameraIndex_"+r,layout:t,entries:a})}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&rT.VERTEX&&n.push("vertex"),t.visibility&rT.FRAGMENT&&n.push("fragment"),t.visibility&rT.COMPUTE&&n.push("compute");const a=`(${n.join(",")})`,o=i.createBuffer({label:`bindingBuffer${t.id}_${t.name}_${a}`,size:s,usage:r});e.buffer=o}n.push({binding:r,resource:{buffer:e.buffer}})}else if(t.isStorageBuffer){const e=s.get(t.attribute).buffer;n.push({binding:r,resource:{buffer:e}})}else if(t.isSampledTexture){const e=s.get(t.texture);let a;if(void 0!==e.externalTexture)a=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}`,a=e[r],void 0===a){const n=uM;let o;o=t.isSampledCubeTexture?hM:t.isSampledTexture3D?lM:t.texture.isArrayTexture||t.texture.isDataArrayTexture||t.texture.isCompressedArrayTexture?oM:aM,a=e[r]=e.texture.createView({aspect:n,dimension:o,mipLevelCount:s,baseMipLevel:i})}}n.push({binding:r,resource:a})}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&rT.COMPUTE&&(i.access===Kn||i.access===Yn)?e.type=Hw:e.type=qw),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===Kn?Kw:t===Yn?Xw:Yw,i.texture.isArrayTexture?e.viewDimension=oM:i.texture.is3DTexture&&(e.viewDimension=lM),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=eM)),i.texture.isDepthTexture)e.compatibilityMode&&null===i.texture.compareFunction?t.sampleType=eM:t.sampleType=tM;else if(i.texture.isDataTexture||i.texture.isDataArrayTexture||i.texture.isData3DTexture||i.texture.isStorageTexture){const e=i.texture.type;e===q?t.sampleType=sM:e===X?t.sampleType=iM:e===Y&&(this.backend.hasFeature("float32-filterable")?t.sampleType=Jw:t.sampleType=eM)}i.isSampledCubeTexture?t.viewDimension=hM:i.texture.isArrayTexture||i.texture.isDataArrayTexture||i.texture.isCompressedArrayTexture?t.viewDimension=oM:i.isSampledTexture3D&&(t.viewDimension=lM),r.texture=t}else if(i.isSampler){const t={};i.texture.isDepthTexture&&(null!==i.texture.compareFunction&&e.hasCompatibility(dt)?t.type=Zw:t.type=Qw),r.sampler=t}else _t(`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 qM{constructor(e){this.backend=e}getMaxAnisotropy(){return 16}getUniformBufferLimit(){return this.backend.device.limits.maxUniformBufferBindingSize}}class XM{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:a,fragmentProgram:o}=n,h=this.backend,l=h.device,u=h.utils,c=h.get(n),d=[];for(const t of e.getBindings()){const e=h.get(t),{layoutGPU:s}=e.layout;d.push(s)}const p=h.attributeUtils.createShaderVertexBuffers(e);let m;0===i.blending||1===i.blending&&!1===i.transparent||(m=this._getBlending(i));let g={};!0===i.stencilWrite&&(g={compare:this._getStencilCompare(i),failOp:this._getStencilOperation(i.stencilFail),depthFailOp:this._getStencilOperation(i.stencilZFail),passOp:this._getStencilOperation(i.stencilZPass)});const f=this._getColorWriteMask(i),y=[];if(null!==e.context.textures){const t=e.context.textures,s=e.context.mrt;for(let e=0;e<t.length;e++){const i=t[e],r=u.getTextureFormatGPU(i);let n;if(null!==s)if(!0!==this.backend.compatibilityMode){const e=s.getBlendMode(i.name);6===e.blending?n=m:0!==e.blending&&(n=this._getBlending(e))}else xt("WebGPURenderer: Multiple Render Targets (MRT) blending configuration is not fully supported in compatibility mode. The material blending will be used for all render targets."),n=m;else n=m;y.push({format:r,blend:n,writeMask:f})}}else{const t=u.getCurrentColorFormat(e.context);y.push({format:t,blend:m,writeMask:f})}const b=h.get(a).module,_=h.get(o).module,x=this._getPrimitiveState(s,r,i),v=this._getDepthCompare(i),T=u.getCurrentDepthStencilFormat(e.context),S=this._getSampleCount(e.context),w={label:`renderPipeline_${i.name||i.type}_${i.id}`,vertex:Object.assign({},b,{buffers:p}),fragment:Object.assign({},_,{targets:y}),primitive:x,multisample:{count:S,alphaToCoverageEnabled:i.alphaToCoverage&&S>1},layout:l.createPipelineLayout({bindGroupLayouts:d})},M={},N=e.context.depth,A=e.context.stencil;if(!0!==N&&!0!==A||(!0===N&&(M.format=T,M.depthWriteEnabled=i.depthWrite,M.depthCompare=v),!0===A&&(M.stencilFront=g,M.stencilBack=g,M.stencilReadMask=i.stencilFuncMask,M.stencilWriteMask=i.stencilWriteMask),!0===i.polygonOffset&&(M.depthBias=i.polygonOffsetUnits,M.depthBiasSlopeScale=i.polygonOffsetFactor,M.depthBiasClamp=0),w.depthStencil=M),l.pushErrorScope("validation"),null===t)c.pipeline=l.createRenderPipeline(w),l.popErrorScope().then(e=>{null!==e&&(c.error=!0,_t(e.message))});else{const e=new Promise(async e=>{try{c.pipeline=await l.createRenderPipelineAsync(w)}catch(e){}const t=await l.popErrorScope();null!==t&&(c.error=!0,_t(t.message)),e()});t.push(e)}}createBundleEncoder(e,t="renderBundleEncoder"){const s=this.backend,{utils:i,device:r}=s,n=i.getCurrentDepthStencilFormat(e),a={label:t,colorFormats:i.getCurrentColorFormats(e),depthStencilFormat:n,sampleCount:this._getSampleCount(e)};return r.createRenderBundleEncoder(a)}createComputePipeline(e,t){const s=this.backend,i=s.device,r=s.get(e.computeProgram).module,n=s.get(e),a=[];for(const e of t){const t=s.get(e),{layoutGPU:i}=t.layout;a.push(i)}n.pipeline=i.createComputePipeline({compute:r,layout:i.createPipelineLayout({bindGroupLayouts:a})})}_getBlending(e){let t,s;const i=e.blending,r=e.blendSrc,n=e.blendDst,a=e.blendEquation;if(5===i){const i=null!==e.blendSrcAlpha?e.blendSrcAlpha:r,o=null!==e.blendDstAlpha?e.blendDstAlpha:n,h=null!==e.blendEquationAlpha?e.blendEquationAlpha:a;t={srcFactor:this._getBlendFactor(r),dstFactor:this._getBlendFactor(n),operation:this._getBlendOperation(a)},s={srcFactor:this._getBlendFactor(i),dstFactor:this._getBlendFactor(o),operation:this._getBlendOperation(h)}}else{const r=(e,i,r,n)=>{t={srcFactor:e,dstFactor:i,operation:Pw},s={srcFactor:r,dstFactor:n,operation:Pw}};if(e.premultipliedAlpha)switch(i){case 1:r(_w,Sw,_w,Sw);break;case 2:r(_w,_w,_w,_w);break;case 3:r(bw,vw,bw,_w);break;case 4:r(ww,Sw,bw,_w)}else switch(i){case 1:r(Tw,Sw,_w,Sw);break;case 2:r(Tw,_w,_w,_w);break;case 3:_t(`WebGPURenderer: "SubtractiveBlending" requires "${e.isMaterial?"material":"blendMode"}.premultipliedAlpha = true".`);break;case 4:_t(`WebGPURenderer: "MultiplyBlending" requires "${e.isMaterial?"material":"blendMode"}.premultipliedAlpha = true".`)}}if(void 0!==t&&void 0!==s)return{color:t,alpha:s};_t("WebGPURenderer: Invalid blending: ",i)}_getBlendFactor(e){let t;switch(e){case p:t=bw;break;case 201:t=_w;break;case 202:t=xw;break;case 203:t=vw;break;case y:t=Tw;break;case b:t=Sw;break;case 208:t=ww;break;case 209:t=Mw;break;case 206:t=Nw;break;case 207:t=Aw;break;case 210:t=Ew;break;case 211:t=Rw;break;case 212:t=Cw;break;default:_t("WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const s=e.stencilFunc;switch(s){case 512:t=nT;break;case 519:t=dT;break;case 513:t=aT;break;case 515:t=hT;break;case 514:t=oT;break;case 518:t=cT;break;case 516:t=lT;break;case 517:t=uT;break;default:_t("WebGPURenderer: Invalid stencil function.",s)}return t}_getStencilOperation(e){let t;switch(e){case Qe:t=Uw;break;case 0:t=kw;break;case 7681:t=zw;break;case 5386:t=Vw;break;case 7682:t=Gw;break;case 7683:t=jw;break;case 34055:t=$w;break;case 34056:t=Ww;break;default:_t("WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case u:t=Pw;break;case 101:t=Bw;break;case 102:t=Fw;break;case 103:t=Lw;break;case 104:t=Dw;break;default:_t("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?xT:vT);let n=1===s.side;return e.isMesh&&e.matrixWorld.determinant()<0&&(n=!n),i.frontFace=!0===n?yT:fT,i.cullMode=2===s.side?bT:_T,i}_getColorWriteMask(e){return!0===e.colorWrite?Ow:Iw}_getDepthCompare(e){let t;if(!1===e.depthTest)t=dT;else{const s=this.backend.parameters.reversedDepthBuffer?Tt[e.depthFunc]:e.depthFunc;switch(s){case 0:t=nT;break;case 1:t=dT;break;case 2:t=aT;break;case 3:t=hT;break;case 4:t=oT;break;case 5:t=cT;break;case 6:t=lT;break;case 7:t=uT;break;default:_t("WebGPUPipelineUtils: Invalid depth function.",s)}}return t}}class YM extends Qv{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 xt(`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)),a={},o=[];for(const[t,s]of e){const e=t.match(/^(.*):f(\d+)$/),i=parseInt(e[2]);!1===o.includes(i)&&o.push(i),void 0===a[i]&&(a[i]=0);const r=n[s],h=n[s+1],l=Number(h-r)/1e6;this.timestamps.set(t,l),a[i]+=l}const h=a[o[o.length-1]];return this.resultBuffer.unmap(),this.lastValue=h,this.frames=o,h}catch(e){return _t("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){_t("Error waiting for pending resolve:",e)}if(this.resultBuffer&&"mapped"===this.resultBuffer.mapState)try{this.resultBuffer.unmap()}catch(e){_t("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}}}const KM={r:0,g:0,b:0,a:1};class QM extends Fv{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=void 0===e.alpha||e.alpha,this.parameters.requiredLimits=void 0===e.requiredLimits?{}:e.requiredLimits,this.compatibilityMode=null,this.device=null,this.defaultRenderPassdescriptor=null,this.utils=new zM(this),this.attributeUtils=new $M(this),this.bindingUtils=new HM(this),this.capabilities=new qM(this),this.pipelineUtils=new XM(this),this.textureUtils=new TM(this),this.occludedResolveCache=new Map;const t="undefined"==typeof navigator||!1===/Android/.test(navigator.userAgent);this._compatibility={[dt]:t}}async init(e){await super.init(e);const t=this.parameters;let s;if(void 0===t.device){const e={powerPreference:t.powerPreference,featureLevel:"compatibility"},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(pM),n=[];for(const e of r)i.features.has(e)&&n.push(e);const a={requiredFeatures:n,requiredLimits:t.requiredLimits};s=await i.requestDevice(a)}else s=t.device;this.compatibilityMode=!s.features.has("core-features-and-limits"),this.compatibilityMode&&(e._samples=0),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(pM.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${a} webgpu`);const r=i.alpha?"premultiplied":"opaque",n=i.outputType===K?"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 lt}async getArrayBufferAsync(e,t=null,s=0,i=-1){return await this.attributeUtils.getArrayBufferAsync(e,t,s,i)}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 a=r[n];if(void 0===a){const t=e.textures,o=[];let h;const l=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:aM};if(s.isRenderTarget3D)h=e.activeCubeFace,n.baseArrayLayer=0,n.dimension=lM,n.depthOrArrayLayers=t[i].image.depth;else if(s.isRenderTarget&&t[i].image.depth>1)if(!0===l){const t=e.camera.cameras;for(let e=0;e<t.length;e++){const t={...n,baseArrayLayer:e,arrayLayerCount:1,dimension:aM},s=r.texture.createView(t);o.push({view:s,resolveTarget:void 0,depthSlice:void 0})}}else n.dimension=oM,n.depthOrArrayLayers=t[i].image.depth;if(!0!==l){const e=r.texture.createView(n);let t,s;void 0!==r.msaaTexture?(t=r.msaaTexture.createView(),s=e):(t=e,s=void 0),o.push({view:t,resolveTarget:s,depthSlice:h})}}if(a={textureViews:o},e.depth){const t=this.get(e.depthTexture),s={};(e.depthTexture.isArrayTexture||e.depthTexture.isCubeTexture)&&(s.dimension=aM,s.arrayLayerCount=1,s.baseArrayLayer=e.activeCubeFace),a.depthStencilView=t.texture.createView(s)}r[n]=a,i.width=s.width,i.height=s.height,i.samples=s.samples,i.activeMipmapLevel=e.activeMipmapLevel,i.activeCubeFace=e.activeCubeFace}const o={colorAttachments:[]};for(let e=0;e<a.textureViews.length;e++){const s=a.textureViews[e];let i={r:0,g:0,b:0,a:1};0===e&&t.clearValue&&(i=t.clearValue),o.colorAttachments.push({view:s.view,depthSlice:s.depthSlice,resolveTarget:s.resolveTarget,loadOp:t.loadOp||mT,storeOp:t.storeOp||pT,clearValue:i})}return a.depthStencilView&&(o.depthStencilAttachment={view:a.depthStencilView}),o}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:mT}),this.initTimestampQuery(ct,this.getTimestampUID(e),n),n.occlusionQuerySet=r;const a=n.depthStencilAttachment;if(null!==e.textures){const t=n.colorAttachments;for(let s=0;s<t.length;s++){const i=t[s];e.clearColor?(0===s?i.clearValue=e.clearColorValue:(KM.r=0,KM.g=0,KM.b=0,KM.a=1,i.clearValue=KM),i.loadOp=gT):i.loadOp=mT,i.storeOp=pT}}else{const t=n.colorAttachments[0];e.clearColor?(t.clearValue=e.clearColorValue,t.loadOp=gT):t.loadOp=mT,t.storeOp=pT}e.depth&&(e.clearDepth?(a.depthClearValue=e.clearDepthValue,a.depthLoadOp=gT):a.depthLoadOp=mT,a.depthStoreOp=pT),e.stencil&&(e.clearStencil?(a.stencilClearValue=e.clearStencilValue,a.stencilLoadOp=gT):a.stencilLoadOp=mT,a.stencilStoreOp=pT);const o=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=o.beginRenderPass(n);t.currentPass=s,e.viewport&&this.updateViewport(e),e.scissor&&this.updateScissor(e)}t.descriptor=n,t.encoder=o,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 a=0;a<i.length;a++){const i={...s,colorAttachments:[{...s.colorAttachments[0],view:s.colorAttachments[a].view}]};if(s.depthStencilAttachment){const t=a;n.viewCache[t]||(n.viewCache[t]=n.texture.createView({dimension:aM,baseArrayLayer:a,arrayLayerCount:1})),i.depthStencilAttachment={view:n.viewCache[t],depthLoadOp:r.depthLoadOp||gT,depthStoreOp:r.depthStoreOp||pT,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=gT):t.depthLoadOp=mT),e.stencil&&(e.clearStencil?(t.stencilClearValue=e.clearStencilValue,t.stencilLoadOp=gT):t.stencilLoadOp=mT)}}}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],a=i.beginRenderPass(n);if(e.viewport){const{x:t,y:s,width:i,height:r,minDepth:n,maxDepth:o}=e.viewportValue;a.setViewport(t,s,i,r,n,o)}if(e.scissor){const{x:t,y:s,width:i,height:r}=e.scissorValue;a.setScissorRect(t,s,i,r)}a.executeBundles([s[r]]),a.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:a,maxDepth:o}=e.viewportValue;t.setViewport(s,i,r,n,a,o)}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 a,o,h,l=[];if(e){const e=this.getClearColor();KM.r=e.r,KM.g=e.g,KM.b=e.b,KM.a=e.a}if(null===i){o=n.depth,h=n.stencil;const t=this._getDefaultRenderPassDescriptor();if(e){l=t.colorAttachments;const e=l[0];e.clearValue=KM,e.loadOp=gT,e.storeOp=pT}(o||h)&&(a=t.depthStencilAttachment)}else{o=i.depth,h=i.stencil;const r={loadOp:e?gT:mT,clearValue:e?KM:void 0};o&&(r.depthLoadOp=t?gT:mT,r.depthClearValue=t?n.getClearDepth():void 0,r.depthStoreOp=pT),h&&(r.stencilLoadOp=s?gT:mT,r.stencilClearValue=s?n.getClearStencil():void 0,r.stencilStoreOp=pT);const u=this._getRenderPassDescriptor(i,r);l=u.colorAttachments,a=u.depthStencilAttachment}o&&a&&(t?(a.depthLoadOp=gT,a.depthClearValue=n.getClearDepth(),a.depthStoreOp=pT):(a.depthLoadOp=mT,a.depthStoreOp=pT)),h&&a&&(s?(a.stencilLoadOp=gT,a.stencilClearValue=n.getClearStencil(),a.stencilStoreOp=pT):(a.stencilLoadOp=mT,a.stencilStoreOp=pT));const u=r.createCommandEncoder({label:"clear"});u.beginRenderPass({colorAttachments:l,depthStencilAttachment:a}).end(),r.queue.submit([u.finish()])}beginCompute(e){const t=this.get(e),s={label:"computeGroup_"+e.id};this.initTimestampQuery(ut,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:a}=this.get(e),o=this.get(i).pipeline;this.pipelineUtils.setPipeline(a,o);for(let e=0,t=s.length;e<t;e++){const t=s[e],i=this.get(t);a.setBindGroup(e,i.group)}if(null===r&&(r=t.dispatchSize||t.count),r&&r.isIndirectStorageBufferAttribute){const e=this.get(r).buffer;return void a.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 a=Math.ceil(e/i),o=this.device.limits.maxComputeWorkgroupsPerDimension;r=[a,1,1],a>o&&(r[0]=Math.min(a,o),r[1]=Math.ceil(a/o)),n.dispatchSize=r}r=n.dispatchSize}a.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,s,i,r,n,a,o,h){const{object:l,material:u,context:c}=e,d=e.getIndex(),p=null!==d;this.pipelineUtils.setPipeline(o,i),h.pipeline=i;const m=h.bindingGroups;for(let e=0,t=r.length;e<t;e++){const t=r[e],s=this.get(t);m[e]!==t.id&&(o.setBindGroup(e,s.group),m[e]=t.id)}if(!0===p&&h.index!==d){const e=this.get(d).buffer,t=d.array instanceof Uint16Array?xT:vT;o.setIndexBuffer(e,t),h.index=d}for(let e=0,t=n.length;e<t;e++){const t=n[e];if(h.attributes[e]!==t){const s=this.get(t).buffer;o.setVertexBuffer(e,s),h.attributes[e]=t}}if(!0===c.stencil&&!0===u.stencilWrite&&s.currentStencilRef!==u.stencilRef&&(o.setStencilReference(u.stencilRef),s.currentStencilRef=u.stencilRef),!0===l.isBatchedMesh){const e=l._multiDrawStarts,s=l._multiDrawCounts,i=l._multiDrawCount;let r=!0===p?d.array.BYTES_PER_ELEMENT:1;u.wireframe&&(r=l.geometry.attributes.position.count>65535?4:2);for(let n=0;n<i;n++)!0===p?o.drawIndexed(s[n],1,e[n]/r,0,n):o.draw(s[n],1,e[n],n),t.update(l,s[n],1)}else if(!0===p){const{vertexCount:s,instanceCount:i,firstVertex:r}=a,n=e.getIndirect();if(null!==n){const t=this.get(n).buffer,s=e.getIndirectOffset(),i=Array.isArray(s)?s:[s];for(let e=0;e<i.length;e++)o.drawIndexedIndirect(t,i[e])}else o.drawIndexed(s,i,r,0,0);t.update(l,s,i)}else{const{vertexCount:s,instanceCount:i,firstVertex:r}=a,n=e.getIndirect();if(null!==n){const t=this.get(n).buffer,s=e.getIndirectOffset(),i=Array.isArray(s)?s:[s];for(let e=0;e<i.length;e++)o.drawIndirect(t,i[e])}else o.draw(s,i,r,0);t.update(l,s,i)}}draw(e,t){const{object:s,context:i,pipeline:r}=e,n=this.get(i),a=this.get(r),o=a.pipeline;if(!0===a.error)return;const h=e.getDrawParameters();if(null===h)return;const l=e.getBindings(),u=e.getVertexBuffers();if(e.camera.isArrayCamera&&e.camera.cameras.length>0){const r=this.get(e.camera),a=e.camera.cameras,c=e.getBindingGroup("cameraIndex");if(void 0===r.indexesGPU||r.indexesGPU.length!==a.length){const e=this.get(c),t=[],s=new Uint32Array([0,0,0,0]);for(let i=0,r=a.length;i<r;i++){s[0]=i;const{layoutGPU:r}=e.layout,n=this.bindingUtils.createBindGroupIndex(s,r);t.push(n)}r.indexesGPU=t}const d=this.renderer.getPixelRatio();for(let p=0,m=a.length;p<m;p++){const m=a[p];if(s.layers.test(m.layers)){const s=m.viewport;let a=n.currentPass,g=n.currentSets;if(n.bundleEncoders){a=n.bundleEncoders[p],g=n.bundleSets[p]}if(s&&a.setViewport(Math.floor(s.x*d),Math.floor(s.y*d),Math.floor(s.width*d),Math.floor(s.height*d),i.viewportValue.minDepth,i.viewportValue.maxDepth),c&&r.indexesGPU){const e=l.indexOf(c);a.setBindGroup(e,r.indexesGPU[p]),g.bindingGroups[e]=c.id}this._draw(e,t,n,o,l,u,h,a,g)}}}else if(n.currentPass){if(void 0!==n.occlusionQuerySet){const e=n.lastOcclusionObject;e!==s&&(null!==e&&!0===e.occlusionTest&&(n.currentPass.endOcclusionQuery(),n.occlusionQueryIndex++),!0===s.occlusionTest&&(n.currentPass.beginOcclusionQuery(n.occlusionQueryIndex),n.occlusionQueryObjects[n.occlusionQueryIndex]=s),n.lastOcclusionObject=s)}this._draw(e,t,n,o,l,u,h,n.currentPass,n.currentSets)}}needsRenderUpdate(e){const t=this.get(e),{object:s,material:i}=e,r=this.utils,n=r.getSampleCountRenderContext(e.context),a=r.getCurrentColorSpace(e.context),o=r.getCurrentColorFormat(e.context),h=r.getCurrentDepthStencilFormat(e.context),l=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===a&&t.colorFormat===o&&t.depthStencilFormat===h&&t.primitiveTopology===l&&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=a,t.colorFormat=o,t.depthStencilFormat=h,t.primitiveTopology=l,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 YM(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 kM(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())}hasFeature(e){return void 0!==mM[e]&&(e=mM[e]),this.device.features.has(e)}copyTextureToTexture(e,t,s=null,i=null,r=0,n=0){let a=0,o=0,h=0,l=0,u=0,c=0,d=e.image.width,p=e.image.height,m=1;null!==s&&(!0===s.isBox3?(l=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):(l=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&&(a=i.x,o=i.y,h=i.z||0);const g=this.device.createCommandEncoder({label:"copyTextureToTexture_"+e.id+"_"+t.id}),f=this.get(e).texture,y=this.get(t).texture;g.copyTextureToTexture({texture:f,mipLevel:r,origin:{x:l,y:u,z:c}},{texture:y,mipLevel:n,origin:{x:a,y:o,z:h}},[d,p,m]),this.device.queue.submit([g.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 _t("WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.",r.format,n.format);let a;if(i.currentPass?(i.currentPass.end(),a=i.encoder):a=this.device.createCommandEncoder({label:"copyFramebufferToTexture_"+e.id}),a.copyTextureToTexture({texture:r,origin:[s.x,s.y,0]},{texture:n},[s.z,s.w]),e.generateMipmaps&&this.textureUtils.generateMipmaps(e,a),i.currentPass){const{descriptor:e}=i;for(let t=0;t<e.colorAttachments.length;t++)e.colorAttachments[t].loadOp=mT;t.depth&&(e.depthStencilAttachment.depthLoadOp=mT),t.stencil&&(e.depthStencilAttachment.stencilLoadOp=mT),i.currentPass=a.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([a.finish()])}hasCompatibility(e){return void 0!==this._compatibility[e]?this._compatibility[e]:super.hasCompatibility(e)}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 ZM extends un{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 JM extends un{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 eN extends Ux{constructor(){super(),this.addMaterial(sg,"MeshPhongMaterial"),this.addMaterial(qf,"MeshStandardMaterial"),this.addMaterial(Yf,"MeshPhysicalMaterial"),this.addMaterial(Jf,"MeshToonMaterial"),this.addMaterial(qm,"MeshBasicMaterial"),this.addMaterial(eg,"MeshLambertMaterial"),this.addMaterial(Lm,"MeshNormalMaterial"),this.addMaterial(sy,"MeshMatcapMaterial"),this.addMaterial(Cm,"LineBasicMaterial"),this.addMaterial(Bm,"LineDashedMaterial"),this.addMaterial(ly,"PointsMaterial"),this.addMaterial(ay,"SpriteMaterial"),this.addMaterial(py,"ShadowMaterial"),this.addLight(M_,dn),this.addLight(dx,gn),this.addLight(Tx,yn),this.addLight(mx,un),this.addLight(cx,fn),this.addLight(px,Yr),this.addLight(fx,_n),this.addLight(gx,ZM),this.addLight(bx,JM),this.addToneMapping(vb,1),this.addToneMapping(Tb,2),this.addToneMapping(Sb,3),this.addToneMapping(Mb,4),this.addToneMapping(Rb,6),this.addToneMapping(Cb,7)}}class tN extends hv{constructor(e={}){let t;e.forceWebGL?t=Jv:(t=QM,e.getFallback=()=>(bt("WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new Jv(e)));super(new t(e),e),this.library=new eN,this.isWebGPURenderer=!0,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}}const sN={type:"change"},iN={type:"start"},rN={type:"end"},nN=1e-6,aN=-1,oN=0,hN=1,lN=2,uN=3,cN=4,dN=new e.Vector2,pN=new e.Vector2,mN=new e.Vector3,gN=new e.Vector3,fN=new e.Vector3,yN=new e.Quaternion,bN=new e.Vector3,_N=new e.Vector3,xN=new e.Vector3,vN=new e.Vector3;class TN extends e.Controls{constructor(t,s=null){super(t,s),this.screen={left:0,top:0,width:0,height:0},this.rotateSpeed=1,this.zoomSpeed=1.2,this.panSpeed=.3,this.noRotate=!1,this.noZoom=!1,this.noPan=!1,this.staticMoving=!1,this.dynamicDampingFactor=.2,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.keys=["KeyA","KeyS","KeyD"],this.mouseButtons={LEFT:e.MOUSE.ROTATE,MIDDLE:e.MOUSE.DOLLY,RIGHT:e.MOUSE.PAN},this.target=new e.Vector3,this.state=aN,this.keyState=aN,this._lastPosition=new e.Vector3,this._lastZoom=1,this._touchZoomDistanceStart=0,this._touchZoomDistanceEnd=0,this._lastAngle=0,this._eye=new e.Vector3,this._movePrev=new e.Vector2,this._moveCurr=new e.Vector2,this._lastAxis=new e.Vector3,this._zoomStart=new e.Vector2,this._zoomEnd=new e.Vector2,this._panStart=new e.Vector2,this._panEnd=new e.Vector2,this._pointers=[],this._pointerPositions={},this._onPointerMove=wN.bind(this),this._onPointerDown=SN.bind(this),this._onPointerUp=MN.bind(this),this._onPointerCancel=NN.bind(this),this._onContextMenu=FN.bind(this),this._onMouseWheel=BN.bind(this),this._onKeyDown=EN.bind(this),this._onKeyUp=AN.bind(this),this._onTouchStart=LN.bind(this),this._onTouchMove=DN.bind(this),this._onTouchEnd=IN.bind(this),this._onMouseDown=RN.bind(this),this._onMouseMove=CN.bind(this),this._onMouseUp=PN.bind(this),this._target0=this.target.clone(),this._position0=this.object.position.clone(),this._up0=this.object.up.clone(),this._zoom0=this.object.zoom,null!==s&&(this.connect(s),this.handleResize()),this.update()}connect(e){super.connect(e),window.addEventListener("keydown",this._onKeyDown),window.addEventListener("keyup",this._onKeyUp),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerCancel),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction="none"}disconnect(){window.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("keyup",this._onKeyUp),this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerCancel),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction=""}dispose(){this.disconnect()}handleResize(){const e=this.domElement.getBoundingClientRect(),t=this.domElement.ownerDocument.documentElement;this.screen.left=e.left+window.pageXOffset-t.clientLeft,this.screen.top=e.top+window.pageYOffset-t.clientTop,this.screen.width=e.width,this.screen.height=e.height}update(){this._eye.subVectors(this.object.position,this.target),this.noRotate||this._rotateCamera(),this.noZoom||this._zoomCamera(),this.noPan||this._panCamera(),this.object.position.addVectors(this.target,this._eye),this.object.isPerspectiveCamera?(this._checkDistances(),this.object.lookAt(this.target),this._lastPosition.distanceToSquared(this.object.position)>nN&&(this.dispatchEvent(sN),this._lastPosition.copy(this.object.position))):this.object.isOrthographicCamera?(this.object.lookAt(this.target),(this._lastPosition.distanceToSquared(this.object.position)>nN||this._lastZoom!==this.object.zoom)&&(this.dispatchEvent(sN),this._lastPosition.copy(this.object.position),this._lastZoom=this.object.zoom)):console.warn("THREE.TrackballControls: Unsupported camera type.")}reset(){this.state=aN,this.keyState=aN,this.target.copy(this._target0),this.object.position.copy(this._position0),this.object.up.copy(this._up0),this.object.zoom=this._zoom0,this.object.updateProjectionMatrix(),this._eye.subVectors(this.object.position,this.target),this.object.lookAt(this.target),this.dispatchEvent(sN),this._lastPosition.copy(this.object.position),this._lastZoom=this.object.zoom}_panCamera(){if(pN.copy(this._panEnd).sub(this._panStart),pN.lengthSq()){if(this.object.isOrthographicCamera){const e=(this.object.right-this.object.left)/this.object.zoom/this.domElement.clientWidth,t=(this.object.top-this.object.bottom)/this.object.zoom/this.domElement.clientWidth;pN.x*=e,pN.y*=t}pN.multiplyScalar(this._eye.length()*this.panSpeed),gN.copy(this._eye).cross(this.object.up).setLength(pN.x),gN.add(mN.copy(this.object.up).setLength(pN.y)),this.object.position.add(gN),this.target.add(gN),this.staticMoving?this._panStart.copy(this._panEnd):this._panStart.add(pN.subVectors(this._panEnd,this._panStart).multiplyScalar(this.dynamicDampingFactor))}}_rotateCamera(){vN.set(this._moveCurr.x-this._movePrev.x,this._moveCurr.y-this._movePrev.y,0);let e=vN.length();e?(this._eye.copy(this.object.position).sub(this.target),bN.copy(this._eye).normalize(),_N.copy(this.object.up).normalize(),xN.crossVectors(_N,bN).normalize(),_N.setLength(this._moveCurr.y-this._movePrev.y),xN.setLength(this._moveCurr.x-this._movePrev.x),vN.copy(_N.add(xN)),fN.crossVectors(vN,this._eye).normalize(),e*=this.rotateSpeed,yN.setFromAxisAngle(fN,e),this._eye.applyQuaternion(yN),this.object.up.applyQuaternion(yN),this._lastAxis.copy(fN),this._lastAngle=e):!this.staticMoving&&this._lastAngle&&(this._lastAngle*=Math.sqrt(1-this.dynamicDampingFactor),this._eye.copy(this.object.position).sub(this.target),yN.setFromAxisAngle(this._lastAxis,this._lastAngle),this._eye.applyQuaternion(yN),this.object.up.applyQuaternion(yN)),this._movePrev.copy(this._moveCurr)}_zoomCamera(){let t;this.state===cN?(t=this._touchZoomDistanceStart/this._touchZoomDistanceEnd,this._touchZoomDistanceStart=this._touchZoomDistanceEnd,this.object.isPerspectiveCamera?this._eye.multiplyScalar(t):this.object.isOrthographicCamera?(this.object.zoom=e.MathUtils.clamp(this.object.zoom/t,this.minZoom,this.maxZoom),this._lastZoom!==this.object.zoom&&this.object.updateProjectionMatrix()):console.warn("THREE.TrackballControls: Unsupported camera type")):(t=1+(this._zoomEnd.y-this._zoomStart.y)*this.zoomSpeed,1!==t&&t>0&&(this.object.isPerspectiveCamera?this._eye.multiplyScalar(t):this.object.isOrthographicCamera?(this.object.zoom=e.MathUtils.clamp(this.object.zoom/t,this.minZoom,this.maxZoom),this._lastZoom!==this.object.zoom&&this.object.updateProjectionMatrix()):console.warn("THREE.TrackballControls: Unsupported camera type")),this.staticMoving?this._zoomStart.copy(this._zoomEnd):this._zoomStart.y+=(this._zoomEnd.y-this._zoomStart.y)*this.dynamicDampingFactor)}_getMouseOnScreen(e,t){return dN.set((e-this.screen.left)/this.screen.width,(t-this.screen.top)/this.screen.height),dN}_getMouseOnCircle(e,t){return dN.set((e-.5*this.screen.width-this.screen.left)/(.5*this.screen.width),(this.screen.height+2*(this.screen.top-t))/this.screen.width),dN}_addPointer(e){this._pointers.push(e)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t].pointerId==e.pointerId)return void this._pointers.splice(t,1)}_trackPointer(t){let s=this._pointerPositions[t.pointerId];void 0===s&&(s=new e.Vector2,this._pointerPositions[t.pointerId]=s),s.set(t.pageX,t.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0].pointerId?this._pointers[1]:this._pointers[0];return this._pointerPositions[t.pointerId]}_checkDistances(){this.noZoom&&this.noPan||(this._eye.lengthSq()>this.maxDistance*this.maxDistance&&(this.object.position.addVectors(this.target,this._eye.setLength(this.maxDistance)),this._zoomStart.copy(this._zoomEnd)),this._eye.lengthSq()<this.minDistance*this.minDistance&&(this.object.position.addVectors(this.target,this._eye.setLength(this.minDistance)),this._zoomStart.copy(this._zoomEnd)))}}function SN(e){!1!==this.enabled&&(0===this._pointers.length&&(this.domElement.setPointerCapture(e.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp)),this._addPointer(e),"touch"===e.pointerType?this._onTouchStart(e):this._onMouseDown(e))}function wN(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchMove(e):this._onMouseMove(e))}function MN(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchEnd(e):this._onMouseUp(),this._removePointer(e),0===this._pointers.length&&(this.domElement.releasePointerCapture(e.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp)))}function NN(e){this._removePointer(e)}function AN(){!1!==this.enabled&&(this.keyState=aN,window.addEventListener("keydown",this._onKeyDown))}function EN(e){!1!==this.enabled&&(window.removeEventListener("keydown",this._onKeyDown),this.keyState===aN&&(e.code!==this.keys[oN]||this.noRotate?e.code!==this.keys[hN]||this.noZoom?e.code!==this.keys[lN]||this.noPan||(this.keyState=lN):this.keyState=hN:this.keyState=oN))}function RN(t){let s;switch(t.button){case 0:s=this.mouseButtons.LEFT;break;case 1:s=this.mouseButtons.MIDDLE;break;case 2:s=this.mouseButtons.RIGHT;break;default:s=-1}switch(s){case e.MOUSE.DOLLY:this.state=hN;break;case e.MOUSE.ROTATE:this.state=oN;break;case e.MOUSE.PAN:this.state=lN;break;default:this.state=aN}const i=this.keyState!==aN?this.keyState:this.state;i!==oN||this.noRotate?i!==hN||this.noZoom?i!==lN||this.noPan||(this._panStart.copy(this._getMouseOnScreen(t.pageX,t.pageY)),this._panEnd.copy(this._panStart)):(this._zoomStart.copy(this._getMouseOnScreen(t.pageX,t.pageY)),this._zoomEnd.copy(this._zoomStart)):(this._moveCurr.copy(this._getMouseOnCircle(t.pageX,t.pageY)),this._movePrev.copy(this._moveCurr)),this.dispatchEvent(iN)}function CN(e){const t=this.keyState!==aN?this.keyState:this.state;t!==oN||this.noRotate?t!==hN||this.noZoom?t!==lN||this.noPan||this._panEnd.copy(this._getMouseOnScreen(e.pageX,e.pageY)):this._zoomEnd.copy(this._getMouseOnScreen(e.pageX,e.pageY)):(this._movePrev.copy(this._moveCurr),this._moveCurr.copy(this._getMouseOnCircle(e.pageX,e.pageY)))}function PN(){this.state=aN,this.dispatchEvent(rN)}function BN(e){if(!1!==this.enabled&&!0!==this.noZoom){switch(e.preventDefault(),e.deltaMode){case 2:this._zoomStart.y-=.025*e.deltaY;break;case 1:this._zoomStart.y-=.01*e.deltaY;break;default:this._zoomStart.y-=25e-5*e.deltaY}this.dispatchEvent(iN),this.dispatchEvent(rN)}}function FN(e){!1!==this.enabled&&e.preventDefault()}function LN(e){if(this._trackPointer(e),1===this._pointers.length)this.state=uN,this._moveCurr.copy(this._getMouseOnCircle(this._pointers[0].pageX,this._pointers[0].pageY)),this._movePrev.copy(this._moveCurr);else{this.state=cN;const e=this._pointers[0].pageX-this._pointers[1].pageX,t=this._pointers[0].pageY-this._pointers[1].pageY;this._touchZoomDistanceEnd=this._touchZoomDistanceStart=Math.sqrt(e*e+t*t);const s=(this._pointers[0].pageX+this._pointers[1].pageX)/2,i=(this._pointers[0].pageY+this._pointers[1].pageY)/2;this._panStart.copy(this._getMouseOnScreen(s,i)),this._panEnd.copy(this._panStart)}this.dispatchEvent(iN)}function DN(e){if(this._trackPointer(e),1===this._pointers.length)this._movePrev.copy(this._moveCurr),this._moveCurr.copy(this._getMouseOnCircle(e.pageX,e.pageY));else{const t=this._getSecondPointerPosition(e),s=e.pageX-t.x,i=e.pageY-t.y;this._touchZoomDistanceEnd=Math.sqrt(s*s+i*i);const r=(e.pageX+t.x)/2,n=(e.pageY+t.y)/2;this._panEnd.copy(this._getMouseOnScreen(r,n))}}function IN(e){switch(this._pointers.length){case 0:this.state=aN;break;case 1:this.state=uN,this._moveCurr.copy(this._getMouseOnCircle(e.pageX,e.pageY)),this._movePrev.copy(this._moveCurr);break;case 2:this.state=cN;for(let t=0;t<this._pointers.length;t++)if(this._pointers[t].pointerId!==e.pointerId){const e=this._pointerPositions[this._pointers[t].pointerId];this._moveCurr.copy(this._getMouseOnCircle(e.x,e.y)),this._movePrev.copy(this._moveCurr);break}}this.dispatchEvent(rN)}const ON={type:"change"},UN={type:"start"},kN={type:"end"},zN=new e.Ray,VN=new e.Plane,GN=Math.cos(70*e.MathUtils.DEG2RAD),jN=new e.Vector3,$N=2*Math.PI,WN=-1,HN=0,qN=1,XN=2,YN=3,KN=4,QN=5,ZN=6,JN=1e-6;class eA extends e.Controls{constructor(t,s=null){super(t,s),this.state=WN,this.target=new e.Vector3,this.cursor=new e.Vector3,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:e.MOUSE.ROTATE,MIDDLE:e.MOUSE.DOLLY,RIGHT:e.MOUSE.PAN},this.touches={ONE:e.TOUCH.ROTATE,TWO:e.TOUCH.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._cursorStyle="auto",this._domElementKeyEvents=null,this._lastPosition=new e.Vector3,this._lastQuaternion=new e.Quaternion,this._lastTargetPosition=new e.Vector3,this._quat=(new e.Quaternion).setFromUnitVectors(t.up,new e.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new e.Spherical,this._sphericalDelta=new e.Spherical,this._scale=1,this._panOffset=new e.Vector3,this._rotateStart=new e.Vector2,this._rotateEnd=new e.Vector2,this._rotateDelta=new e.Vector2,this._panStart=new e.Vector2,this._panEnd=new e.Vector2,this._panDelta=new e.Vector2,this._dollyStart=new e.Vector2,this._dollyEnd=new e.Vector2,this._dollyDelta=new e.Vector2,this._dollyDirection=new e.Vector3,this._mouse=new e.Vector2,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=sA.bind(this),this._onPointerDown=tA.bind(this),this._onPointerUp=iA.bind(this),this._onContextMenu=uA.bind(this),this._onMouseWheel=aA.bind(this),this._onKeyDown=oA.bind(this),this._onTouchStart=hA.bind(this),this._onTouchMove=lA.bind(this),this._onMouseDown=rA.bind(this),this._onMouseMove=nA.bind(this),this._interceptControlDown=cA.bind(this),this._interceptControlUp=dA.bind(this),null!==this.domElement&&this.connect(this.domElement),this.update()}set cursorStyle(e){this._cursorStyle=e,this.domElement.style.cursor="grab"===e?"grab":"auto"}get cursorStyle(){return this._cursorStyle}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1});this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents();this.domElement.getRootNode().removeEventListener("keydown",this._interceptControlDown,{capture:!0}),this.domElement.style.touchAction=""}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){null!==this._domElementKeyEvents&&(this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null)}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(ON),this.update(),this.state=WN}pan(e,t){this._pan(e,t),this.update()}dollyIn(e){this._dollyIn(e),this.update()}dollyOut(e){this._dollyOut(e),this.update()}rotateLeft(e){this._rotateLeft(e),this.update()}rotateUp(e){this._rotateUp(e),this.update()}update(t=null){const s=this.object.position;jN.copy(s).sub(this.target),jN.applyQuaternion(this._quat),this._spherical.setFromVector3(jN),this.autoRotate&&this.state===WN&&this._rotateLeft(this._getAutoRotationAngle(t)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let i=this.minAzimuthAngle,r=this.maxAzimuthAngle;isFinite(i)&&isFinite(r)&&(i<-Math.PI?i+=$N:i>Math.PI&&(i-=$N),r<-Math.PI?r+=$N:r>Math.PI&&(r-=$N),this._spherical.theta=i<=r?Math.max(i,Math.min(r,this._spherical.theta)):this._spherical.theta>(i+r)/2?Math.max(i,this._spherical.theta):Math.min(r,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),!0===this.enableDamping?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let n=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const e=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),n=e!=this._spherical.radius}if(jN.setFromSpherical(this._spherical),jN.applyQuaternion(this._quatInverse),s.copy(this.target).add(jN),this.object.lookAt(this.target),!0===this.enableDamping?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let t=null;if(this.object.isPerspectiveCamera){const e=jN.length();t=this._clampDistance(e*this._scale);const s=e-t;this.object.position.addScaledVector(this._dollyDirection,s),this.object.updateMatrixWorld(),n=!!s}else if(this.object.isOrthographicCamera){const s=new e.Vector3(this._mouse.x,this._mouse.y,0);s.unproject(this.object);const i=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),n=i!==this.object.zoom;const r=new e.Vector3(this._mouse.x,this._mouse.y,0);r.unproject(this.object),this.object.position.sub(r).add(s),this.object.updateMatrixWorld(),t=jN.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;null!==t&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(t).add(this.object.position):(zN.origin.copy(this.object.position),zN.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(zN.direction))<GN?this.object.lookAt(this.target):(VN.setFromNormalAndCoplanarPoint(this.object.up,this.target),zN.intersectPlane(VN,this.target))))}else if(this.object.isOrthographicCamera){const e=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),e!==this.object.zoom&&(this.object.updateProjectionMatrix(),n=!0)}return this._scale=1,this._performCursorZoom=!1,!!(n||this._lastPosition.distanceToSquared(this.object.position)>JN||8*(1-this._lastQuaternion.dot(this.object.quaternion))>JN||this._lastTargetPosition.distanceToSquared(this.target)>JN)&&(this.dispatchEvent(ON),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0)}_getAutoRotationAngle(e){return null!==e?$N/60*this.autoRotateSpeed*e:$N/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(.01*e);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){jN.setFromMatrixColumn(t,0),jN.multiplyScalar(-e),this._panOffset.add(jN)}_panUp(e,t){!0===this.screenSpacePanning?jN.setFromMatrixColumn(t,1):(jN.setFromMatrixColumn(t,0),jN.crossVectors(this.object.up,jN)),jN.multiplyScalar(e),this._panOffset.add(jN)}_pan(e,t){const s=this.domElement;if(this.object.isPerspectiveCamera){const i=this.object.position;jN.copy(i).sub(this.target);let r=jN.length();r*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*r/s.clientHeight,this.object.matrix),this._panUp(2*t*r/s.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/s.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/s.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const s=this.domElement.getBoundingClientRect(),i=e-s.left,r=t-s.top,n=s.width,a=s.height;this._mouse.x=i/n*2-1,this._mouse.y=-r/a*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft($N*this._rotateDelta.x/t.clientHeight),this._rotateUp($N*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp($N*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-$N*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft($N*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-$N*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(1===this._pointers.length)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),s=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._rotateStart.set(s,i)}}_handleTouchStartPan(e){if(1===this._pointers.length)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),s=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panStart.set(s,i)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),s=e.pageX-t.x,i=e.pageY-t.y,r=Math.sqrt(s*s+i*i);this._dollyStart.set(0,r)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(1==this._pointers.length)this._rotateEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),s=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._rotateEnd.set(s,i)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft($N*this._rotateDelta.x/t.clientHeight),this._rotateUp($N*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(1===this._pointers.length)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),s=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panEnd.set(s,i)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),s=e.pageX-t.x,i=e.pageY-t.y,r=Math.sqrt(s*s+i*i);this._dollyEnd.set(0,r),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const n=.5*(e.pageX+t.x),a=.5*(e.pageY+t.y);this._updateZoomParameters(n,a)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return void this._pointers.splice(t,1)}_isTrackingPointer(e){for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return!0;return!1}_trackPointer(t){let s=this._pointerPositions[t.pointerId];void 0===s&&(s=new e.Vector2,this._pointerPositions[t.pointerId]=s),s.set(t.pageX,t.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){const t=e.deltaMode,s={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:s.deltaY*=16;break;case 2:s.deltaY*=100}return e.ctrlKey&&!this._controlActive&&(s.deltaY*=10),s}}function tA(e){!1!==this.enabled&&(0===this._pointers.length&&(this.domElement.setPointerCapture(e.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp)),this._isTrackingPointer(e)||(this._addPointer(e),"touch"===e.pointerType?this._onTouchStart(e):this._onMouseDown(e),"grab"===this._cursorStyle&&(this.domElement.style.cursor="grabbing")))}function sA(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchMove(e):this._onMouseMove(e))}function iA(e){switch(this._removePointer(e),this._pointers.length){case 0:this.domElement.releasePointerCapture(e.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(kN),this.state=WN,"grab"===this._cursorStyle&&(this.domElement.style.cursor="grab");break;case 1:const t=this._pointers[0],s=this._pointerPositions[t];this._onTouchStart({pointerId:t,pageX:s.x,pageY:s.y})}}function rA(t){let s;switch(t.button){case 0:s=this.mouseButtons.LEFT;break;case 1:s=this.mouseButtons.MIDDLE;break;case 2:s=this.mouseButtons.RIGHT;break;default:s=-1}switch(s){case e.MOUSE.DOLLY:if(!1===this.enableZoom)return;this._handleMouseDownDolly(t),this.state=qN;break;case e.MOUSE.ROTATE:if(t.ctrlKey||t.metaKey||t.shiftKey){if(!1===this.enablePan)return;this._handleMouseDownPan(t),this.state=XN}else{if(!1===this.enableRotate)return;this._handleMouseDownRotate(t),this.state=HN}break;case e.MOUSE.PAN:if(t.ctrlKey||t.metaKey||t.shiftKey){if(!1===this.enableRotate)return;this._handleMouseDownRotate(t),this.state=HN}else{if(!1===this.enablePan)return;this._handleMouseDownPan(t),this.state=XN}break;default:this.state=WN}this.state!==WN&&this.dispatchEvent(UN)}function nA(e){switch(this.state){case HN:if(!1===this.enableRotate)return;this._handleMouseMoveRotate(e);break;case qN:if(!1===this.enableZoom)return;this._handleMouseMoveDolly(e);break;case XN:if(!1===this.enablePan)return;this._handleMouseMovePan(e)}}function aA(e){!1!==this.enabled&&!1!==this.enableZoom&&this.state===WN&&(e.preventDefault(),this.dispatchEvent(UN),this._handleMouseWheel(this._customWheelEvent(e)),this.dispatchEvent(kN))}function oA(e){!1!==this.enabled&&this._handleKeyDown(e)}function hA(t){switch(this._trackPointer(t),this._pointers.length){case 1:switch(this.touches.ONE){case e.TOUCH.ROTATE:if(!1===this.enableRotate)return;this._handleTouchStartRotate(t),this.state=YN;break;case e.TOUCH.PAN:if(!1===this.enablePan)return;this._handleTouchStartPan(t),this.state=KN;break;default:this.state=WN}break;case 2:switch(this.touches.TWO){case e.TOUCH.DOLLY_PAN:if(!1===this.enableZoom&&!1===this.enablePan)return;this._handleTouchStartDollyPan(t),this.state=QN;break;case e.TOUCH.DOLLY_ROTATE:if(!1===this.enableZoom&&!1===this.enableRotate)return;this._handleTouchStartDollyRotate(t),this.state=ZN;break;default:this.state=WN}break;default:this.state=WN}this.state!==WN&&this.dispatchEvent(UN)}function lA(e){switch(this._trackPointer(e),this.state){case YN:if(!1===this.enableRotate)return;this._handleTouchMoveRotate(e),this.update();break;case KN:if(!1===this.enablePan)return;this._handleTouchMovePan(e),this.update();break;case QN:if(!1===this.enableZoom&&!1===this.enablePan)return;this._handleTouchMoveDollyPan(e),this.update();break;case ZN:if(!1===this.enableZoom&&!1===this.enableRotate)return;this._handleTouchMoveDollyRotate(e),this.update();break;default:this.state=WN}}function uA(e){!1!==this.enabled&&e.preventDefault()}function cA(e){if("Control"===e.key){this._controlActive=!0;this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}}function dA(e){if("Control"===e.key){this._controlActive=!1;this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}}const pA={type:"change"},mA=1e-6,gA=new e.Quaternion;class fA extends e.Controls{constructor(t,s=null){super(t,s),this.movementSpeed=1,this.rollSpeed=.005,this.dragToLook=!1,this.autoForward=!1,this._moveState={up:0,down:0,left:0,right:0,forward:0,back:0,pitchUp:0,pitchDown:0,yawLeft:0,yawRight:0,rollLeft:0,rollRight:0},this._moveVector=new e.Vector3(0,0,0),this._rotationVector=new e.Vector3(0,0,0),this._lastQuaternion=new e.Quaternion,this._lastPosition=new e.Vector3,this._status=0,this._onKeyDown=yA.bind(this),this._onKeyUp=bA.bind(this),this._onPointerMove=xA.bind(this),this._onPointerDown=_A.bind(this),this._onPointerUp=vA.bind(this),this._onPointerCancel=TA.bind(this),this._onContextMenu=SA.bind(this),null!==s&&this.connect(s)}connect(e){super.connect(e),window.addEventListener("keydown",this._onKeyDown),window.addEventListener("keyup",this._onKeyUp),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointerup",this._onPointerUp),this.domElement.addEventListener("pointercancel",this._onPointerCancel),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction="none"}disconnect(){window.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("keyup",this._onKeyUp),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerCancel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction=""}dispose(){this.disconnect()}update(e){if(!1===this.enabled)return;const t=this.object,s=e*this.movementSpeed,i=e*this.rollSpeed;t.translateX(this._moveVector.x*s),t.translateY(this._moveVector.y*s),t.translateZ(this._moveVector.z*s),gA.set(this._rotationVector.x*i,this._rotationVector.y*i,this._rotationVector.z*i,1).normalize(),t.quaternion.multiply(gA),(this._lastPosition.distanceToSquared(t.position)>mA||8*(1-this._lastQuaternion.dot(t.quaternion))>mA)&&(this.dispatchEvent(pA),this._lastQuaternion.copy(t.quaternion),this._lastPosition.copy(t.position))}_updateMovementVector(){const e=this._moveState.forward||this.autoForward&&!this._moveState.back?1:0;this._moveVector.x=-this._moveState.left+this._moveState.right,this._moveVector.y=-this._moveState.down+this._moveState.up,this._moveVector.z=-e+this._moveState.back}_updateRotationVector(){this._rotationVector.x=-this._moveState.pitchDown+this._moveState.pitchUp,this._rotationVector.y=-this._moveState.yawRight+this._moveState.yawLeft,this._rotationVector.z=-this._moveState.rollRight+this._moveState.rollLeft}_getContainerDimensions(){return this.domElement!=document?{size:[this.domElement.offsetWidth,this.domElement.offsetHeight],offset:[this.domElement.offsetLeft,this.domElement.offsetTop]}:{size:[window.innerWidth,window.innerHeight],offset:[0,0]}}}function yA(e){if(!e.altKey&&!1!==this.enabled){switch(e.code){case"ShiftLeft":case"ShiftRight":this.movementSpeedMultiplier=.1;break;case"KeyW":this._moveState.forward=1;break;case"KeyS":this._moveState.back=1;break;case"KeyA":this._moveState.left=1;break;case"KeyD":this._moveState.right=1;break;case"KeyR":this._moveState.up=1;break;case"KeyF":this._moveState.down=1;break;case"ArrowUp":this._moveState.pitchUp=1;break;case"ArrowDown":this._moveState.pitchDown=1;break;case"ArrowLeft":this._moveState.yawLeft=1;break;case"ArrowRight":this._moveState.yawRight=1;break;case"KeyQ":this._moveState.rollLeft=1;break;case"KeyE":this._moveState.rollRight=1}this._updateMovementVector(),this._updateRotationVector()}}function bA(e){if(!1!==this.enabled){switch(e.code){case"ShiftLeft":case"ShiftRight":this.movementSpeedMultiplier=1;break;case"KeyW":this._moveState.forward=0;break;case"KeyS":this._moveState.back=0;break;case"KeyA":this._moveState.left=0;break;case"KeyD":this._moveState.right=0;break;case"KeyR":this._moveState.up=0;break;case"KeyF":this._moveState.down=0;break;case"ArrowUp":this._moveState.pitchUp=0;break;case"ArrowDown":this._moveState.pitchDown=0;break;case"ArrowLeft":this._moveState.yawLeft=0;break;case"ArrowRight":this._moveState.yawRight=0;break;case"KeyQ":this._moveState.rollLeft=0;break;case"KeyE":this._moveState.rollRight=0}this._updateMovementVector(),this._updateRotationVector()}}function _A(e){if(!1!==this.enabled)if(this.dragToLook)this._status++;else{switch(e.button){case 0:this._moveState.forward=1;break;case 2:this._moveState.back=1}this._updateMovementVector()}}function xA(e){if(!1!==this.enabled&&(!this.dragToLook||this._status>0)){const t=this._getContainerDimensions(),s=t.size[0]/2,i=t.size[1]/2;this._moveState.yawLeft=-(e.pageX-t.offset[0]-s)/s,this._moveState.pitchDown=(e.pageY-t.offset[1]-i)/i,this._updateRotationVector()}}function vA(e){if(!1!==this.enabled){if(this.dragToLook)this._status--,this._moveState.yawLeft=this._moveState.pitchDown=0;else{switch(e.button){case 0:this._moveState.forward=0;break;case 2:this._moveState.back=0}this._updateMovementVector()}this._updateRotationVector()}}function TA(){!1!==this.enabled&&(this.dragToLook?(this._status=0,this._moveState.yawLeft=this._moveState.pitchDown=0):(this._moveState.forward=0,this._moveState.back=0,this._updateMovementVector()),this._updateRotationVector())}function SA(e){!1!==this.enabled&&e.preventDefault()}const wA={name:"CopyShader",uniforms:{tDiffuse:{value:null},opacity:{value:1}},vertexShader:"\n\n\t\tvarying vec2 vUv;\n\n\t\tvoid main() {\n\n\t\t\tvUv = uv;\n\t\t\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\n\t\t}",fragmentShader:"\n\n\t\tuniform float opacity;\n\n\t\tuniform sampler2D tDiffuse;\n\n\t\tvarying vec2 vUv;\n\n\t\tvoid main() {\n\n\t\t\tvec4 texel = texture2D( tDiffuse, vUv );\n\t\t\tgl_FragColor = opacity * texel;\n\n\n\t\t}"};class MA{constructor(){this.isPass=!0,this.enabled=!0,this.needsSwap=!0,this.clear=!1,this.renderToScreen=!1}setSize(){}render(){console.error("THREE.Pass: .render() must be implemented in derived pass.")}dispose(){}}const NA=new e.OrthographicCamera(-1,1,1,-1,0,1);class AA extends e.BufferGeometry{constructor(){super(),this.setAttribute("position",new e.Float32BufferAttribute([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new e.Float32BufferAttribute([0,2,0,0,2,0],2))}}const EA=new AA;class RA{constructor(t){this._mesh=new e.Mesh(EA,t)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,NA)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}class CA extends MA{constructor(t,s="tDiffuse"){super(),this.textureID=s,this.uniforms=null,this.material=null,t instanceof e.ShaderMaterial?(this.uniforms=t.uniforms,this.material=t):t&&(this.uniforms=e.UniformsUtils.clone(t.uniforms),this.material=new e.ShaderMaterial({name:void 0!==t.name?t.name:"unspecified",defines:Object.assign({},t.defines),uniforms:this.uniforms,vertexShader:t.vertexShader,fragmentShader:t.fragmentShader})),this._fsQuad=new RA(this.material)}render(e,t,s){this.uniforms[this.textureID]&&(this.uniforms[this.textureID].value=s.texture),this._fsQuad.material=this.material,this.renderToScreen?(e.setRenderTarget(null),this._fsQuad.render(e)):(e.setRenderTarget(t),this.clear&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),this._fsQuad.render(e))}dispose(){this.material.dispose(),this._fsQuad.dispose()}}class PA extends MA{constructor(e,t){super(),this.scene=e,this.camera=t,this.clear=!0,this.needsSwap=!1,this.inverse=!1}render(e,t,s){const i=e.getContext(),r=e.state;let n,a;r.buffers.color.setMask(!1),r.buffers.depth.setMask(!1),r.buffers.color.setLocked(!0),r.buffers.depth.setLocked(!0),this.inverse?(n=0,a=1):(n=1,a=0),r.buffers.stencil.setTest(!0),r.buffers.stencil.setOp(i.REPLACE,i.REPLACE,i.REPLACE),r.buffers.stencil.setFunc(i.ALWAYS,n,4294967295),r.buffers.stencil.setClear(a),r.buffers.stencil.setLocked(!0),e.setRenderTarget(s),this.clear&&e.clear(),e.render(this.scene,this.camera),e.setRenderTarget(t),this.clear&&e.clear(),e.render(this.scene,this.camera),r.buffers.color.setLocked(!1),r.buffers.depth.setLocked(!1),r.buffers.color.setMask(!0),r.buffers.depth.setMask(!0),r.buffers.stencil.setLocked(!1),r.buffers.stencil.setFunc(i.EQUAL,1,4294967295),r.buffers.stencil.setOp(i.KEEP,i.KEEP,i.KEEP),r.buffers.stencil.setLocked(!0)}}class BA extends MA{constructor(){super(),this.needsSwap=!1}render(e){e.state.buffers.stencil.setLocked(!1),e.state.buffers.stencil.setTest(!1)}}class FA{constructor(t,s){if(this.renderer=t,this._pixelRatio=t.getPixelRatio(),void 0===s){const i=t.getSize(new e.Vector2);this._width=i.width,this._height=i.height,(s=new e.WebGLRenderTarget(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:e.HalfFloatType})).texture.name="EffectComposer.rt1"}else this._width=s.width,this._height=s.height;this.renderTarget1=s,this.renderTarget2=s.clone(),this.renderTarget2.texture.name="EffectComposer.rt2",this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2,this.renderToScreen=!0,this.passes=[],this.copyPass=new CA(wA),this.copyPass.material.blending=e.NoBlending,this.timer=new e.Timer}swapBuffers(){const e=this.readBuffer;this.readBuffer=this.writeBuffer,this.writeBuffer=e}addPass(e){this.passes.push(e),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}insertPass(e,t){this.passes.splice(t,0,e),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}removePass(e){const t=this.passes.indexOf(e);-1!==t&&this.passes.splice(t,1)}isLastEnabledPass(e){for(let t=e+1;t<this.passes.length;t++)if(this.passes[t].enabled)return!1;return!0}render(e){this.timer.update(),void 0===e&&(e=this.timer.getDelta());const t=this.renderer.getRenderTarget();let s=!1;for(let t=0,i=this.passes.length;t<i;t++){const i=this.passes[t];if(!1!==i.enabled){if(i.renderToScreen=this.renderToScreen&&this.isLastEnabledPass(t),i.render(this.renderer,this.writeBuffer,this.readBuffer,e,s),i.needsSwap){if(s){const t=this.renderer.getContext(),s=this.renderer.state.buffers.stencil;s.setFunc(t.NOTEQUAL,1,4294967295),this.copyPass.render(this.renderer,this.writeBuffer,this.readBuffer,e),s.setFunc(t.EQUAL,1,4294967295)}this.swapBuffers()}void 0!==PA&&(i instanceof PA?s=!0:i instanceof BA&&(s=!1))}}this.renderer.setRenderTarget(t)}reset(t){if(void 0===t){const s=this.renderer.getSize(new e.Vector2);this._pixelRatio=this.renderer.getPixelRatio(),this._width=s.width,this._height=s.height,(t=this.renderTarget1.clone()).setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}this.renderTarget1.dispose(),this.renderTarget2.dispose(),this.renderTarget1=t,this.renderTarget2=t.clone(),this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2}setSize(e,t){this._width=e,this._height=t;const s=this._width*this._pixelRatio,i=this._height*this._pixelRatio;this.renderTarget1.setSize(s,i),this.renderTarget2.setSize(s,i);for(let e=0;e<this.passes.length;e++)this.passes[e].setSize(s,i)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget1.dispose(),this.renderTarget2.dispose(),this.copyPass.dispose()}}class LA extends MA{constructor(t,s,i=null,r=null,n=null){super(),this.scene=t,this.camera=s,this.overrideMaterial=i,this.clearColor=r,this.clearAlpha=n,this.clear=!0,this.clearDepth=!1,this.needsSwap=!1,this.isRenderPass=!0,this._oldClearColor=new e.Color}render(e,t,s){const i=e.autoClear;let r,n;e.autoClear=!1,null!==this.overrideMaterial&&(n=this.scene.overrideMaterial,this.scene.overrideMaterial=this.overrideMaterial),null!==this.clearColor&&(e.getClearColor(this._oldClearColor),e.setClearColor(this.clearColor,e.getClearAlpha())),null!==this.clearAlpha&&(r=e.getClearAlpha(),e.setClearAlpha(this.clearAlpha)),1==this.clearDepth&&e.clearDepth(),e.setRenderTarget(this.renderToScreen?null:s),!0===this.clear&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),e.render(this.scene,this.camera),null!==this.clearColor&&e.setClearColor(this._oldClearColor),null!==this.clearAlpha&&e.setClearAlpha(r),null!==this.overrideMaterial&&(this.scene.overrideMaterial=n),e.autoClear=i}}function DA(){return DA=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var s=arguments[t];for(var i in s)({}).hasOwnProperty.call(s,i)&&(e[i]=s[i])}return e},DA.apply(null,arguments)}function IA(e,t){return IA=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},IA(e,t)}function OA(e){return OA=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},OA(e)}function UA(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(UA=function(){return!!e})()}function kA(e){var t="function"==typeof Map?new Map:void 0;return kA=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,s)}function s(){return function(e,t,s){if(UA())return Reflect.construct.apply(null,arguments);var i=[null];i.push.apply(i,t);var r=new(e.bind.apply(e,i));return s&&IA(r,s.prototype),r}(e,arguments,OA(this).constructor)}return s.prototype=Object.create(e.prototype,{constructor:{value:s,enumerable:!1,writable:!0,configurable:!0}}),IA(s,e)},kA(e)}var zA={1:"Passed invalid arguments to hsl, please pass multiple numbers e.g. hsl(360, 0.75, 0.4) or an object e.g. rgb({ hue: 255, saturation: 0.4, lightness: 0.75 }).\n\n",2:"Passed invalid arguments to hsla, please pass multiple numbers e.g. hsla(360, 0.75, 0.4, 0.7) or an object e.g. rgb({ hue: 255, saturation: 0.4, lightness: 0.75, alpha: 0.7 }).\n\n",3:"Passed an incorrect argument to a color function, please pass a string representation of a color.\n\n",4:"Couldn't generate valid rgb string from %s, it returned %s.\n\n",5:"Couldn't parse the color string. Please provide the color as a string in hex, rgb, rgba, hsl or hsla notation.\n\n",6:"Passed invalid arguments to rgb, please pass multiple numbers e.g. rgb(255, 205, 100) or an object e.g. rgb({ red: 255, green: 205, blue: 100 }).\n\n",7:"Passed invalid arguments to rgba, please pass multiple numbers e.g. rgb(255, 205, 100, 0.75) or an object e.g. rgb({ red: 255, green: 205, blue: 100, alpha: 0.75 }).\n\n",8:"Passed invalid argument to toColorString, please pass a RgbColor, RgbaColor, HslColor or HslaColor object.\n\n",9:"Please provide a number of steps to the modularScale helper.\n\n",10:"Please pass a number or one of the predefined scales to the modularScale helper as the ratio.\n\n",11:'Invalid value passed as base to modularScale, expected number or em string but got "%s"\n\n',12:'Expected a string ending in "px" or a number passed as the first argument to %s(), got "%s" instead.\n\n',13:'Expected a string ending in "px" or a number passed as the second argument to %s(), got "%s" instead.\n\n',14:'Passed invalid pixel value ("%s") to %s(), please pass a value like "12px" or 12.\n\n',15:'Passed invalid base value ("%s") to %s(), please pass a value like "12px" or 12.\n\n',16:"You must provide a template to this method.\n\n",17:"You passed an unsupported selector state to this method.\n\n",18:"minScreen and maxScreen must be provided as stringified numbers with the same units.\n\n",19:"fromSize and toSize must be provided as stringified numbers with the same units.\n\n",20:"expects either an array of objects or a single object with the properties prop, fromSize, and toSize.\n\n",21:"expects the objects in the first argument array to have the properties `prop`, `fromSize`, and `toSize`.\n\n",22:"expects the first argument object to have the properties `prop`, `fromSize`, and `toSize`.\n\n",23:"fontFace expects a name of a font-family.\n\n",24:"fontFace expects either the path to the font file(s) or a name of a local copy.\n\n",25:"fontFace expects localFonts to be an array.\n\n",26:"fontFace expects fileFormats to be an array.\n\n",27:"radialGradient requries at least 2 color-stops to properly render.\n\n",28:"Please supply a filename to retinaImage() as the first argument.\n\n",29:"Passed invalid argument to triangle, please pass correct pointingDirection e.g. 'right'.\n\n",30:"Passed an invalid value to `height` or `width`. Please provide a pixel based unit.\n\n",31:"The animation shorthand only takes 8 arguments. See the specification for more information: http://mdn.io/animation\n\n",32:"To pass multiple animations please supply them in arrays, e.g. animation(['rotate', '2s'], ['move', '1s'])\nTo pass a single animation please supply them in simple values, e.g. animation('rotate', '2s')\n\n",33:"The animation shorthand arrays can only have 8 elements. See the specification for more information: http://mdn.io/animation\n\n",34:"borderRadius expects a radius value as a string or number as the second argument.\n\n",35:'borderRadius expects one of "top", "bottom", "left" or "right" as the first argument.\n\n',36:"Property must be a string value.\n\n",37:"Syntax Error at %s.\n\n",38:"Formula contains a function that needs parentheses at %s.\n\n",39:"Formula is missing closing parenthesis at %s.\n\n",40:"Formula has too many closing parentheses at %s.\n\n",41:"All values in a formula must have the same unit or be unitless.\n\n",42:"Please provide a number of steps to the modularScale helper.\n\n",43:"Please pass a number or one of the predefined scales to the modularScale helper as the ratio.\n\n",44:"Invalid value passed as base to modularScale, expected number or em/rem string but got %s.\n\n",45:"Passed invalid argument to hslToColorString, please pass a HslColor or HslaColor object.\n\n",46:"Passed invalid argument to rgbToColorString, please pass a RgbColor or RgbaColor object.\n\n",47:"minScreen and maxScreen must be provided as stringified numbers with the same units.\n\n",48:"fromSize and toSize must be provided as stringified numbers with the same units.\n\n",49:"Expects either an array of objects or a single object with the properties prop, fromSize, and toSize.\n\n",50:"Expects the objects in the first argument array to have the properties prop, fromSize, and toSize.\n\n",51:"Expects the first argument object to have the properties prop, fromSize, and toSize.\n\n",52:"fontFace expects either the path to the font file(s) or a name of a local copy.\n\n",53:"fontFace expects localFonts to be an array.\n\n",54:"fontFace expects fileFormats to be an array.\n\n",55:"fontFace expects a name of a font-family.\n\n",56:"linearGradient requries at least 2 color-stops to properly render.\n\n",57:"radialGradient requries at least 2 color-stops to properly render.\n\n",58:"Please supply a filename to retinaImage() as the first argument.\n\n",59:"Passed invalid argument to triangle, please pass correct pointingDirection e.g. 'right'.\n\n",60:"Passed an invalid value to `height` or `width`. Please provide a pixel based unit.\n\n",61:"Property must be a string value.\n\n",62:"borderRadius expects a radius value as a string or number as the second argument.\n\n",63:'borderRadius expects one of "top", "bottom", "left" or "right" as the first argument.\n\n',64:"The animation shorthand only takes 8 arguments. See the specification for more information: http://mdn.io/animation.\n\n",65:"To pass multiple animations please supply them in arrays, e.g. animation(['rotate', '2s'], ['move', '1s'])\\nTo pass a single animation please supply them in simple values, e.g. animation('rotate', '2s').\n\n",66:"The animation shorthand arrays can only have 8 elements. See the specification for more information: http://mdn.io/animation.\n\n",67:"You must provide a template to this method.\n\n",68:"You passed an unsupported selector state to this method.\n\n",69:'Expected a string ending in "px" or a number passed as the first argument to %s(), got %s instead.\n\n',70:'Expected a string ending in "px" or a number passed as the second argument to %s(), got %s instead.\n\n',71:'Passed invalid pixel value %s to %s(), please pass a value like "12px" or 12.\n\n',72:'Passed invalid base value %s to %s(), please pass a value like "12px" or 12.\n\n',73:"Please provide a valid CSS variable.\n\n",74:"CSS variable not found and no default was provided.\n\n",75:"important requires a valid style object, got a %s instead.\n\n",76:"fromSize and toSize must be provided as stringified numbers with the same units as minScreen and maxScreen.\n\n",77:'remToPx expects a value in "rem" but you provided it in "%s".\n\n',78:'base must be set in "px" or "%" but you set it in "%s".\n'};function VA(){for(var e=arguments.length,t=new Array(e),s=0;s<e;s++)t[s]=arguments[s];var i,r=t[0],n=[];for(i=1;i<t.length;i+=1)n.push(t[i]);return n.forEach(function(e){r=r.replace(/%[a-z]/,e)}),r}var GA=function(e){function t(t){var s;if("production"===process.env.NODE_ENV)s=e.call(this,"An error occurred. See https://github.com/styled-components/polished/blob/main/src/internalHelpers/errors.md#"+t+" for more information.")||this;else{for(var i=arguments.length,r=new Array(i>1?i-1:0),n=1;n<i;n++)r[n-1]=arguments[n];s=e.call(this,VA.apply(void 0,[zA[t]].concat(r)))||this}return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(s)}return function(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,IA(e,t)}(t,e),t}(kA(Error));function jA(e){return Math.round(255*e)}function $A(e,t,s){return jA(e)+","+jA(t)+","+jA(s)}function WA(e,t,s,i){if(void 0===i&&(i=$A),0===t)return i(s,s,s);var r=(e%360+360)%360/60,n=(1-Math.abs(2*s-1))*t,a=n*(1-Math.abs(r%2-1)),o=0,h=0,l=0;r>=0&&r<1?(o=n,h=a):r>=1&&r<2?(o=a,h=n):r>=2&&r<3?(h=n,l=a):r>=3&&r<4?(h=a,l=n):r>=4&&r<5?(o=a,l=n):r>=5&&r<6&&(o=n,l=a);var u=s-n/2;return i(o+u,h+u,l+u)}var HA={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"00ffff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"0000ff",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"00ffff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"ff00ff",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"639",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"};var qA=/^#[a-fA-F0-9]{6}$/,XA=/^#[a-fA-F0-9]{8}$/,YA=/^#[a-fA-F0-9]{3}$/,KA=/^#[a-fA-F0-9]{4}$/,QA=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,ZA=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,JA=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,eE=/^hsl(?:a)?\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i;function tE(e){if("string"!=typeof e)throw new GA(3);var t=function(e){if("string"!=typeof e)return e;var t=e.toLowerCase();return HA[t]?"#"+HA[t]:e}(e);if(t.match(qA))return{red:parseInt(""+t[1]+t[2],16),green:parseInt(""+t[3]+t[4],16),blue:parseInt(""+t[5]+t[6],16)};if(t.match(XA)){var s=parseFloat((parseInt(""+t[7]+t[8],16)/255).toFixed(2));return{red:parseInt(""+t[1]+t[2],16),green:parseInt(""+t[3]+t[4],16),blue:parseInt(""+t[5]+t[6],16),alpha:s}}if(t.match(YA))return{red:parseInt(""+t[1]+t[1],16),green:parseInt(""+t[2]+t[2],16),blue:parseInt(""+t[3]+t[3],16)};if(t.match(KA)){var i=parseFloat((parseInt(""+t[4]+t[4],16)/255).toFixed(2));return{red:parseInt(""+t[1]+t[1],16),green:parseInt(""+t[2]+t[2],16),blue:parseInt(""+t[3]+t[3],16),alpha:i}}var r=QA.exec(t);if(r)return{red:parseInt(""+r[1],10),green:parseInt(""+r[2],10),blue:parseInt(""+r[3],10)};var n=ZA.exec(t.substring(0,50));if(n)return{red:parseInt(""+n[1],10),green:parseInt(""+n[2],10),blue:parseInt(""+n[3],10),alpha:parseFloat(""+n[4])>1?parseFloat(""+n[4])/100:parseFloat(""+n[4])};var a=JA.exec(t);if(a){var o="rgb("+WA(parseInt(""+a[1],10),parseInt(""+a[2],10)/100,parseInt(""+a[3],10)/100)+")",h=QA.exec(o);if(!h)throw new GA(4,t,o);return{red:parseInt(""+h[1],10),green:parseInt(""+h[2],10),blue:parseInt(""+h[3],10)}}var l=eE.exec(t.substring(0,50));if(l){var u="rgb("+WA(parseInt(""+l[1],10),parseInt(""+l[2],10)/100,parseInt(""+l[3],10)/100)+")",c=QA.exec(u);if(!c)throw new GA(4,t,u);return{red:parseInt(""+c[1],10),green:parseInt(""+c[2],10),blue:parseInt(""+c[3],10),alpha:parseFloat(""+l[4])>1?parseFloat(""+l[4])/100:parseFloat(""+l[4])}}throw new GA(5)}function sE(e){return function(e){var t,s=e.red/255,i=e.green/255,r=e.blue/255,n=Math.max(s,i,r),a=Math.min(s,i,r),o=(n+a)/2;if(n===a)return void 0!==e.alpha?{hue:0,saturation:0,lightness:o,alpha:e.alpha}:{hue:0,saturation:0,lightness:o};var h=n-a,l=o>.5?h/(2-n-a):h/(n+a);switch(n){case s:t=(i-r)/h+(i<r?6:0);break;case i:t=(r-s)/h+2;break;default:t=(s-i)/h+4}return t*=60,void 0!==e.alpha?{hue:t,saturation:l,lightness:o,alpha:e.alpha}:{hue:t,saturation:l,lightness:o}}(tE(e))}var iE=function(e){return 7===e.length&&e[1]===e[2]&&e[3]===e[4]&&e[5]===e[6]?"#"+e[1]+e[3]+e[5]:e};function rE(e){var t=e.toString(16);return 1===t.length?"0"+t:t}function nE(e){return rE(Math.round(255*e))}function aE(e,t,s){return iE("#"+nE(e)+nE(t)+nE(s))}function oE(e,t,s){return WA(e,t,s,aE)}function hE(e,t,s){if("number"==typeof e&&"number"==typeof t&&"number"==typeof s)return iE("#"+rE(e)+rE(t)+rE(s));if("object"==typeof e&&void 0===t&&void 0===s)return iE("#"+rE(e.red)+rE(e.green)+rE(e.blue));throw new GA(6)}function lE(e,t,s,i){if("object"==typeof e&&void 0===t&&void 0===s&&void 0===i)return e.alpha>=1?hE(e.red,e.green,e.blue):"rgba("+e.red+","+e.green+","+e.blue+","+e.alpha+")";throw new GA(7)}function uE(e){if("object"!=typeof e)throw new GA(8);if(function(e){return"number"==typeof e.red&&"number"==typeof e.green&&"number"==typeof e.blue&&"number"==typeof e.alpha}(e))return lE(e);if(function(e){return"number"==typeof e.red&&"number"==typeof e.green&&"number"==typeof e.blue&&("number"!=typeof e.alpha||void 0===e.alpha)}(e))return hE(e);if(function(e){return"number"==typeof e.hue&&"number"==typeof e.saturation&&"number"==typeof e.lightness&&"number"==typeof e.alpha}(e))return function(e,t,s,i){if("object"==typeof e&&void 0===t&&void 0===s&&void 0===i)return e.alpha>=1?oE(e.hue,e.saturation,e.lightness):"rgba("+WA(e.hue,e.saturation,e.lightness)+","+e.alpha+")";throw new GA(2)}(e);if(function(e){return"number"==typeof e.hue&&"number"==typeof e.saturation&&"number"==typeof e.lightness&&("number"!=typeof e.alpha||void 0===e.alpha)}(e))return function(e,t,s){if("object"==typeof e&&void 0===t&&void 0===s)return oE(e.hue,e.saturation,e.lightness);throw new GA(1)}(e);throw new GA(8)}function cE(e,t,s){return function(){var i=s.concat(Array.prototype.slice.call(arguments));return i.length>=t?e.apply(this,i):cE(e,t,i)}}function dE(e){return cE(e,e.length,[])}function pE(e,t,s){return Math.max(e,Math.min(t,s))}dE(function(e,t){if("transparent"===t)return t;var s=sE(t);return uE(DA({},s,{hue:s.hue+parseFloat(e)}))}),dE(function(e,t){if("transparent"===t)return t;var s=sE(t);return uE(DA({},s,{lightness:pE(0,1,s.lightness-parseFloat(e))}))}),dE(function(e,t){if("transparent"===t)return t;var s=sE(t);return uE(DA({},s,{saturation:pE(0,1,s.saturation-parseFloat(e))}))}),dE(function(e,t){if("transparent"===t)return t;var s=sE(t);return uE(DA({},s,{lightness:pE(0,1,s.lightness+parseFloat(e))}))});var mE=dE(function(e,t,s){if("transparent"===t)return s;if("transparent"===s)return t;if(0===e)return s;var i=tE(t),r=DA({},i,{alpha:"number"==typeof i.alpha?i.alpha:1}),n=tE(s),a=DA({},n,{alpha:"number"==typeof n.alpha?n.alpha:1}),o=r.alpha-a.alpha,h=2*parseFloat(e)-1,l=((h*o===-1?h:h+o)/(1+h*o)+1)/2,u=1-l;return lE({red:Math.floor(r.red*l+a.red*u),green:Math.floor(r.green*l+a.green*u),blue:Math.floor(r.blue*l+a.blue*u),alpha:r.alpha*parseFloat(e)+a.alpha*(1-parseFloat(e))})}),gE=mE;var fE=dE(function(e,t){if("transparent"===t)return t;var s=tE(t);return lE(DA({},s,{alpha:pE(0,1,(100*("number"==typeof s.alpha?s.alpha:1)+100*parseFloat(e))/100)}))}),yE=fE;dE(function(e,t){if("transparent"===t)return t;var s=sE(t);return uE(DA({},s,{saturation:pE(0,1,s.saturation+parseFloat(e))}))}),dE(function(e,t){return"transparent"===t?t:uE(DA({},sE(t),{hue:parseFloat(e)}))}),dE(function(e,t){return"transparent"===t?t:uE(DA({},sE(t),{lightness:parseFloat(e)}))}),dE(function(e,t){return"transparent"===t?t:uE(DA({},sE(t),{saturation:parseFloat(e)}))}),dE(function(e,t){return"transparent"===t?t:gE(parseFloat(e),"rgb(0, 0, 0)",t)}),dE(function(e,t){return"transparent"===t?t:gE(parseFloat(e),"rgb(255, 255, 255)",t)}),dE(function(e,t){if("transparent"===t)return t;var s=tE(t);return lE(DA({},s,{alpha:pE(0,1,+(100*("number"==typeof s.alpha?s.alpha:1)-100*parseFloat(e)).toFixed(2)/100)}))});var bE=Object.freeze({Linear:Object.freeze({None:function(e){return e},In:function(e){return e},Out:function(e){return e},InOut:function(e){return e}}),Quadratic:Object.freeze({In:function(e){return e*e},Out:function(e){return e*(2-e)},InOut:function(e){return(e*=2)<1?.5*e*e:-.5*(--e*(e-2)-1)}}),Cubic:Object.freeze({In:function(e){return e*e*e},Out:function(e){return--e*e*e+1},InOut:function(e){return(e*=2)<1?.5*e*e*e:.5*((e-=2)*e*e+2)}}),Quartic:Object.freeze({In:function(e){return e*e*e*e},Out:function(e){return 1- --e*e*e*e},InOut:function(e){return(e*=2)<1?.5*e*e*e*e:-.5*((e-=2)*e*e*e-2)}}),Quintic:Object.freeze({In:function(e){return e*e*e*e*e},Out:function(e){return--e*e*e*e*e+1},InOut:function(e){return(e*=2)<1?.5*e*e*e*e*e:.5*((e-=2)*e*e*e*e+2)}}),Sinusoidal:Object.freeze({In:function(e){return 1-Math.sin((1-e)*Math.PI/2)},Out:function(e){return Math.sin(e*Math.PI/2)},InOut:function(e){return.5*(1-Math.sin(Math.PI*(.5-e)))}}),Exponential:Object.freeze({In:function(e){return 0===e?0:Math.pow(1024,e-1)},Out:function(e){return 1===e?1:1-Math.pow(2,-10*e)},InOut:function(e){return 0===e?0:1===e?1:(e*=2)<1?.5*Math.pow(1024,e-1):.5*(2-Math.pow(2,-10*(e-1)))}}),Circular:Object.freeze({In:function(e){return 1-Math.sqrt(1-e*e)},Out:function(e){return Math.sqrt(1- --e*e)},InOut:function(e){return(e*=2)<1?-.5*(Math.sqrt(1-e*e)-1):.5*(Math.sqrt(1-(e-=2)*e)+1)}}),Elastic:Object.freeze({In:function(e){return 0===e?0:1===e?1:-Math.pow(2,10*(e-1))*Math.sin(5*(e-1.1)*Math.PI)},Out:function(e){return 0===e?0:1===e?1:Math.pow(2,-10*e)*Math.sin(5*(e-.1)*Math.PI)+1},InOut:function(e){return 0===e?0:1===e?1:(e*=2)<1?-.5*Math.pow(2,10*(e-1))*Math.sin(5*(e-1.1)*Math.PI):.5*Math.pow(2,-10*(e-1))*Math.sin(5*(e-1.1)*Math.PI)+1}}),Back:Object.freeze({In:function(e){var t=1.70158;return 1===e?1:e*e*((t+1)*e-t)},Out:function(e){var t=1.70158;return 0===e?0:--e*e*((t+1)*e+t)+1},InOut:function(e){var t=2.5949095;return(e*=2)<1?e*e*((t+1)*e-t)*.5:.5*((e-=2)*e*((t+1)*e+t)+2)}}),Bounce:Object.freeze({In:function(e){return 1-bE.Bounce.Out(1-e)},Out:function(e){return e<1/2.75?7.5625*e*e:e<2/2.75?7.5625*(e-=1.5/2.75)*e+.75:e<2.5/2.75?7.5625*(e-=2.25/2.75)*e+.9375:7.5625*(e-=2.625/2.75)*e+.984375},InOut:function(e){return e<.5?.5*bE.Bounce.In(2*e):.5*bE.Bounce.Out(2*e-1)+.5}}),generatePow:function(e){return void 0===e&&(e=4),e=(e=e<Number.EPSILON?Number.EPSILON:e)>1e4?1e4:e,{In:function(t){return Math.pow(t,e)},Out:function(t){return 1-Math.pow(1-t,e)},InOut:function(t){return t<.5?Math.pow(2*t,e)/2:(1-Math.pow(2-2*t,e))/2+.5}}}}),_E=function(){return performance.now()},xE=function(){function e(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._tweens={},this._tweensAddedDuringUpdate={},this.add.apply(this,e)}return e.prototype.getAll=function(){var e=this;return Object.keys(this._tweens).map(function(t){return e._tweens[t]})},e.prototype.removeAll=function(){this._tweens={}},e.prototype.add=function(){for(var e,t=[],s=0;s<arguments.length;s++)t[s]=arguments[s];for(var i=0,r=t;i<r.length;i++){var n=r[i];null===(e=n._group)||void 0===e||e.remove(n),n._group=this,this._tweens[n.getId()]=n,this._tweensAddedDuringUpdate[n.getId()]=n}},e.prototype.remove=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var s=0,i=e;s<i.length;s++){var r=i[s];r._group=void 0,delete this._tweens[r.getId()],delete this._tweensAddedDuringUpdate[r.getId()]}},e.prototype.allStopped=function(){return this.getAll().every(function(e){return!e.isPlaying()})},e.prototype.update=function(e,t){void 0===e&&(e=_E()),void 0===t&&(t=!0);var s=Object.keys(this._tweens);if(0!==s.length)for(;s.length>0;){this._tweensAddedDuringUpdate={};for(var i=0;i<s.length;i++){var r=this._tweens[s[i]],n=!t;r&&!1===r.update(e,n)&&!t&&this.remove(r)}s=Object.keys(this._tweensAddedDuringUpdate)}},e}(),vE={Linear:function(e,t){var s=e.length-1,i=s*t,r=Math.floor(i),n=vE.Utils.Linear;return t<0?n(e[0],e[1],i):t>1?n(e[s],e[s-1],s-i):n(e[r],e[r+1>s?s:r+1],i-r)},Utils:{Linear:function(e,t,s){return(t-e)*s+e}}},TE=function(){function e(){}return e.nextId=function(){return e._nextId++},e._nextId=0,e}(),SE=new xE,wE=function(){function e(e,t){this._isPaused=!1,this._pauseStart=0,this._valuesStart={},this._valuesEnd={},this._valuesStartRepeat={},this._duration=1e3,this._isDynamic=!1,this._initialRepeat=0,this._repeat=0,this._yoyo=!1,this._isPlaying=!1,this._reversed=!1,this._delayTime=0,this._startTime=0,this._easingFunction=bE.Linear.None,this._interpolationFunction=vE.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=TE.nextId(),this._isChainStopped=!1,this._propertiesAreSetUp=!1,this._goToEnd=!1,this._object=e,"object"==typeof t?(this._group=t,t.add(this)):!0===t&&(this._group=SE,SE.add(this))}return e.prototype.getId=function(){return this._id},e.prototype.isPlaying=function(){return this._isPlaying},e.prototype.isPaused=function(){return this._isPaused},e.prototype.getDuration=function(){return this._duration},e.prototype.to=function(e,t){if(void 0===t&&(t=1e3),this._isPlaying)throw new Error("Can not call Tween.to() while Tween is already started or paused. Stop the Tween first.");return this._valuesEnd=e,this._propertiesAreSetUp=!1,this._duration=t<0?0:t,this},e.prototype.duration=function(e){return void 0===e&&(e=1e3),this._duration=e<0?0:e,this},e.prototype.dynamic=function(e){return void 0===e&&(e=!1),this._isDynamic=e,this},e.prototype.start=function(e,t){if(void 0===e&&(e=_E()),void 0===t&&(t=!1),this._isPlaying)return this;if(this._repeat=this._initialRepeat,this._reversed)for(var s in this._reversed=!1,this._valuesStartRepeat)this._swapEndStartRepeatValues(s),this._valuesStart[s]=this._valuesStartRepeat[s];if(this._isPlaying=!0,this._isPaused=!1,this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._isChainStopped=!1,this._startTime=e,this._startTime+=this._delayTime,!this._propertiesAreSetUp||t){if(this._propertiesAreSetUp=!0,!this._isDynamic){var i={};for(var r in this._valuesEnd)i[r]=this._valuesEnd[r];this._valuesEnd=i}this._setupProperties(this._object,this._valuesStart,this._valuesEnd,this._valuesStartRepeat,t)}return this},e.prototype.startFromCurrentValues=function(e){return this.start(e,!0)},e.prototype._setupProperties=function(e,t,s,i,r){for(var n in s){var a=e[n],o=Array.isArray(a),h=o?"array":typeof a,l=!o&&Array.isArray(s[n]);if("undefined"!==h&&"function"!==h){if(l){if(0===(f=s[n]).length)continue;for(var u=[a],c=0,d=f.length;c<d;c+=1){var p=this._handleRelativeValue(a,f[c]);if(isNaN(p)){l=!1,console.warn("Found invalid interpolation list. Skipping.");break}u.push(p)}l&&(s[n]=u)}if("object"!==h&&!o||!a||l)(void 0===t[n]||r)&&(t[n]=a),o||(t[n]*=1),i[n]=l?s[n].slice().reverse():t[n]||0;else{t[n]=o?[]:{};var m=a;for(var g in m)t[n][g]=m[g];i[n]=o?[]:{};var f=s[n];if(!this._isDynamic){var y={};for(var g in f)y[g]=f[g];s[n]=f=y}this._setupProperties(m,t[n],f,i[n],r)}}}},e.prototype.stop=function(){return this._isChainStopped||(this._isChainStopped=!0,this.stopChainedTweens()),this._isPlaying?(this._isPlaying=!1,this._isPaused=!1,this._onStopCallback&&this._onStopCallback(this._object),this):this},e.prototype.end=function(){return this._goToEnd=!0,this.update(this._startTime+this._duration),this},e.prototype.pause=function(e){return void 0===e&&(e=_E()),this._isPaused||!this._isPlaying||(this._isPaused=!0,this._pauseStart=e),this},e.prototype.resume=function(e){return void 0===e&&(e=_E()),this._isPaused&&this._isPlaying?(this._isPaused=!1,this._startTime+=e-this._pauseStart,this._pauseStart=0,this):this},e.prototype.stopChainedTweens=function(){for(var e=0,t=this._chainedTweens.length;e<t;e++)this._chainedTweens[e].stop();return this},e.prototype.group=function(e){return e?(e.add(this),this):(console.warn("tween.group() without args has been removed, use group.add(tween) instead."),this)},e.prototype.remove=function(){var e;return null===(e=this._group)||void 0===e||e.remove(this),this},e.prototype.delay=function(e){return void 0===e&&(e=0),this._delayTime=e,this},e.prototype.repeat=function(e){return void 0===e&&(e=0),this._initialRepeat=e,this._repeat=e,this},e.prototype.repeatDelay=function(e){return this._repeatDelayTime=e,this},e.prototype.yoyo=function(e){return void 0===e&&(e=!1),this._yoyo=e,this},e.prototype.easing=function(e){return void 0===e&&(e=bE.Linear.None),this._easingFunction=e,this},e.prototype.interpolation=function(e){return void 0===e&&(e=vE.Linear),this._interpolationFunction=e,this},e.prototype.chain=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this._chainedTweens=e,this},e.prototype.onStart=function(e){return this._onStartCallback=e,this},e.prototype.onEveryStart=function(e){return this._onEveryStartCallback=e,this},e.prototype.onUpdate=function(e){return this._onUpdateCallback=e,this},e.prototype.onRepeat=function(e){return this._onRepeatCallback=e,this},e.prototype.onComplete=function(e){return this._onCompleteCallback=e,this},e.prototype.onStop=function(e){return this._onStopCallback=e,this},e.prototype.update=function(t,s){var i,r,n=this;if(void 0===t&&(t=_E()),void 0===s&&(s=e.autoStartOnUpdate),this._isPaused)return!0;if(!this._goToEnd&&!this._isPlaying){if(!s)return!1;this.start(t,!0)}if(this._goToEnd=!1,t<this._startTime)return!0;!1===this._onStartCallbackFired&&(this._onStartCallback&&this._onStartCallback(this._object),this._onStartCallbackFired=!0),!1===this._onEveryStartCallbackFired&&(this._onEveryStartCallback&&this._onEveryStartCallback(this._object),this._onEveryStartCallbackFired=!0);var a=t-this._startTime,o=this._duration+(null!==(i=this._repeatDelayTime)&&void 0!==i?i:this._delayTime),h=this._duration+this._repeat*o,l=function(){if(0===n._duration)return 1;if(a>h)return 1;var e=Math.trunc(a/o),t=a-e*o,s=Math.min(t/n._duration,1);return 0===s&&a===n._duration?1:s}(),u=this._easingFunction(l);if(this._updateProperties(this._object,this._valuesStart,this._valuesEnd,u),this._onUpdateCallback&&this._onUpdateCallback(this._object,l),0===this._duration||a>=this._duration){if(this._repeat>0){var c=Math.min(Math.trunc((a-this._duration)/o)+1,this._repeat);for(r in isFinite(this._repeat)&&(this._repeat-=c),this._valuesStartRepeat)this._yoyo||"string"!=typeof this._valuesEnd[r]||(this._valuesStartRepeat[r]=this._valuesStartRepeat[r]+parseFloat(this._valuesEnd[r])),this._yoyo&&this._swapEndStartRepeatValues(r),this._valuesStart[r]=this._valuesStartRepeat[r];return this._yoyo&&(this._reversed=!this._reversed),this._startTime+=o*c,this._onRepeatCallback&&this._onRepeatCallback(this._object),this._onEveryStartCallbackFired=!1,!0}this._onCompleteCallback&&this._onCompleteCallback(this._object);for(var d=0,p=this._chainedTweens.length;d<p;d++)this._chainedTweens[d].start(this._startTime+this._duration,!1);return this._isPlaying=!1,!1}return!0},e.prototype._updateProperties=function(e,t,s,i){for(var r in s)if(void 0!==t[r]){var n=t[r]||0,a=s[r],o=Array.isArray(e[r]),h=Array.isArray(a);!o&&h?e[r]=this._interpolationFunction(a,i):"object"==typeof a&&a?this._updateProperties(e[r],n,a,i):"number"==typeof(a=this._handleRelativeValue(n,a))&&(e[r]=n+(a-n)*i)}},e.prototype._handleRelativeValue=function(e,t){return"string"!=typeof t?t:"+"===t.charAt(0)||"-"===t.charAt(0)?e+parseFloat(t):parseFloat(t)},e.prototype._swapEndStartRepeatValues=function(e){var t=this._valuesStartRepeat[e],s=this._valuesEnd[e];this._valuesStartRepeat[e]="string"==typeof s?this._valuesStartRepeat[e]+parseFloat(s):this._valuesEnd[e],this._valuesEnd[e]=t},e.autoStartOnUpdate=!1,e}();TE.nextId;var ME=SE;ME.getAll.bind(ME),ME.removeAll.bind(ME),ME.add.bind(ME),ME.remove.bind(ME),ME.update.bind(ME);function NE(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}var AE="object"==typeof global&&global&&global.Object===Object&&global,EE="object"==typeof self&&self&&self.Object===Object&&self,RE=AE||EE||Function("return this")(),CE=function(){return RE.Date.now()},PE=/\s/;var BE=/^\s+/;function FE(e){return e?e.slice(0,function(e){for(var t=e.length;t--&&PE.test(e.charAt(t)););return t}(e)+1).replace(BE,""):e}var LE=RE.Symbol,DE=Object.prototype,IE=DE.hasOwnProperty,OE=DE.toString,UE=LE?LE.toStringTag:void 0;var kE=Object.prototype.toString;var zE=LE?LE.toStringTag:void 0;function VE(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":zE&&zE in Object(e)?function(e){var t=IE.call(e,UE),s=e[UE];try{e[UE]=void 0;var i=!0}catch(e){}var r=OE.call(e);return i&&(t?e[UE]=s:delete e[UE]),r}(e):function(e){return kE.call(e)}(e)}var GE=/^[-+]0x[0-9a-f]+$/i,jE=/^0b[01]+$/i,$E=/^0o[0-7]+$/i,WE=parseInt;function HE(e){if("number"==typeof e)return e;if(function(e){return"symbol"==typeof e||function(e){return null!=e&&"object"==typeof e}(e)&&"[object Symbol]"==VE(e)}(e))return NaN;if(NE(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=NE(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=FE(e);var s=jE.test(e);return s||$E.test(e)?WE(e.slice(2),s?2:8):GE.test(e)?NaN:+e}var qE=Math.max,XE=Math.min;function YE(e,t,s){var i,r,n,a,o,h,l=0,u=!1,c=!1,d=!0;if("function"!=typeof e)throw new TypeError("Expected a function");function p(t){var s=i,n=r;return i=r=void 0,l=t,a=e.apply(n,s)}function m(e){var s=e-h;return void 0===h||s>=t||s<0||c&&e-l>=n}function g(){var e=CE();if(m(e))return f(e);o=setTimeout(g,function(e){var s=t-(e-h);return c?XE(s,n-(e-l)):s}(e))}function f(e){return o=void 0,d&&i?p(e):(i=r=void 0,a)}function y(){var e=CE(),s=m(e);if(i=arguments,r=this,h=e,s){if(void 0===o)return function(e){return l=e,o=setTimeout(g,t),u?p(e):a}(h);if(c)return clearTimeout(o),o=setTimeout(g,t),p(h)}return void 0===o&&(o=setTimeout(g,t)),a}return t=HE(t)||0,NE(s)&&(u=!!s.leading,n=(c="maxWait"in s)?qE(HE(s.maxWait)||0,t):n,d="trailing"in s?!!s.trailing:d),y.cancel=function(){void 0!==o&&clearTimeout(o),l=0,i=h=r=o=void 0},y.flush=function(){return void 0===o?a:f(CE())},y}function KE(e,t){(null==t||t>e.length)&&(t=e.length);for(var s=0,i=Array(t);s<t;s++)i[s]=e[s];return i}function QE(e,t,s){return Object.defineProperty(e,"prototype",{writable:!1}),e}function ZE(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var s=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=s){var i,r,n,a,o=[],h=!0,l=!1;try{if(n=(s=s.call(e)).next,0===t);else for(;!(h=(i=n.call(s)).done)&&(o.push(i.value),o.length!==t);h=!0);}catch(e){l=!0,r=e}finally{try{if(!h&&null!=s.return&&(a=s.return(),Object(a)!==a))return}finally{if(l)throw r}}return o}}(e,t)||function(e,t){if(e){if("string"==typeof e)return KE(e,t);var s={}.toString.call(e).slice(8,-1);return"Object"===s&&e.constructor&&(s=e.constructor.name),"Map"===s||"Set"===s?Array.from(e):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?KE(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}var JE=QE(function e(t,s){var i=s.default,r=void 0===i?null:i,n=s.triggerUpdate,a=void 0===n||n,o=s.onChange,h=void 0===o?function(e,t){}:o;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.name=t,this.defaultVal=r,this.triggerUpdate=a,this.onChange=h});function eR(e){var t=e.stateInit,s=void 0===t?function(){return{}}:t,i=e.props,r=void 0===i?{}:i,n=e.methods,a=void 0===n?{}:n,o=e.aliases,h=void 0===o?{}:o,l=e.init,u=void 0===l?function(){}:l,c=e.update,d=void 0===c?function(){}:c,p=Object.keys(r).map(function(e){return new JE(e,r[e])});return function e(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];var n=!!(this instanceof e?this.constructor:void 0),o=n?i.shift():void 0,l=i[0],c=void 0===l?{}:l,m=Object.assign({},s instanceof Function?s(c):s,{initialised:!1}),g={};function f(e){return y(e,c),b(),f}var y=function(e,t){u.call(f,e,m,t),m.initialised=!0},b=YE(function(){m.initialised&&(d.call(f,m,g),g={})},1);return p.forEach(function(e){f[e.name]=function(e){var t=e.name,s=e.triggerUpdate,i=void 0!==s&&s,r=e.onChange,n=void 0===r?function(e,t){}:r,a=e.defaultVal,o=void 0===a?null:a;return function(e){var s=m[t];if(!arguments.length)return s;var r=void 0===e?o:e;return m[t]=r,n.call(f,r,m,s),!g.hasOwnProperty(t)&&(g[t]=s),i&&b(),f}}(e)}),Object.keys(a).forEach(function(e){f[e]=function(){for(var t,s=arguments.length,i=new Array(s),r=0;r<s;r++)i[r]=arguments[r];return(t=a[e]).call.apply(t,[f,m].concat(i))}}),Object.entries(h).forEach(function(e){var t=ZE(e,2),s=t[0],i=t[1];return f[s]=f[i]}),f.resetProps=function(){return p.forEach(function(e){f[e.name](e.defaultVal)}),f},f.resetProps(),m._rerender=b,n&&o&&f(o),f}}var tR="http://www.w3.org/1999/xhtml",sR={svg:"http://www.w3.org/2000/svg",xhtml:tR,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function iR(e){var t=e+="",s=t.indexOf(":");return s>=0&&"xmlns"!==(t=e.slice(0,s))&&(e=e.slice(s+1)),sR.hasOwnProperty(t)?{space:sR[t],local:e}:e}function rR(e){return function(){var t=this.ownerDocument,s=this.namespaceURI;return s===tR&&t.documentElement.namespaceURI===tR?t.createElement(e):t.createElementNS(s,e)}}function nR(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function aR(e){var t=iR(e);return(t.local?nR:rR)(t)}function oR(){}function hR(e){return null==e?oR:function(){return this.querySelector(e)}}function lR(){return[]}function uR(e){return function(){return function(e){return null==e?[]:Array.isArray(e)?e:Array.from(e)}(e.apply(this,arguments))}}function cR(e){return function(t){return t.matches(e)}}var dR=Array.prototype.find;function pR(){return this.firstElementChild}var mR=Array.prototype.filter;function gR(){return Array.from(this.children)}function fR(e){return new Array(e.length)}function yR(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}function bR(e,t,s,i,r,n){for(var a,o=0,h=t.length,l=n.length;o<l;++o)(a=t[o])?(a.__data__=n[o],i[o]=a):s[o]=new yR(e,n[o]);for(;o<h;++o)(a=t[o])&&(r[o]=a)}function _R(e,t,s,i,r,n,a){var o,h,l,u=new Map,c=t.length,d=n.length,p=new Array(c);for(o=0;o<c;++o)(h=t[o])&&(p[o]=l=a.call(h,h.__data__,o,t)+"",u.has(l)?r[o]=h:u.set(l,h));for(o=0;o<d;++o)l=a.call(e,n[o],o,n)+"",(h=u.get(l))?(i[o]=h,h.__data__=n[o],u.delete(l)):s[o]=new yR(e,n[o]);for(o=0;o<c;++o)(h=t[o])&&u.get(p[o])===h&&(r[o]=h)}function xR(e){return e.__data__}function vR(e){return"object"==typeof e&&"length"in e?e:Array.from(e)}function TR(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function SR(e){return function(){this.removeAttribute(e)}}function wR(e){return function(){this.removeAttributeNS(e.space,e.local)}}function MR(e,t){return function(){this.setAttribute(e,t)}}function NR(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function AR(e,t){return function(){var s=t.apply(this,arguments);null==s?this.removeAttribute(e):this.setAttribute(e,s)}}function ER(e,t){return function(){var s=t.apply(this,arguments);null==s?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,s)}}function RR(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function CR(e){return function(){this.style.removeProperty(e)}}function PR(e,t,s){return function(){this.style.setProperty(e,t,s)}}function BR(e,t,s){return function(){var i=t.apply(this,arguments);null==i?this.style.removeProperty(e):this.style.setProperty(e,i,s)}}function FR(e){return function(){delete this[e]}}function LR(e,t){return function(){this[e]=t}}function DR(e,t){return function(){var s=t.apply(this,arguments);null==s?delete this[e]:this[e]=s}}function IR(e){return e.trim().split(/^|\s+/)}function OR(e){return e.classList||new UR(e)}function UR(e){this._node=e,this._names=IR(e.getAttribute("class")||"")}function kR(e,t){for(var s=OR(e),i=-1,r=t.length;++i<r;)s.add(t[i])}function zR(e,t){for(var s=OR(e),i=-1,r=t.length;++i<r;)s.remove(t[i])}function VR(e){return function(){kR(this,e)}}function GR(e){return function(){zR(this,e)}}function jR(e,t){return function(){(t.apply(this,arguments)?kR:zR)(this,e)}}function $R(){this.textContent=""}function WR(e){return function(){this.textContent=e}}function HR(e){return function(){var t=e.apply(this,arguments);this.textContent=null==t?"":t}}function qR(){this.innerHTML=""}function XR(e){return function(){this.innerHTML=e}}function YR(e){return function(){var t=e.apply(this,arguments);this.innerHTML=null==t?"":t}}function KR(){this.nextSibling&&this.parentNode.appendChild(this)}function QR(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function ZR(){return null}function JR(){var e=this.parentNode;e&&e.removeChild(this)}function eC(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function tC(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function sC(e){return function(){var t=this.__on;if(t){for(var s,i=0,r=-1,n=t.length;i<n;++i)s=t[i],e.type&&s.type!==e.type||s.name!==e.name?t[++r]=s:this.removeEventListener(s.type,s.listener,s.options);++r?t.length=r:delete this.__on}}}function iC(e,t,s){return function(){var i,r=this.__on,n=function(e){return function(t){e.call(this,t,this.__data__)}}(t);if(r)for(var a=0,o=r.length;a<o;++a)if((i=r[a]).type===e.type&&i.name===e.name)return this.removeEventListener(i.type,i.listener,i.options),this.addEventListener(i.type,i.listener=n,i.options=s),void(i.value=t);this.addEventListener(e.type,n,s),i={type:e.type,name:e.name,value:t,listener:n,options:s},r?r.push(i):this.__on=[i]}}function rC(e,t,s){var i=RR(e),r=i.CustomEvent;"function"==typeof r?r=new r(t,s):(r=i.document.createEvent("Event"),s?(r.initEvent(t,s.bubbles,s.cancelable),r.detail=s.detail):r.initEvent(t,!1,!1)),e.dispatchEvent(r)}function nC(e,t){return function(){return rC(this,e,t)}}function aC(e,t){return function(){return rC(this,e,t.apply(this,arguments))}}yR.prototype={constructor:yR,appendChild:function(e){return this._parent.insertBefore(e,this._next)},insertBefore:function(e,t){return this._parent.insertBefore(e,t)},querySelector:function(e){return this._parent.querySelector(e)},querySelectorAll:function(e){return this._parent.querySelectorAll(e)}},UR.prototype={add:function(e){this._names.indexOf(e)<0&&(this._names.push(e),this._node.setAttribute("class",this._names.join(" ")))},remove:function(e){var t=this._names.indexOf(e);t>=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(e){return this._names.indexOf(e)>=0}};var oC=[null];function hC(e,t){this._groups=e,this._parents=t}hC.prototype={constructor:hC,select:function(e){"function"!=typeof e&&(e=hR(e));for(var t=this._groups,s=t.length,i=new Array(s),r=0;r<s;++r)for(var n,a,o=t[r],h=o.length,l=i[r]=new Array(h),u=0;u<h;++u)(n=o[u])&&(a=e.call(n,n.__data__,u,o))&&("__data__"in n&&(a.__data__=n.__data__),l[u]=a);return new hC(i,this._parents)},selectAll:function(e){e="function"==typeof e?uR(e):function(e){return null==e?lR:function(){return this.querySelectorAll(e)}}(e);for(var t=this._groups,s=t.length,i=[],r=[],n=0;n<s;++n)for(var a,o=t[n],h=o.length,l=0;l<h;++l)(a=o[l])&&(i.push(e.call(a,a.__data__,l,o)),r.push(a));return new hC(i,r)},selectChild:function(e){return this.select(null==e?pR:function(e){return function(){return dR.call(this.children,e)}}("function"==typeof e?e:cR(e)))},selectChildren:function(e){return this.selectAll(null==e?gR:function(e){return function(){return mR.call(this.children,e)}}("function"==typeof e?e:cR(e)))},filter:function(e){"function"!=typeof e&&(e=function(e){return function(){return this.matches(e)}}(e));for(var t=this._groups,s=t.length,i=new Array(s),r=0;r<s;++r)for(var n,a=t[r],o=a.length,h=i[r]=[],l=0;l<o;++l)(n=a[l])&&e.call(n,n.__data__,l,a)&&h.push(n);return new hC(i,this._parents)},data:function(e,t){if(!arguments.length)return Array.from(this,xR);var s=t?_R:bR,i=this._parents,r=this._groups;"function"!=typeof e&&(e=function(e){return function(){return e}}(e));for(var n=r.length,a=new Array(n),o=new Array(n),h=new Array(n),l=0;l<n;++l){var u=i[l],c=r[l],d=c.length,p=vR(e.call(u,u&&u.__data__,l,i)),m=p.length,g=o[l]=new Array(m),f=a[l]=new Array(m);s(u,c,g,f,h[l]=new Array(d),p,t);for(var y,b,_=0,x=0;_<m;++_)if(y=g[_]){for(_>=x&&(x=_+1);!(b=f[x])&&++x<m;);y._next=b||null}}return(a=new hC(a,i))._enter=o,a._exit=h,a},enter:function(){return new hC(this._enter||this._groups.map(fR),this._parents)},exit:function(){return new hC(this._exit||this._groups.map(fR),this._parents)},join:function(e,t,s){var i=this.enter(),r=this,n=this.exit();return"function"==typeof e?(i=e(i))&&(i=i.selection()):i=i.append(e+""),null!=t&&(r=t(r))&&(r=r.selection()),null==s?n.remove():s(n),i&&r?i.merge(r).order():r},merge:function(e){for(var t=e.selection?e.selection():e,s=this._groups,i=t._groups,r=s.length,n=i.length,a=Math.min(r,n),o=new Array(r),h=0;h<a;++h)for(var l,u=s[h],c=i[h],d=u.length,p=o[h]=new Array(d),m=0;m<d;++m)(l=u[m]||c[m])&&(p[m]=l);for(;h<r;++h)o[h]=s[h];return new hC(o,this._parents)},selection:function(){return this},order:function(){for(var e=this._groups,t=-1,s=e.length;++t<s;)for(var i,r=e[t],n=r.length-1,a=r[n];--n>=0;)(i=r[n])&&(a&&4^i.compareDocumentPosition(a)&&a.parentNode.insertBefore(i,a),a=i);return this},sort:function(e){function t(t,s){return t&&s?e(t.__data__,s.__data__):!t-!s}e||(e=TR);for(var s=this._groups,i=s.length,r=new Array(i),n=0;n<i;++n){for(var a,o=s[n],h=o.length,l=r[n]=new Array(h),u=0;u<h;++u)(a=o[u])&&(l[u]=a);l.sort(t)}return new hC(r,this._parents).order()},call:function(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this},nodes:function(){return Array.from(this)},node:function(){for(var e=this._groups,t=0,s=e.length;t<s;++t)for(var i=e[t],r=0,n=i.length;r<n;++r){var a=i[r];if(a)return a}return null},size:function(){let e=0;for(const t of this)++e;return e},empty:function(){return!this.node()},each:function(e){for(var t=this._groups,s=0,i=t.length;s<i;++s)for(var r,n=t[s],a=0,o=n.length;a<o;++a)(r=n[a])&&e.call(r,r.__data__,a,n);return this},attr:function(e,t){var s=iR(e);if(arguments.length<2){var i=this.node();return s.local?i.getAttributeNS(s.space,s.local):i.getAttribute(s)}return this.each((null==t?s.local?wR:SR:"function"==typeof t?s.local?ER:AR:s.local?NR:MR)(s,t))},style:function(e,t,s){return arguments.length>1?this.each((null==t?CR:"function"==typeof t?BR:PR)(e,t,null==s?"":s)):function(e,t){return e.style.getPropertyValue(t)||RR(e).getComputedStyle(e,null).getPropertyValue(t)}(this.node(),e)},property:function(e,t){return arguments.length>1?this.each((null==t?FR:"function"==typeof t?DR:LR)(e,t)):this.node()[e]},classed:function(e,t){var s=IR(e+"");if(arguments.length<2){for(var i=OR(this.node()),r=-1,n=s.length;++r<n;)if(!i.contains(s[r]))return!1;return!0}return this.each(("function"==typeof t?jR:t?VR:GR)(s,t))},text:function(e){return arguments.length?this.each(null==e?$R:("function"==typeof e?HR:WR)(e)):this.node().textContent},html:function(e){return arguments.length?this.each(null==e?qR:("function"==typeof e?YR:XR)(e)):this.node().innerHTML},raise:function(){return this.each(KR)},lower:function(){return this.each(QR)},append:function(e){var t="function"==typeof e?e:aR(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})},insert:function(e,t){var s="function"==typeof e?e:aR(e),i=null==t?ZR:"function"==typeof t?t:hR(t);return this.select(function(){return this.insertBefore(s.apply(this,arguments),i.apply(this,arguments)||null)})},remove:function(){return this.each(JR)},clone:function(e){return this.select(e?tC:eC)},datum:function(e){return arguments.length?this.property("__data__",e):this.node().__data__},on:function(e,t,s){var i,r,n=function(e){return e.trim().split(/^|\s+/).map(function(e){var t="",s=e.indexOf(".");return s>=0&&(t=e.slice(s+1),e=e.slice(0,s)),{type:e,name:t}})}(e+""),a=n.length;if(!(arguments.length<2)){for(o=t?iC:sC,i=0;i<a;++i)this.each(o(n[i],t,s));return this}var o=this.node().__on;if(o)for(var h,l=0,u=o.length;l<u;++l)for(i=0,h=o[l];i<a;++i)if((r=n[i]).type===h.type&&r.name===h.name)return h.value},dispatch:function(e,t){return this.each(("function"==typeof t?aC:nC)(e,t))},[Symbol.iterator]:function*(){for(var e=this._groups,t=0,s=e.length;t<s;++t)for(var i,r=e[t],n=0,a=r.length;n<a;++n)(i=r[n])&&(yield i)}};var lC,uC,cC,dC,pC,mC,gC,fC,yC,bC,_C,xC,vC,TC,SC,wC={},MC=[],NC=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,AC=Array.isArray;function EC(e,t){for(var s in t)e[s]=t[s];return e}function RC(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function CC(e,t,s,i,r){var n={type:e,props:t,key:s,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:null==r?++cC:r,__i:-1,__u:0};return null==r&&null!=uC.vnode&&uC.vnode(n),n}function PC(e){return e.children}function BC(e,t){this.props=e,this.context=t}function FC(e,t){if(null==t)return e.__?FC(e.__,e.__i+1):null;for(var s;t<e.__k.length;t++)if(null!=(s=e.__k[t])&&null!=s.__e)return s.__e;return"function"==typeof e.type?FC(e):null}function LC(e){if(e.__P&&e.__d){var t=e.__v,s=t.__e,i=[],r=[],n=EC({},t);n.__v=t.__v+1,uC.vnode&&uC.vnode(n),WC(e.__P,n,t,e.__n,e.__P.namespaceURI,32&t.__u?[s]:null,i,null==s?FC(t):s,!!(32&t.__u),r),n.__v=t.__v,n.__.__k[n.__i]=n,qC(i,n,r),t.__e=t.__=null,n.__e!=s&&DC(n)}}function DC(e){if(null!=(e=e.__)&&null!=e.__c)return e.__e=e.__c.base=null,e.__k.some(function(t){if(null!=t&&null!=t.__e)return e.__e=e.__c.base=t.__e}),DC(e)}function IC(e){(!e.__d&&(e.__d=!0)&&pC.push(e)&&!OC.__r++||mC!=uC.debounceRendering)&&((mC=uC.debounceRendering)||gC)(OC)}function OC(){try{for(var e,t=1;pC.length;)pC.length>t&&pC.sort(fC),e=pC.shift(),t=pC.length,LC(e)}finally{pC.length=OC.__r=0}}function UC(e,t,s,i,r,n,a,o,h,l,u){var c,d,p,m,g,f,y,b=i&&i.__k||MC,_=t.length;for(h=kC(s,t,b,h,_),c=0;c<_;c++)null!=(p=s.__k[c])&&(d=-1!=p.__i&&b[p.__i]||wC,p.__i=c,f=WC(e,p,d,r,n,a,o,h,l,u),m=p.__e,p.ref&&d.ref!=p.ref&&(d.ref&&KC(d.ref,null,p),u.push(p.ref,p.__c||m,p)),null==g&&null!=m&&(g=m),(y=!!(4&p.__u))||d.__k===p.__k?(h=zC(p,h,e,y),y&&d.__e&&(d.__e=null)):"function"==typeof p.type&&void 0!==f?h=f:m&&(h=m.nextSibling),p.__u&=-7);return s.__e=g,h}function kC(e,t,s,i,r){var n,a,o,h,l,u=s.length,c=u,d=0;for(e.__k=new Array(r),n=0;n<r;n++)null!=(a=t[n])&&"boolean"!=typeof a&&"function"!=typeof a?("string"==typeof a||"number"==typeof a||"bigint"==typeof a||a.constructor==String?a=e.__k[n]=CC(null,a,null,null,null):AC(a)?a=e.__k[n]=CC(PC,{children:a},null,null,null):void 0===a.constructor&&a.__b>0?a=e.__k[n]=CC(a.type,a.props,a.key,a.ref?a.ref:null,a.__v):e.__k[n]=a,h=n+d,a.__=e,a.__b=e.__b+1,o=null,-1!=(l=a.__i=VC(a,s,h,c))&&(c--,(o=s[l])&&(o.__u|=2)),null==o||null==o.__v?(-1==l&&(r>u?d--:r<u&&d++),"function"!=typeof a.type&&(a.__u|=4)):l!=h&&(l==h-1?d--:l==h+1?d++:(l>h?d--:d++,a.__u|=4))):e.__k[n]=null;if(c)for(n=0;n<u;n++)null!=(o=s[n])&&!(2&o.__u)&&(o.__e==i&&(i=FC(o)),QC(o,o));return i}function zC(e,t,s,i){var r,n;if("function"==typeof e.type){for(r=e.__k,n=0;r&&n<r.length;n++)r[n]&&(r[n].__=e,t=zC(r[n],t,s,i));return t}e.__e!=t&&(i&&(t&&e.type&&!t.parentNode&&(t=FC(e)),s.insertBefore(e.__e,t||null)),t=e.__e);do{t=t&&t.nextSibling}while(null!=t&&8==t.nodeType);return t}function VC(e,t,s,i){var r,n,a,o=e.key,h=e.type,l=t[s],u=null!=l&&!(2&l.__u);if(null===l&&null==o||u&&o==l.key&&h==l.type)return s;if(i>(u?1:0))for(r=s-1,n=s+1;r>=0||n<t.length;)if(null!=(l=t[a=r>=0?r--:n++])&&!(2&l.__u)&&o==l.key&&h==l.type)return a;return-1}function GC(e,t,s){"-"==t[0]?e.setProperty(t,null==s?"":s):e[t]=null==s?"":"number"!=typeof s||NC.test(t)?s:s+"px"}function jC(e,t,s,i,r){var n,a;e:if("style"==t)if("string"==typeof s)e.style.cssText=s;else{if("string"==typeof i&&(e.style.cssText=i=""),i)for(t in i)s&&t in s||GC(e.style,t,"");if(s)for(t in s)i&&s[t]==i[t]||GC(e.style,t,s[t])}else if("o"==t[0]&&"n"==t[1])n=t!=(t=t.replace(xC,"$1")),a=t.toLowerCase(),t=a in e||"onFocusOut"==t||"onFocusIn"==t?a.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+n]=s,s?i?s[_C]=i[_C]:(s[_C]=vC,e.addEventListener(t,n?SC:TC,n)):e.removeEventListener(t,n?SC:TC,n);else{if("http://www.w3.org/2000/svg"==r)t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if("width"!=t&&"height"!=t&&"href"!=t&&"list"!=t&&"form"!=t&&"tabIndex"!=t&&"download"!=t&&"rowSpan"!=t&&"colSpan"!=t&&"role"!=t&&"popover"!=t&&t in e)try{e[t]=null==s?"":s;break e}catch(e){}"function"==typeof s||(null==s||!1===s&&"-"!=t[4]?e.removeAttribute(t):e.setAttribute(t,"popover"==t&&1==s?"":s))}}function $C(e){return function(t){if(this.l){var s=this.l[t.type+e];if(null==t[bC])t[bC]=vC++;else if(t[bC]<s[_C])return;return s(uC.event?uC.event(t):t)}}}function WC(e,t,s,i,r,n,a,o,h,l){var u,c,d,p,m,g,f,y,b,_,x,v,T,S,w,M=t.type;if(void 0!==t.constructor)return null;128&s.__u&&(h=!!(32&s.__u),n=[o=t.__e=s.__e]),(u=uC.__b)&&u(t);e:if("function"==typeof M)try{if(y=t.props,b=M.prototype&&M.prototype.render,_=(u=M.contextType)&&i[u.__c],x=u?_?_.props.value:u.__:i,s.__c?f=(c=t.__c=s.__c).__=c.__E:(b?t.__c=c=new M(y,x):(t.__c=c=new BC(y,x),c.constructor=M,c.render=ZC),_&&_.sub(c),c.state||(c.state={}),c.__n=i,d=c.__d=!0,c.__h=[],c._sb=[]),b&&null==c.__s&&(c.__s=c.state),b&&null!=M.getDerivedStateFromProps&&(c.__s==c.state&&(c.__s=EC({},c.__s)),EC(c.__s,M.getDerivedStateFromProps(y,c.__s))),p=c.props,m=c.state,c.__v=t,d)b&&null==M.getDerivedStateFromProps&&null!=c.componentWillMount&&c.componentWillMount(),b&&null!=c.componentDidMount&&c.__h.push(c.componentDidMount);else{if(b&&null==M.getDerivedStateFromProps&&y!==p&&null!=c.componentWillReceiveProps&&c.componentWillReceiveProps(y,x),t.__v==s.__v||!c.__e&&null!=c.shouldComponentUpdate&&!1===c.shouldComponentUpdate(y,c.__s,x)){t.__v!=s.__v&&(c.props=y,c.state=c.__s,c.__d=!1),t.__e=s.__e,t.__k=s.__k,t.__k.some(function(e){e&&(e.__=t)}),MC.push.apply(c.__h,c._sb),c._sb=[],c.__h.length&&a.push(c);break e}null!=c.componentWillUpdate&&c.componentWillUpdate(y,c.__s,x),b&&null!=c.componentDidUpdate&&c.__h.push(function(){c.componentDidUpdate(p,m,g)})}if(c.context=x,c.props=y,c.__P=e,c.__e=!1,v=uC.__r,T=0,b)c.state=c.__s,c.__d=!1,v&&v(t),u=c.render(c.props,c.state,c.context),MC.push.apply(c.__h,c._sb),c._sb=[];else do{c.__d=!1,v&&v(t),u=c.render(c.props,c.state,c.context),c.state=c.__s}while(c.__d&&++T<25);c.state=c.__s,null!=c.getChildContext&&(i=EC(EC({},i),c.getChildContext())),b&&!d&&null!=c.getSnapshotBeforeUpdate&&(g=c.getSnapshotBeforeUpdate(p,m)),S=null!=u&&u.type===PC&&null==u.key?XC(u.props.children):u,o=UC(e,AC(S)?S:[S],t,s,i,r,n,a,o,h,l),c.base=t.__e,t.__u&=-161,c.__h.length&&a.push(c),f&&(c.__E=c.__=null)}catch(e){if(t.__v=null,h||null!=n)if(e.then){for(t.__u|=h?160:128;o&&8==o.nodeType&&o.nextSibling;)o=o.nextSibling;n[n.indexOf(o)]=null,t.__e=o}else{for(w=n.length;w--;)RC(n[w]);HC(t)}else t.__e=s.__e,t.__k=s.__k,e.then||HC(t);uC.__e(e,t,s)}else null==n&&t.__v==s.__v?(t.__k=s.__k,t.__e=s.__e):o=t.__e=YC(s.__e,t,s,i,r,n,a,h,l);return(u=uC.diffed)&&u(t),128&t.__u?void 0:o}function HC(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(HC))}function qC(e,t,s){for(var i=0;i<s.length;i++)KC(s[i],s[++i],s[++i]);uC.__c&&uC.__c(t,e),e.some(function(t){try{e=t.__h,t.__h=[],e.some(function(e){e.call(t)})}catch(e){uC.__e(e,t.__v)}})}function XC(e){return"object"!=typeof e||null==e||e.__b>0?e:AC(e)?e.map(XC):EC({},e)}function YC(e,t,s,i,r,n,a,o,h){var l,u,c,d,p,m,g,f=s.props||wC,y=t.props,b=t.type;if("svg"==b?r="http://www.w3.org/2000/svg":"math"==b?r="http://www.w3.org/1998/Math/MathML":r||(r="http://www.w3.org/1999/xhtml"),null!=n)for(l=0;l<n.length;l++)if((p=n[l])&&"setAttribute"in p==!!b&&(b?p.localName==b:3==p.nodeType)){e=p,n[l]=null;break}if(null==e){if(null==b)return document.createTextNode(y);e=document.createElementNS(r,b,y.is&&y),o&&(uC.__m&&uC.__m(t,n),o=!1),n=null}if(null==b)f===y||o&&e.data==y||(e.data=y);else{if(n=n&&lC.call(e.childNodes),!o&&null!=n)for(f={},l=0;l<e.attributes.length;l++)f[(p=e.attributes[l]).name]=p.value;for(l in f)p=f[l],"dangerouslySetInnerHTML"==l?c=p:"children"==l||l in y||"value"==l&&"defaultValue"in y||"checked"==l&&"defaultChecked"in y||jC(e,l,null,p,r);for(l in y)p=y[l],"children"==l?d=p:"dangerouslySetInnerHTML"==l?u=p:"value"==l?m=p:"checked"==l?g=p:o&&"function"!=typeof p||f[l]===p||jC(e,l,p,f[l],r);if(u)o||c&&(u.__html==c.__html||u.__html==e.innerHTML)||(e.innerHTML=u.__html),t.__k=[];else if(c&&(e.innerHTML=""),UC("template"==t.type?e.content:e,AC(d)?d:[d],t,s,i,"foreignObject"==b?"http://www.w3.org/1999/xhtml":r,n,a,n?n[0]:s.__k&&FC(s,0),o,h),null!=n)for(l=n.length;l--;)RC(n[l]);o||(l="value","progress"==b&&null==m?e.removeAttribute("value"):null!=m&&(m!==e[l]||"progress"==b&&!m||"option"==b&&m!=f[l])&&jC(e,l,m,f[l],r),l="checked",null!=g&&g!=e[l]&&jC(e,l,g,f[l],r))}return e}function KC(e,t,s){try{if("function"==typeof e){var i="function"==typeof e.__u;i&&e.__u(),i&&null==t||(e.__u=e(t))}else e.current=t}catch(e){uC.__e(e,s)}}function QC(e,t,s){var i,r;if(uC.unmount&&uC.unmount(e),(i=e.ref)&&(i.current&&i.current!=e.__e||KC(i,null,t)),null!=(i=e.__c)){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(e){uC.__e(e,t)}i.base=i.__P=null}if(i=e.__k)for(r=0;r<i.length;r++)i[r]&&QC(i[r],t,s||"function"!=typeof e.type);s||RC(e.__e),e.__c=e.__=e.__e=void 0}function ZC(e,t,s){return this.constructor(e,s)}function JC(e,t,s){var i,r,n;t==document&&(t=document.documentElement),uC.__&&uC.__(e,t),i=!1?null:t.__k,r=[],n=[],WC(t,e=t.__k=function(e,t,s){var i,r,n,a={};for(n in t)"key"==n?i=t[n]:"ref"==n?r=t[n]:a[n]=t[n];if(arguments.length>2&&(a.children=arguments.length>3?lC.call(arguments,2):s),"function"==typeof e&&null!=e.defaultProps)for(n in e.defaultProps)void 0===a[n]&&(a[n]=e.defaultProps[n]);return CC(e,a,i,r,null)}(PC,null,[e]),i||wC,wC,t.namespaceURI,i?null:t.firstChild?lC.call(t.childNodes):null,r,i?i.__e:t.firstChild,false,n),qC(r,e,n)}function eP(e,t,s){var i,r,n,a,o=EC({},e.props);for(n in e.type&&e.type.defaultProps&&(a=e.type.defaultProps),t)"key"==n?i=t[n]:"ref"==n?r=t[n]:o[n]=void 0===t[n]&&null!=a?a[n]:t[n];return arguments.length>2&&(o.children=arguments.length>3?lC.call(arguments,2):s),CC(e.type,o,i||e.key,r||e.ref,null)}function tP(e,t){(null==t||t>e.length)&&(t=e.length);for(var s=0,i=Array(t);s<t;s++)i[s]=e[s];return i}function sP(e,t,s){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var s=e[Symbol.toPrimitive];if(void 0!==s){var i=s.call(e,t);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function iP(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),s.push.apply(s,i)}return s}function rP(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var s=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=s){var i,r,n,a,o=[],h=!0,l=!1;try{if(n=(s=s.call(e)).next,0===t);else for(;!(h=(i=n.call(s)).done)&&(o.push(i.value),o.length!==t);h=!0);}catch(e){l=!0,r=e}finally{try{if(!h&&null!=s.return&&(a=s.return(),Object(a)!==a))return}finally{if(l)throw r}}return o}}(e,t)||function(e,t){if(e){if("string"==typeof e)return tP(e,t);var s={}.toString.call(e).slice(8,-1);return"Object"===s&&e.constructor&&(s=e.constructor.name),"Map"===s||"Set"===s?Array.from(e):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?tP(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function nP(e){return nP="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},nP(e)}lC=MC.slice,uC={__e:function(e,t,s,i){for(var r,n,a;t=t.__;)if((r=t.__c)&&!r.__)try{if((n=r.constructor)&&null!=n.getDerivedStateFromError&&(r.setState(n.getDerivedStateFromError(e)),a=r.__d),null!=r.componentDidCatch&&(r.componentDidCatch(e,i||{}),a=r.__d),a)return r.__E=r}catch(t){e=t}throw e}},cC=0,dC=function(e){return null!=e&&void 0===e.constructor},BC.prototype.setState=function(e,t){var s;s=null!=this.__s&&this.__s!=this.state?this.__s:this.__s=EC({},this.state),"function"==typeof e&&(e=e(EC({},s),this.props)),e&&EC(s,e),null!=e&&this.__v&&(t&&this._sb.push(t),IC(this))},BC.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),IC(this))},BC.prototype.render=PC,pC=[],gC="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,fC=function(e,t){return e.__v.__b-t.__v.__b},OC.__r=0,yC=Math.random().toString(8),bC="__d"+yC,_C="__a"+yC,xC=/(PointerCapture)$|Capture$/i,vC=0,TC=$C(!1),SC=$C(!0);var aP=function(e){if("object"!==nP(e))return e;var t,s=eP(e);s.props&&(s.props=function(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?iP(Object(s),!0).forEach(function(t){sP(e,t,s[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):iP(Object(s)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))})}return e}({},s.props),null!=s&&null!==(t=s.props)&&void 0!==t&&t.children&&(s.props.children=Array.isArray(s.props.children)?s.props.children.map(aP):aP(s.props.children)));return s};!function(e,t){void 0===t&&(t={});var s=t.insertAt;if("undefined"!=typeof document){var i=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css","top"===s&&i.firstChild?i.insertBefore(r,i.firstChild):i.appendChild(r),r.styleSheet?r.styleSheet.cssText=e:r.appendChild(document.createTextNode(e))}}(".float-tooltip-kap {\n position: absolute;\n width: max-content; /* prevent shrinking near right edge */\n max-width: max(50%, 150px);\n padding: 3px 5px;\n border-radius: 3px;\n font: 12px sans-serif;\n color: #eee;\n background: rgba(0,0,0,0.6);\n pointer-events: none;\n}\n");var oP=eR({props:{content:{default:!1},offsetX:{triggerUpdate:!1},offsetY:{triggerUpdate:!1}},init:function(e,t){var s=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).style,i=void 0===s?{}:s,r=function(e){return"string"==typeof e?new hC([[document.querySelector(e)]],[document.documentElement]):new hC([[e]],oC)}(!!e&&"object"===nP(e)&&!!e.node&&"function"==typeof e.node?e.node():e);"static"===r.style("position")&&r.style("position","relative"),t.tooltipEl=r.append("div").attr("class","float-tooltip-kap"),Object.entries(i).forEach(function(e){var s=rP(e,2),i=s[0],r=s[1];return t.tooltipEl.style(i,r)}),t.tooltipEl.style("left","-10000px").style("display","none");var n="tooltip-".concat(Math.round(1e12*Math.random()));t.mouseInside=!1,r.on("mousemove.".concat(n),function(e){t.mouseInside=!0;var s=function(e,t){if(e=function(e){let t;for(;t=e.sourceEvent;)e=t;return e}(e),void 0===t&&(t=e.currentTarget),t){var s=t.ownerSVGElement||t;if(s.createSVGPoint){var i=s.createSVGPoint();return i.x=e.clientX,i.y=e.clientY,[(i=i.matrixTransform(t.getScreenCTM().inverse())).x,i.y]}if(t.getBoundingClientRect){var r=t.getBoundingClientRect();return[e.clientX-r.left-t.clientLeft,e.clientY-r.top-t.clientTop]}}return[e.pageX,e.pageY]}(e),i=r.node(),n=i.offsetWidth,a=i.offsetHeight,o=[null===t.offsetX||void 0===t.offsetX?"-".concat(s[0]/n*100,"%"):"number"==typeof t.offsetX?"calc(-50% + ".concat(t.offsetX,"px)"):t.offsetX,null===t.offsetY||void 0===t.offsetY?a>130&&a-s[1]<100?"calc(-100% - 6px)":"21px":"number"==typeof t.offsetY?t.offsetY<0?"calc(-100% - ".concat(Math.abs(t.offsetY),"px)"):"".concat(t.offsetY,"px"):t.offsetY];t.tooltipEl.style("left",s[0]+"px").style("top",s[1]+"px").style("transform","translate(".concat(o.join(","),")")),t.content&&t.tooltipEl.style("display","inline")}),r.on("mouseover.".concat(n),function(){t.mouseInside=!0,t.content&&t.tooltipEl.style("display","inline")}),r.on("mouseout.".concat(n),function(){t.mouseInside=!1,t.tooltipEl.style("display","none")})},update:function(e){var t,s;e.tooltipEl.style("display",e.content&&e.mouseInside?"inline":"none"),e.content?e.content instanceof HTMLElement?(e.tooltipEl.text(""),e.tooltipEl.append(function(){return e.content})):"string"==typeof e.content?e.tooltipEl.html(e.content):!function(e){return dC(eP(e))}(e.content)?(e.tooltipEl.style("display","none"),console.warn("Tooltip content is invalid, skipping.",e.content,e.content.toString())):(e.tooltipEl.text(""),t=e.content,delete(s=e.tooltipEl.node()).__k,JC(aP(t),s)):e.tooltipEl.text("")}}),hP=function(e){e instanceof Array?e.forEach(hP):(e.map&&e.map.dispose(),e.dispose())},lP=function(e){e.geometry&&e.geometry.dispose(),e.material&&hP(e.material),e.texture&&e.texture.dispose(),e.children&&e.children.forEach(lP)},uP=window.THREE?window.THREE:{WebGLRenderer:e.WebGLRenderer,Scene:e.Scene,PerspectiveCamera:e.PerspectiveCamera,Raycaster:e.Raycaster,SRGBColorSpace:e.SRGBColorSpace,TextureLoader:e.TextureLoader,Vector2:e.Vector2,Vector3:e.Vector3,Box3:e.Box3,Color:e.Color,Mesh:e.Mesh,SphereGeometry:e.SphereGeometry,MeshBasicMaterial:e.MeshBasicMaterial,BackSide:e.BackSide,Timer:e.Timer},cP=eR({props:{width:{default:window.innerWidth,onChange:function(e,t,s){isNaN(e)&&(t.width=s)}},height:{default:window.innerHeight,onChange:function(e,t,s){isNaN(e)&&(t.height=s)}},viewOffset:{default:[0,0]},backgroundColor:{default:"#000011"},backgroundImageUrl:{},onBackgroundImageLoaded:{},showNavInfo:{default:!0},skyRadius:{default:5e4},objects:{default:[]},lights:{default:[]},enablePointerInteraction:{default:!0,onChange:function(e,t){t.hoverObj=null,t.tooltip&&t.tooltip.content(null)},triggerUpdate:!1},pointerRaycasterThrottleMs:{default:50,triggerUpdate:!1},lineHoverPrecision:{default:1,triggerUpdate:!1},pointsHoverPrecision:{default:1,triggerUpdate:!1},hoverOrderComparator:{triggerUpdate:!1},hoverFilter:{default:function(){return!0},triggerUpdate:!1},tooltipContent:{triggerUpdate:!1},hoverDuringDrag:{default:!1,triggerUpdate:!1},clickAfterDrag:{default:!1,triggerUpdate:!1},onHover:{default:function(){},triggerUpdate:!1},onClick:{default:function(){},triggerUpdate:!1},onRightClick:{triggerUpdate:!1}},methods:{tick:function(e){if(e.initialised){e.controls.enabled&&e.controls.update&&e.controls.update(Math.min(1,e.timer.update().getDelta())),e.postProcessingComposer?e.postProcessingComposer.render():e.renderer.render(e.scene,e.camera),e.extraRenderers.forEach(function(t){return t.render(e.scene,e.camera)});var t=+new Date;if(e.enablePointerInteraction&&t-e.lastRaycasterCheck>=e.pointerRaycasterThrottleMs){e.lastRaycasterCheck=t;var s=null;if(e.hoverDuringDrag||!e.isPointerDragging){var i=this.intersectingObjects(e.pointerPos.x,e.pointerPos.y);e.hoverOrderComparator&&i.sort(function(t,s){return e.hoverOrderComparator(t.object,s.object)});var r=i.find(function(t){return e.hoverFilter(t.object)})||null;s=r?r.object:null,e.intersection=r||null}s!==e.hoverObj&&(e.onHover(s,e.hoverObj,e.intersection),e.tooltip.content(s&&function(e){return"function"==typeof e?e:"string"==typeof e?function(t){return t[e]}:function(t){return e}}(e.tooltipContent)(s,e.intersection)||null),e.hoverObj=s)}e.tweenGroup.update()}return this},getPointerPos:function(e){var t=e.pointerPos;return{x:t.x,y:t.y}},cameraPosition:function(e,t,s,i){var r=e.camera;if(t&&e.initialised){var n,a,o=t,h=s||{x:0,y:0,z:0};if(null===(n=e.povPosTween)||void 0===n||n.end(),null===(a=e.povTgtTween)||void 0===a||a.end(),i){var l=Object.assign({},r.position),u=p();e.tweenGroup.add(e.povPosTween=new wE(l).to(o,i).easing(bE.Quadratic.Out).onUpdate(c).onComplete(function(){e.povPosTween=void 0,e.tweenGroup.remove(this)}).start()),e.tweenGroup.add(e.povTgtTween=new wE(u).to(h,i/3).easing(bE.Quadratic.Out).onUpdate(d).onComplete(function(){e.povTgtTween=void 0,e.tweenGroup.remove(this)}).start())}else c(o),d(h);return this}return Object.assign({},r.position,{lookAt:p()});function c(e){var t=e.x,s=e.y,i=e.z;void 0!==t&&(r.position.x=t),void 0!==s&&(r.position.y=s),void 0!==i&&(r.position.z=i)}function d(t){var s=new uP.Vector3(t.x,t.y,t.z);e.controls.enabled&&e.controls.target?e.controls.target=s:r.lookAt(s)}function p(){return Object.assign(new uP.Vector3(0,0,-1e3).applyQuaternion(r.quaternion).add(r.position))}},zoomToFit:function(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:10,i=arguments.length,r=new Array(i>3?i-3:0),n=3;n<i;n++)r[n-3]=arguments[n];return this.fitToBbox(this.getBbox.apply(this,r),t,s)},fitToBbox:function(e,t){var s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:10,a=e.camera;if(t){var o=new uP.Vector3(0,0,0),h=2*Math.max.apply(Math,r(Object.entries(t).map(function(e){var t=i(e,2),s=t[0],n=t[1];return Math.max.apply(Math,r(n.map(function(e){return Math.abs(o[s]-e)})))}))),l=(1-2*n/e.height)*a.fov,u=h/Math.atan(l*Math.PI/180),c=u/a.aspect,d=Math.max(u,c);if(d>0){var p=o.clone().sub(a.position).normalize().multiplyScalar(-d);this.cameraPosition(p,o,s)}}return this},getBbox:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(){return!0},i=new uP.Box3(new uP.Vector3(0,0,0),new uP.Vector3(0,0,0)),n=e.objects.filter(t);return n.length?(n.forEach(function(e){return i.expandByObject(e)}),Object.assign.apply(Object,r(["x","y","z"].map(function(e){return s({},e,[i.min[e],i.max[e]])})))):null},getScreenCoords:function(e,t,s,i){var r=new uP.Vector3(t,s,i);return r.project(this.camera()),{x:(r.x+1)*e.width/2,y:-(r.y-1)*e.height/2}},getSceneCoords:function(e,t,s){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,r=new uP.Vector2(t/e.width*2-1,-s/e.height*2+1),n=new uP.Raycaster;return n.setFromCamera(r,e.camera),Object.assign({},n.ray.at(i,new uP.Vector3))},intersectingObjects:function(e,t,s){var i=new uP.Vector2(t/e.width*2-1,-s/e.height*2+1),r=new uP.Raycaster;return r.params.Line.threshold=e.lineHoverPrecision,r.params.Points.threshold=e.pointsHoverPrecision,r.setFromCamera(i,e.camera),r.intersectObjects(e.objects,!0)},renderer:function(e){return e.renderer},scene:function(e){return e.scene},camera:function(e){return e.camera},postProcessingComposer:function(e){return e.postProcessingComposer},controls:function(e){return e.controls},tbControls:function(e){return e.controls},_destructor:function(e){var t,s,i;!function(e){for(;e.children.length;){var t=e.children[0];e.remove(t),lP(t)}}(e.scene),null===(t=e.controls)||void 0===t||t.dispose(),null===(s=e.renderer)||void 0===s||s.dispose(),null===(i=e.postProcessingComposer)||void 0===i||i.dispose()}},stateInit:function(){return{scene:new uP.Scene,camera:new uP.PerspectiveCamera,timer:new uP.Timer,tweenGroup:new xE,lastRaycasterCheck:0}},init:function(e,t){var s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=s.controlType,n=void 0===i?"trackball":i,a=s.useWebGPU,o=void 0!==a&&a,h=s.rendererConfig,l=void 0===h?{}:h,u=s.extraRenderers,c=void 0===u?[]:u,d=s.waitForLoadComplete,p=void 0===d||d;e.innerHTML="",e.appendChild(t.container=document.createElement("div")),t.container.className="scene-container",t.container.style.position="relative",t.container.appendChild(t.navInfo=document.createElement("div")),t.navInfo.className="scene-nav-info",t.navInfo.textContent={orbit:"Left-click: rotate, Mouse-wheel/middle-click: zoom, Right-click: pan",trackball:"Left-click: rotate, Mouse-wheel/middle-click: zoom, Right-click: pan",fly:"WASD: move, R|F: up | down, Q|E: roll, up|down: pitch, left|right: yaw"}[n]||"",t.navInfo.style.display=t.showNavInfo?null:"none",t.tooltip=new oP(t.container),t.pointerPos=new uP.Vector2,t.pointerPos.x=-2,t.pointerPos.y=-2,["pointermove","pointerdown"].forEach(function(e){return t.container.addEventListener(e,function(s){if("pointerdown"===e&&(t.isPointerPressed=!0),!t.isPointerDragging&&"pointermove"===s.type&&(s.pressure>0||t.isPointerPressed)&&("mouse"===s.pointerType||void 0===s.movementX||[s.movementX,s.movementY].some(function(e){return Math.abs(e)>1}))&&(t.isPointerDragging=!0),t.enablePointerInteraction){var i=(r=t.container,n=r.getBoundingClientRect(),a=window.pageXOffset||document.documentElement.scrollLeft,o=window.pageYOffset||document.documentElement.scrollTop,{top:n.top+o,left:n.left+a});t.pointerPos.x=s.pageX-i.left,t.pointerPos.y=s.pageY-i.top}var r,n,a,o},{passive:!0})}),t.container.addEventListener("pointerup",function(e){t.isPointerPressed&&(t.isPointerPressed=!1,t.isPointerDragging&&(t.isPointerDragging=!1,!t.clickAfterDrag)||requestAnimationFrame(function(){0===e.button&&t.onClick(t.hoverObj||null,e,t.intersection),2===e.button&&t.onRightClick&&t.onRightClick(t.hoverObj||null,e,t.intersection)}))},{passive:!0,capture:!0}),t.container.addEventListener("contextmenu",function(e){t.onRightClick&&e.preventDefault()}),t.renderer=new(o?tN:uP.WebGLRenderer)(Object.assign({antialias:!0,alpha:!0},l)),t.renderer.setPixelRatio(Math.min(2,window.devicePixelRatio)),t.container.appendChild(t.renderer.domElement),t.extraRenderers=c,t.extraRenderers.forEach(function(e){e.domElement.style.position="absolute",e.domElement.style.top="0px",e.domElement.style.pointerEvents="none",t.container.appendChild(e.domElement)}),t.postProcessingComposer=new FA(t.renderer),t.postProcessingComposer.addPass(new LA(t.scene,t.camera)),t.controls=new{trackball:TN,orbit:eA,fly:fA}[n](t.camera,t.renderer.domElement),"fly"===n&&(t.controls.movementSpeed=300,t.controls.rollSpeed=Math.PI/6,t.controls.dragToLook=!0),"trackball"!==n&&"orbit"!==n||(t.controls.minDistance=.1,t.controls.maxDistance=t.skyRadius,t.controls.addEventListener("start",function(){t.controlsEngaged=!0}),t.controls.addEventListener("change",function(){t.controlsEngaged&&(t.controlsDragging=!0)}),t.controls.addEventListener("end",function(){t.controlsEngaged=!1,t.controlsDragging=!1})),[t.renderer,t.postProcessingComposer].concat(r(t.extraRenderers)).forEach(function(e){return e.setSize(t.width,t.height)}),t.camera.aspect=t.width/t.height,t.camera.updateProjectionMatrix(),t.camera.position.z=1e3,t.scene.add(t.skysphere=new uP.Mesh),t.skysphere.visible=!1,t.loadComplete=t.scene.visible=!p,window.scene=t.scene},update:function(e,t){if(e.width&&e.height&&(t.hasOwnProperty("width")||t.hasOwnProperty("height"))){var s,i=e.width,n=e.height;e.container.style.width="".concat(i,"px"),e.container.style.height="".concat(n,"px"),[e.renderer,e.postProcessingComposer].concat(r(e.extraRenderers)).forEach(function(e){return e.setSize(i,n)}),e.camera.aspect=i/n;var a=e.viewOffset.slice(0,2);a.some(function(e){return e})&&(s=e.camera).setViewOffset.apply(s,[i,n].concat(r(a),[i,n])),e.camera.updateProjectionMatrix()}if(t.hasOwnProperty("viewOffset")){var o,h=e.width,l=e.height,u=e.viewOffset.slice(0,2);u.some(function(e){return e})?(o=e.camera).setViewOffset.apply(o,[h,l].concat(r(u),[h,l])):e.camera.clearViewOffset()}if(t.hasOwnProperty("skyRadius")&&e.skyRadius&&(e.controls.hasOwnProperty("maxDistance")&&t.skyRadius&&(e.controls.maxDistance=Math.min(e.controls.maxDistance,e.skyRadius)),e.camera.far=2.5*e.skyRadius,e.camera.updateProjectionMatrix(),e.skysphere.geometry=new uP.SphereGeometry(e.skyRadius)),t.hasOwnProperty("backgroundColor")){var c=tE(e.backgroundColor).alpha;void 0===c&&(c=1),e.renderer.setClearColor(new uP.Color(yE(1,e.backgroundColor)),c)}function d(){e.loadComplete=e.scene.visible=!0}t.hasOwnProperty("backgroundImageUrl")&&(e.backgroundImageUrl?(new uP.TextureLoader).load(e.backgroundImageUrl,function(t){t.colorSpace=uP.SRGBColorSpace,e.skysphere.material=new uP.MeshBasicMaterial({map:t,side:uP.BackSide}),e.skysphere.visible=!0,e.onBackgroundImageLoaded&&setTimeout(e.onBackgroundImageLoaded),!e.loadComplete&&d()}):(e.skysphere.visible=!1,e.skysphere.material.map=null,!e.loadComplete&&d())),t.hasOwnProperty("showNavInfo")&&(e.navInfo.style.display=e.showNavInfo?null:"none"),t.hasOwnProperty("lights")&&((t.lights||[]).forEach(function(t){return e.scene.remove(t)}),e.lights.forEach(function(t){return e.scene.add(t)})),t.hasOwnProperty("objects")&&((t.objects||[]).forEach(function(t){return e.scene.remove(t)}),e.objects.forEach(function(t){return e.scene.add(t)}))}});return cP});
|
|
1
|
+
// Version 1.43.0 three-render-objects - https://github.com/vasturiano/three-render-objects
|
|
2
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("three")):"function"==typeof define&&define.amd?define(["three"],t):(e="undefined"!=typeof globalThis?globalThis:e||self).ThreeRenderObjects=t(e.THREE)}(this,function(e){"use strict";!function(e,t){void 0===t&&(t={});var s=t.insertAt;if("undefined"!=typeof document){var i=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css","top"===s&&i.firstChild?i.insertBefore(r,i.firstChild):i.appendChild(r),r.styleSheet?r.styleSheet.cssText=e:r.appendChild(document.createTextNode(e))}}(".scene-nav-info {\n position: absolute;\n bottom: 5px;\n width: 100%;\n text-align: center;\n color: slategrey;\n opacity: 0.7;\n font-size: 10px;\n font-family: sans-serif;\n pointer-events: none;\n user-select: none;\n}\n\n.scene-container canvas:focus {\n outline: none;\n}");const t="186",s=0,i=1,r=2,n=100,a=101,o=102,l=103,h=104,u=200,c=201,d=202,p=203,m=204,f=205,g=206,y=207,b=208,_=209,x=210,v=211,T=212,S=213,w=214,M=0,E=1,A=2,N=3,C=4,R=5,P=6,B=7,F=301,L=302,D=306,O=1e3,I=1001,U=1002,k=1003,z=1004,V=1005,G=1006,$=1007,j=1008,W=1009,H=1010,q=1011,X=1012,Y=1013,K=1014,Q=1015,Z=1016,J=1017,ee=1018,te=1020,se=35902,ie=35899,re=1021,ne=1022,ae=1023,oe=1026,le=1027,he=1028,ue=1029,ce=1030,de=1031,pe=1032,me=1033,fe=33776,ge=33777,ye=33778,be=33779,_e=35840,xe=35841,ve=35842,Te=35843,Se=36196,we=37492,Me=37496,Ee=37488,Ae=37489,Ne=37490,Ce=37491,Re=37808,Pe=37809,Be=37810,Fe=37811,Le=37812,De=37813,Oe=37814,Ie=37815,Ue=37816,ke=37817,ze=37818,Ve=37819,Ge=37820,$e=37821,je=36492,We=36494,He=36495,qe=36283,Xe=36284,Ye=36285,Ke=36286,Qe="",Ze="srgb",Je="srgb-linear",et="linear",tt="srgb",st=7680,it=512,rt=513,nt=514,at=515,ot=516,lt=517,ht=518,ut=519,ct=35044,dt=35048,pt=2e3,mt=2001,ft="compute",gt="render",yt="depthTextureCompare",bt=0,_t=1,xt=2;function vt(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function Tt(e){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}const St={};function wt(...e){const t="THREE."+e.shift();console.log(t,...e)}function Mt(e){const t=e[0];if("string"==typeof t&&t.startsWith("TSL:")){const t=e[1];t&&t.isStackTrace?e[0]+=" "+t.getLocation():e[1]='Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'}return e}function Et(...e){const t="THREE."+(e=Mt(e)).shift();{const s=e[0];s&&s.isStackTrace?console.warn(s.getError(t)):console.warn(t,...e)}}function At(...e){const t="THREE."+(e=Mt(e)).shift();{const s=e[0];s&&s.isStackTrace?console.error(s.getError(t)):console.error(t,...e)}}function Nt(...e){const t=e.join(" ");t in St||(St[t]=!0,Et(...e))}function Ct(){return"undefined"!=typeof self&&void 0!==self.scheduler&&void 0!==self.scheduler.yield?self.scheduler.yield():new Promise(e=>{requestAnimationFrame(e)})}const Rt={[M]:1,[A]:6,[C]:7,[N]:5,[E]:0,[P]:2,[B]:4,[R]:3};class Pt{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 Bt=["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 Ft=1234567;const Lt=Math.PI/180,Dt=180/Math.PI;function Ot(){const e=4294967295*Math.random()|0,t=4294967295*Math.random()|0,s=4294967295*Math.random()|0,i=4294967295*Math.random()|0;return(Bt[255&e]+Bt[e>>8&255]+Bt[e>>16&255]+Bt[e>>24&255]+"-"+Bt[255&t]+Bt[t>>8&255]+"-"+Bt[t>>16&15|64]+Bt[t>>24&255]+"-"+Bt[63&s|128]+Bt[s>>8&255]+"-"+Bt[s>>16&255]+Bt[s>>24&255]+Bt[255&i]+Bt[i>>8&255]+Bt[i>>16&255]+Bt[i>>24&255]).toLowerCase()}function It(e,t,s){return Math.max(t,Math.min(s,e))}function Ut(e,t){return(e%t+t)%t}function kt(e,t,s){return(1-s)*e+s*t}function zt(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:case Uint8ClampedArray: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("THREE.MathUtils: Invalid component type.")}}function Vt(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:case Uint8ClampedArray: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("THREE.MathUtils: Invalid component type.")}}const Gt={DEG2RAD:Lt,RAD2DEG:Dt,generateUUID:Ot,clamp:It,euclideanModulo:Ut,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:kt,damp:function(e,t,s,i){return kt(e,t,1-Math.exp(-s*i))},pingpong:function(e,t=1){return t-Math.abs(Ut(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&&(Ft=e);let t=Ft+=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*Lt},radToDeg:function(e){return e*Dt},isPowerOfTwo:function(e){return e>0&&Number.isInteger(e)&&2**Math.round(Math.log2(e))===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,a=Math.sin,o=n(s/2),l=a(s/2),h=n((t+i)/2),u=a((t+i)/2),c=n((t-i)/2),d=a((t-i)/2),p=n((i-t)/2),m=a((i-t)/2);switch(r){case"XYX":e.set(o*u,l*c,l*d,o*h);break;case"YZY":e.set(l*d,o*u,l*c,o*h);break;case"ZXZ":e.set(l*c,l*d,o*u,o*h);break;case"XZX":e.set(o*u,l*m,l*p,o*h);break;case"YXY":e.set(l*p,o*u,l*m,o*h);break;case"ZYZ":e.set(l*m,l*p,o*u,o*h);break;default:Et("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}},normalize:Vt,denormalize:zt};class $t{static{$t.prototype.isVector2=!0}constructor(e=0,t=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("THREE.Vector2: 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("THREE.Vector2: 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=It(this.x,e.x,t.x),this.y=It(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=It(this.x,e,t),this.y=It(this.y,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(It(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(It(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 jt{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,a){let o=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(u!==m||o!==c||l!==d||h!==p){let e=o*c+l*d+h*p+u*m;e<0&&(c=-c,d=-d,p=-p,m=-m,e=-e);let t=1-a;if(e<.9995){const s=Math.acos(e),i=Math.sin(s);t=Math.sin(t*s)/i,o=o*t+c*(a=Math.sin(a*s)/i),l=l*t+d*a,h=h*t+p*a,u=u*t+m*a}else{o=o*t+c*a,l=l*t+d*a,h=h*t+p*a,u=u*t+m*a;const e=1/Math.sqrt(o*o+l*l+h*h+u*u);o*=e,l*=e,h*=e,u*=e}}e[t]=o,e[t+1]=l,e[t+2]=h,e[t+3]=u}static multiplyQuaternionsFlat(e,t,s,i,r,n){const a=s[i],o=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]=a*p+h*u+o*d-l*c,e[t+1]=o*p+h*c+l*u-a*d,e[t+2]=l*p+h*d+a*c-o*u,e[t+3]=h*p-a*u-o*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,a=Math.cos,o=Math.sin,l=a(s/2),h=a(i/2),u=a(r/2),c=o(s/2),d=o(i/2),p=o(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:Et("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],a=t[5],o=t[9],l=t[2],h=t[6],u=t[10],c=s+a+u;if(c>0){const e=.5/Math.sqrt(c+1);this._w=.25/e,this._x=(h-o)*e,this._y=(r-l)*e,this._z=(n-i)*e}else if(s>a&&s>u){const e=2*Math.sqrt(1+s-a-u);this._w=(h-o)/e,this._x=.25*e,this._y=(i+n)/e,this._z=(r+l)/e}else if(a>u){const e=2*Math.sqrt(1+a-s-u);this._w=(r-l)/e,this._x=(i+n)/e,this._y=.25*e,this._z=(o+h)/e}else{const e=2*Math.sqrt(1+u-s-a);this._w=(n-i)/e,this._x=(r+l)/e,this._y=(o+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(It(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,a=t._x,o=t._y,l=t._z,h=t._w;return this._x=s*h+n*a+i*l-r*o,this._y=i*h+n*o+r*a-s*l,this._z=r*h+n*l+s*o-i*a,this._w=n*h-s*a-i*o-r*l,this._onChangeCallback(),this}slerp(e,t){let s=e._x,i=e._y,r=e._z,n=e._w,a=this.dot(e);a<0&&(s=-s,i=-i,r=-r,n=-n,a=-a);let o=1-t;if(a<.9995){const e=Math.acos(a),l=Math.sin(e);o=Math.sin(o*e)/l,t=Math.sin(t*e)/l,this._x=this._x*o+s*t,this._y=this._y*o+i*t,this._z=this._z*o+r*t,this._w=this._w*o+n*t,this._onChangeCallback()}else this._x=this._x*o+s*t,this._y=this._y*o+i*t,this._z=this._z*o+r*t,this._w=this._w*o+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 Wt{static{Wt.prototype.isVector3=!0}constructor(e=0,t=0,s=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("THREE.Vector3: 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("THREE.Vector3: 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(qt.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(qt.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,a=e.z,o=e.w,l=2*(n*i-a*s),h=2*(a*t-r*i),u=2*(r*s-n*t);return this.x=t+o*l+n*u-a*h,this.y=s+o*h+a*l-r*u,this.z=i+o*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=It(this.x,e.x,t.x),this.y=It(this.y,e.y,t.y),this.z=It(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=It(this.x,e,t),this.y=It(this.y,e,t),this.z=It(this.z,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(It(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,a=t.y,o=t.z;return this.x=i*o-r*a,this.y=r*n-s*o,this.z=s*a-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 Ht.copy(this).projectOnVector(e),this.sub(Ht)}reflect(e){return this.sub(Ht.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(It(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 Ht=new Wt,qt=new jt;class Xt{static{Xt.prototype.isMatrix3=!0}constructor(e,t,s,i,r,n,a,o,l){this.elements=[1,0,0,0,1,0,0,0,1],void 0!==e&&this.set(e,t,s,i,r,n,a,o,l)}set(e,t,s,i,r,n,a,o,l){const h=this.elements;return h[0]=e,h[1]=i,h[2]=a,h[3]=t,h[4]=r,h[5]=o,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],a=s[3],o=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],_=i[7],x=i[2],v=i[5],T=i[8];return r[0]=n*m+a*y+o*x,r[3]=n*f+a*b+o*v,r[6]=n*g+a*_+o*T,r[1]=l*m+h*y+u*x,r[4]=l*f+h*b+u*v,r[7]=l*g+h*_+u*T,r[2]=c*m+d*y+p*x,r[5]=c*f+d*b+p*v,r[8]=c*g+d*_+p*T,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],a=e[5],o=e[6],l=e[7],h=e[8];return t*n*h-t*a*l-s*r*h+s*a*o+i*r*l-i*n*o}invert(){const e=this.elements,t=e[0],s=e[1],i=e[2],r=e[3],n=e[4],a=e[5],o=e[6],l=e[7],h=e[8],u=h*n-a*l,c=a*o-h*r,d=l*r-n*o,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]=(a*s-i*n)*m,e[3]=c*m,e[4]=(h*t-i*o)*m,e[5]=(i*r-a*t)*m,e[6]=d*m,e[7]=(s*o-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,a){const o=Math.cos(r),l=Math.sin(r);return this.set(s*o,s*l,-s*(o*n+l*a)+n+e,-i*l,i*o,-i*(-l*n+o*a)+a+t,0,0,1),this}scale(e,t){return Nt("Matrix3: .scale() is deprecated. Use .makeScale() instead."),this.premultiply(Yt.makeScale(e,t)),this}rotate(e){return Nt("Matrix3: .rotate() is deprecated. Use .makeRotation() instead."),this.premultiply(Yt.makeRotation(-e)),this}translate(e,t){return Nt("Matrix3: .translate() is deprecated. Use .makeTranslation() instead."),this.premultiply(Yt.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 Yt=new Xt,Kt=(new Xt).set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),Qt=(new Xt).set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function Zt(){const e={enabled:!0,workingColorSpace:Je,spaces:{},convert:function(e,t,s){return!1!==this.enabled&&t!==s&&t&&s?(this.spaces[t].transfer===tt&&(e.r=es(e.r),e.g=es(e.g),e.b=es(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===tt&&(e.r=ts(e.r),e.g=ts(e.g),e.b=ts(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===Qe?et: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 Nt("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),e.workingToColorSpace(t,s)},toWorkingColorSpace:function(t,s){return Nt("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({[Je]:{primaries:t,whitePoint:i,transfer:et,toXYZ:Kt,fromXYZ:Qt,luminanceCoefficients:s,workingColorSpaceConfig:{unpackColorSpace:Ze},outputColorSpaceConfig:{drawingBufferColorSpace:Ze}},[Ze]:{primaries:t,whitePoint:i,transfer:tt,toXYZ:Kt,fromXYZ:Qt,luminanceCoefficients:s,outputColorSpaceConfig:{drawingBufferColorSpace:Ze}}}),e}const Jt=Zt();function es(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}function ts(e){return e<.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}let ss;class is{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===ss&&(ss=Tt("canvas")),ss.width=e.width,ss.height=e.height;const t=ss.getContext("2d");e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),s=ss}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=Tt("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*es(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*es(t[e]/255)):t[e]=es(t[e]);return{data:t,width:e.width,height:e.height}}return Et("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let rs=0;class ns{constructor(e=null){this.isTextureSource=!0,Object.defineProperty(this,"id",{value:rs++}),this.uuid=Ot(),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.displayWidth,t.displayHeight,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(as(i[t].image)):e.push(as(i[t]))}else e=as(i);s.url=e}return t||(e.images[this.uuid]=s),s}}function as(e){return"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?is.getDataURL(e):e.data?{data:Array.from(e.data),width:e.width,height:e.height,type:e.data.constructor.name}:(Et("Texture: Unable to serialize Texture."),{})}let os=0;const ls=new Wt;class hs extends Pt{constructor(e=hs.DEFAULT_IMAGE,t=hs.DEFAULT_MAPPING,s=1001,i=1001,r=1006,n=1008,a=1023,o=1009,l=hs.DEFAULT_ANISOTROPY,h=""){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:os++}),this.uuid=Ot(),this.name="",this.source=new ns(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=a,this.internalFormat=null,this.type=o,this.offset=new $t(0,0),this.repeat=new $t(1,1),this.center=new $t(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new Xt,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,this.normalized=!1}get width(){return this.source.getSize(ls).x}get height(){return this.source.getSize(ls).y}get depth(){return this.source.getSize(ls).z}get image(){return this.source.data}set image(e){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.normalized=e.normalized,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){Et(`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:Et(`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,normalized:this.normalized,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 O:e.x=e.x-Math.floor(e.x);break;case I:e.x=e.x<0?0:1;break;case U: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 O:e.y=e.y-Math.floor(e.y);break;case I:e.y=e.y<0?0:1;break;case U: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++}}hs.DEFAULT_IMAGE=null,hs.DEFAULT_MAPPING=300,hs.DEFAULT_ANISOTROPY=1;class us{static{us.prototype.isVector4=!0}constructor(e=0,t=0,s=0,i=1){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("THREE.Vector4: 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("THREE.Vector4: 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,a=.1,o=e.elements,l=o[0],h=o[4],u=o[8],c=o[1],d=o[5],p=o[9],m=o[2],f=o[6],g=o[10];if(Math.abs(h-c)<n&&Math.abs(u-m)<n&&Math.abs(p-f)<n){if(Math.abs(h+c)<a&&Math.abs(u+m)<a&&Math.abs(p+f)<a&&Math.abs(l+d+g-3)<a)return this.set(1,0,0,0),this;t=Math.PI;const e=(l+1)/2,o=(d+1)/2,y=(g+1)/2,b=(h+c)/4,_=(u+m)/4,x=(p+f)/4;return e>o&&e>y?e<n?(s=0,i=.707106781,r=.707106781):(s=Math.sqrt(e),i=b/s,r=_/s):o>y?o<n?(s=.707106781,i=0,r=.707106781):(i=Math.sqrt(o),s=b/i,r=x/i):y<n?(s=.707106781,i=.707106781,r=0):(r=Math.sqrt(y),s=_/r,i=x/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=It(this.x,e.x,t.x),this.y=It(this.y,e.y,t.y),this.z=It(this.z,e.z,t.z),this.w=It(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=It(this.x,e,t),this.y=It(this.y,e,t),this.z=It(this.z,e,t),this.w=It(this.w,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(It(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 cs extends Pt{constructor(e=1,t=1,s={}){super(),s=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:G,depthBuffer:!0,stencilBuffer:!1,resolveColorBuffer:!0,resolveDepthBuffer:!0,resolveStencilBuffer:!0,storeMultisampledColorBuffer:!0,storeMultisampledDepthBuffer:!0,storeMultisampledStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1,useArrayDepthTexture:!1},s),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=s.depth,this.scissor=new us(0,0,e,t),this.scissorTest=!1,this.viewport=new us(0,0,e,t),this.textures=[];const i={width:e,height:t,depth:s.depth},r=new hs(i),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.resolveColorBuffer=s.resolveColorBuffer,this.resolveDepthBuffer=s.resolveDepthBuffer,this.resolveStencilBuffer=s.resolveStencilBuffer,this.storeMultisampledColorBuffer=s.storeMultisampledColorBuffer,this.storeMultisampledDepthBuffer=s.storeMultisampledDepthBuffer,this.storeMultisampledStencilBuffer=s.storeMultisampledStencilBuffer,this._depthTexture=null,this.depthTexture=s.depthTexture,this.samples=s.samples,this.multiview=s.multiview,this.useArrayDepthTexture=s.useArrayDepthTexture}_setTextureOptions(e={}){const t={minFilter:G,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===this&&(this._depthTexture.renderTarget=null),null!==e&&null===e.renderTarget&&(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 ns(s)}if(this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveColorBuffer=e.resolveColorBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,this.storeMultisampledColorBuffer=e.storeMultisampledColorBuffer,this.storeMultisampledDepthBuffer=e.storeMultisampledDepthBuffer,this.storeMultisampledStencilBuffer=e.storeMultisampledStencilBuffer,null!==e.depthTexture)if(e.depthTexture.renderTarget===e){const t=e.depthTexture.clone();t.renderTarget=null,this.depthTexture=t}else this.depthTexture=e.depthTexture;return this.samples=e.samples,this.multiview=e.multiview,this.useArrayDepthTexture=e.useArrayDepthTexture,this}dispose(){this.dispatchEvent({type:"dispose"})}}class ds extends hs{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=k,this.minFilter=k,this.wrapR=I,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}copy(e){return super.copy(e),this.wrapR=e.wrapR,this}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class ps{static{ps.prototype.isMatrix4=!0}constructor(e,t,s,i,r,n,a,o,l,h,u,c,d,p,m,f){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,a,o,l,h,u,c,d,p,m,f)}set(e,t,s,i,r,n,a,o,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]=a,g[13]=o,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 ps).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.determinantAffine()?(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.determinantAffine())return this.identity();const t=this.elements,s=e.elements,i=1/ms.setFromMatrixColumn(e,0).length(),r=1/ms.setFromMatrixColumn(e,1).length(),n=1/ms.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),a=Math.sin(s),o=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=a*h,r=a*u;t[0]=o*h,t[4]=-o*u,t[8]=l,t[1]=s+i*l,t[5]=e-r*l,t[9]=-a*o,t[2]=r-e*l,t[6]=i+s*l,t[10]=n*o}else if("YXZ"===e.order){const e=o*h,s=o*u,i=l*h,r=l*u;t[0]=e+r*a,t[4]=i*a-s,t[8]=n*l,t[1]=n*u,t[5]=n*h,t[9]=-a,t[2]=s*a-i,t[6]=r+e*a,t[10]=n*o}else if("ZXY"===e.order){const e=o*h,s=o*u,i=l*h,r=l*u;t[0]=e-r*a,t[4]=-n*u,t[8]=i+s*a,t[1]=s+i*a,t[5]=n*h,t[9]=r-e*a,t[2]=-n*l,t[6]=a,t[10]=n*o}else if("ZYX"===e.order){const e=n*h,s=n*u,i=a*h,r=a*u;t[0]=o*h,t[4]=i*l-s,t[8]=e*l+r,t[1]=o*u,t[5]=r*l+e,t[9]=s*l-i,t[2]=-l,t[6]=a*o,t[10]=n*o}else if("YZX"===e.order){const e=n*o,s=n*l,i=a*o,r=a*l;t[0]=o*h,t[4]=r-e*u,t[8]=i*u+s,t[1]=u,t[5]=n*h,t[9]=-a*h,t[2]=-l*h,t[6]=s*u+i,t[10]=e-r*u}else if("XZY"===e.order){const e=n*o,s=n*l,i=a*o,r=a*l;t[0]=o*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]=a*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(gs,e,ys)}lookAt(e,t,s){const i=this.elements;return xs.subVectors(e,t),0===xs.lengthSq()&&(xs.z=1),xs.normalize(),bs.crossVectors(s,xs),0===bs.lengthSq()&&(1===Math.abs(s.z)?xs.x+=1e-4:xs.z+=1e-4,xs.normalize(),bs.crossVectors(s,xs)),bs.normalize(),_s.crossVectors(xs,bs),i[0]=bs.x,i[4]=_s.x,i[8]=xs.x,i[1]=bs.y,i[5]=_s.y,i[9]=xs.y,i[2]=bs.z,i[6]=_s.z,i[10]=xs.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],a=s[4],o=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],_=s[11],x=s[15],v=i[0],T=i[4],S=i[8],w=i[12],M=i[1],E=i[5],A=i[9],N=i[13],C=i[2],R=i[6],P=i[10],B=i[14],F=i[3],L=i[7],D=i[11],O=i[15];return r[0]=n*v+a*M+o*C+l*F,r[4]=n*T+a*E+o*R+l*L,r[8]=n*S+a*A+o*P+l*D,r[12]=n*w+a*N+o*B+l*O,r[1]=h*v+u*M+c*C+d*F,r[5]=h*T+u*E+c*R+d*L,r[9]=h*S+u*A+c*P+d*D,r[13]=h*w+u*N+c*B+d*O,r[2]=p*v+m*M+f*C+g*F,r[6]=p*T+m*E+f*R+g*L,r[10]=p*S+m*A+f*P+g*D,r[14]=p*w+m*N+f*B+g*O,r[3]=y*v+b*M+_*C+x*F,r[7]=y*T+b*E+_*R+x*L,r[11]=y*S+b*A+_*P+x*D,r[15]=y*w+b*N+_*B+x*O,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],a=e[5],o=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=o*d-l*c,b=a*d-l*u,_=a*c-o*u,x=n*d-l*h,v=n*c-o*h,T=n*u-a*h;return t*(m*y-f*b+g*_)-s*(p*y-f*x+g*v)+i*(p*b-m*x+g*T)-r*(p*_-m*v+f*T)}determinantAffine(){const e=this.elements,t=e[0],s=e[4],i=e[8],r=e[1],n=e[5],a=e[9],o=e[2],l=e[6],h=e[10];return t*(n*h-a*l)-s*(r*h-a*o)+i*(r*l-n*o)}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],a=e[5],o=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=t*a-s*n,b=t*o-i*n,_=t*l-r*n,x=s*o-i*a,v=s*l-r*a,T=i*l-r*o,S=h*m-u*p,w=h*f-c*p,M=h*g-d*p,E=u*f-c*m,A=u*g-d*m,N=c*g-d*f,C=y*N-b*A+_*E+x*M-v*w+T*S;if(0===C)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const R=1/C;return e[0]=(a*N-o*A+l*E)*R,e[1]=(i*A-s*N-r*E)*R,e[2]=(m*T-f*v+g*x)*R,e[3]=(c*v-u*T-d*x)*R,e[4]=(o*M-n*N-l*w)*R,e[5]=(t*N-i*M+r*w)*R,e[6]=(f*_-p*T-g*b)*R,e[7]=(h*T-c*_+d*b)*R,e[8]=(n*A-a*M+l*S)*R,e[9]=(s*M-t*A-r*S)*R,e[10]=(p*v-m*_+g*y)*R,e[11]=(u*_-h*v-d*y)*R,e[12]=(a*w-n*E-o*S)*R,e[13]=(t*E-s*w+i*S)*R,e[14]=(m*b-p*x-f*y)*R,e[15]=(h*x-u*b+c*y)*R,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,a=e.y,o=e.z,l=r*n,h=r*a;return this.set(l*n+s,l*a-i*o,l*o+i*a,0,l*a+i*o,h*a+s,h*o-i*n,0,l*o-i*a,h*o+i*n,r*o*o+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,a=t._z,o=t._w,l=r+r,h=n+n,u=a+a,c=r*l,d=r*h,p=r*u,m=n*h,f=n*u,g=a*u,y=o*l,b=o*h,_=o*u,x=s.x,v=s.y,T=s.z;return i[0]=(1-(m+g))*x,i[1]=(d+_)*x,i[2]=(p-b)*x,i[3]=0,i[4]=(d-_)*v,i[5]=(1-(c+g))*v,i[6]=(f+y)*v,i[7]=0,i[8]=(p+b)*T,i[9]=(f-y)*T,i[10]=(1-(c+m))*T,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;e.x=i[12],e.y=i[13],e.z=i[14];const r=this.determinantAffine();if(0===r)return s.set(1,1,1),t.identity(),this;let n=ms.set(i[0],i[1],i[2]).length();const a=ms.set(i[4],i[5],i[6]).length(),o=ms.set(i[8],i[9],i[10]).length();r<0&&(n=-n),fs.copy(this);const l=1/n,h=1/a,u=1/o;return fs.elements[0]*=l,fs.elements[1]*=l,fs.elements[2]*=l,fs.elements[4]*=h,fs.elements[5]*=h,fs.elements[6]*=h,fs.elements[8]*=u,fs.elements[9]*=u,fs.elements[10]*=u,t.setFromRotationMatrix(fs),s.x=n,s.y=a,s.z=o,this}makePerspective(e,t,s,i,r,n,a=2e3,o=!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(o)p=r/(n-r),m=n*r/(n-r);else if(a===pt)p=-(n+r)/(n-r),m=-2*n*r/(n-r);else{if(a!==mt)throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);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,a=2e3,o=!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(o)p=1/(n-r),m=n/(n-r);else if(a===pt)p=-2/(n-r),m=-(n+r)/(n-r);else{if(a!==mt)throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);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 ms=new Wt,fs=new ps,gs=new Wt(0,0,0),ys=new Wt(1,1,1),bs=new Wt,_s=new Wt,xs=new Wt,vs=new ps,Ts=new jt;class Ss{constructor(e=0,t=0,s=0,i=Ss.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],a=i[8],o=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(It(a,-1,1)),Math.abs(a)<.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(-It(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(a,d),this._z=Math.atan2(o,l)):(this._y=Math.atan2(-u,r),this._z=0);break;case"ZXY":this._x=Math.asin(It(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(o,r));break;case"ZYX":this._y=Math.asin(-It(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(c,d),this._z=Math.atan2(o,r)):(this._x=0,this._z=Math.atan2(-n,l));break;case"YZX":this._z=Math.asin(It(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-h,l),this._y=Math.atan2(-u,r)):(this._x=0,this._y=Math.atan2(a,d));break;case"XZY":this._z=Math.asin(-It(n,-1,1)),Math.abs(n)<.9999999?(this._x=Math.atan2(c,l),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-h,d),this._y=0);break;default:Et("Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,!0===s&&this._onChangeCallback(),this}setFromQuaternion(e,t,s){return vs.makeRotationFromQuaternion(e),this.setFromRotationMatrix(vs,t,s)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return Ts.setFromEuler(this),this.setFromQuaternion(Ts,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}}Ss.DEFAULT_ORDER="XYZ";class ws{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 Ms=0;const Es=new Wt,As=new jt,Ns=new ps,Cs=new Wt,Rs=new Wt,Ps=new Wt,Bs=new jt,Fs=new Wt(1,0,0),Ls=new Wt(0,1,0),Ds=new Wt(0,0,1),Os={type:"added"},Is={type:"removed"},Us={type:"childadded",child:null},ks={type:"childremoved",child:null};class zs extends Pt{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:Ms++}),this.uuid=Ot(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=zs.DEFAULT_UP.clone();const e=new Wt,t=new Ss,s=new jt,i=new Wt(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 ps},normalMatrix:{value:new Xt}}),this.matrix=new ps,this.matrixWorld=new ps,this.matrixAutoUpdate=zs.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=zs.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new ws,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.static=!1,this.userData={},this.pivot=null}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 As.setFromAxisAngle(e,t),this.quaternion.multiply(As),this}rotateOnWorldAxis(e,t){return As.setFromAxisAngle(e,t),this.quaternion.premultiply(As),this}rotateX(e){return this.rotateOnAxis(Fs,e)}rotateY(e){return this.rotateOnAxis(Ls,e)}rotateZ(e){return this.rotateOnAxis(Ds,e)}translateOnAxis(e,t){return Es.copy(e).applyQuaternion(this.quaternion),this.position.add(Es.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(Fs,e)}translateY(e){return this.translateOnAxis(Ls,e)}translateZ(e){return this.translateOnAxis(Ds,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(Ns.copy(this.matrixWorld).invert())}lookAt(e,t,s){e.isVector3?Cs.copy(e):Cs.set(e,t,s);const i=this.parent;this.updateWorldMatrix(!0,!1),Rs.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Ns.lookAt(Rs,Cs,this.up):Ns.lookAt(Cs,Rs,this.up),this.quaternion.setFromRotationMatrix(Ns),i&&(Ns.extractRotation(i.matrixWorld),As.setFromRotationMatrix(Ns),this.quaternion.premultiply(As.invert()))}add(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return e===this?(At("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(Os),Us.child=e,this.dispatchEvent(Us),Us.child=null):At("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(Is),ks.child=e,this.dispatchEvent(ks),ks.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),Ns.copy(this.matrixWorld).invert(),null!==e.parent&&(e.parent.updateWorldMatrix(!0,!1),Ns.multiply(e.parent.matrixWorld)),e.applyMatrix4(Ns),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(Os),Us.child=e,this.dispatchEvent(Us),Us.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(Rs,e,Ps),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Rs,Bs,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}intersectsFrustum(){}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);const e=this.pivot;if(null!==e){const t=e.x,s=e.y,i=e.z,r=this.matrix.elements;r[12]+=t-r[0]*t-r[4]*s-r[8]*i,r[13]+=s-r[1]*t-r[5]*s-r[9]*i,r[14]+=i-r[2]*t-r[6]*s-r[10]*i}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,s=!1){const i=this.parent;if(!0===e&&null!==i&&i.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||s)&&(!0===this.matrixWorldAutoUpdate&&(null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,s=!0),!0===t){const e=this.children;for(let t=0,i=e.length;t<i;t++){e[t].updateWorldMatrix(!1,!0,s)}}}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,i.name=this.name,i.castShadow=this.castShadow,i.receiveShadow=this.receiveShadow,i.visible=this.visible,i.frustumCulled=this.frustumCulled,i.renderOrder=this.renderOrder,i.static=this.static,i.matrixAutoUpdate=this.matrixAutoUpdate,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(),null!==this.pivot&&(i.pivot=this.pivot.toArray()),void 0!==this.morphTargetDictionary&&(i.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),void 0!==this.morphTargetInfluences&&(i.morphTargetInfluences=this.morphTargetInfluences.slice()),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),a=n(e.images),o=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),a.length>0&&(s.images=a),o.length>0&&(s.shapes=o),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.pivot=null!==e.pivot?e.pivot.clone():null,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.static=e.static,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}dispose(){this.dispatchEvent({type:"dispose"})}}zs.DEFAULT_UP=new Wt(0,1,0),zs.DEFAULT_MATRIX_AUTO_UPDATE=!0,zs.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;let Vs=class extends zs{constructor(){super(),this.isGroup=!0,this.type="Group"}};const Gs={type:"move"};class $s{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return null===this._hand&&(this._hand=new Vs,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 Vs,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new Wt,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new Wt),this._targetRay}getGripSpace(){return null===this._grip&&(this._grip=new Vs,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new Wt,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new Wt,this._grip.eventsEnabled=!1),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 a=this._targetRay,o=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"],a=i.position.distanceTo(r.position),o=.02,h=.005;l.inputState.pinching&&a>o+h?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!l.inputState.pinching&&a<=o-h&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else null!==o&&e.gripSpace&&(r=t.getPose(e.gripSpace,s),null!==r&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1,o.eventsEnabled&&o.dispatchEvent({type:"gripUpdated",data:e,target:this})));null!==a&&(i=t.getPose(e.targetRaySpace,s),null===i&&null!==r&&(i=r),null!==i&&(a.matrix.fromArray(i.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,i.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(i.linearVelocity)):a.hasLinearVelocity=!1,i.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(i.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(Gs)))}return null!==a&&(a.visible=null!==i),null!==o&&(o.visible=null!==r),null!==l&&(l.visible=null!==n),this}_getHandJoint(e,t){if(void 0===e.joints[t.jointName]){const s=new Vs;s.matrixAutoUpdate=!1,s.visible=!1,e.joints[t.jointName]=s,e.add(s)}return e.joints[t.jointName]}}const js={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},Ws={h:0,s:0,l:0},Hs={h:0,s:0,l:0};function qs(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 Xs{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=Ze){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(255&e)/255,Jt.colorSpaceToWorking(this,t),this}setRGB(e,t,s,i=Jt.workingColorSpace){return this.r=e,this.g=t,this.b=s,Jt.colorSpaceToWorking(this,i),this}setHSL(e,t,s,i=Jt.workingColorSpace){if(e=Ut(e,1),t=It(t,0,1),s=It(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=qs(r,i,e+1/3),this.g=qs(r,i,e),this.b=qs(r,i,e-1/3)}return Jt.colorSpaceToWorking(this,i),this}setStyle(e,t=Ze){function s(t){void 0!==t&&parseFloat(t)<1&&Et("Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const n=i[1],a=i[2];switch(n){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))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(a))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(a))return s(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:Et("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);Et("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Ze){const s=js[e.toLowerCase()];return void 0!==s?this.setHex(s,t):Et("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=es(e.r),this.g=es(e.g),this.b=es(e.b),this}copyLinearToSRGB(e){return this.r=ts(e.r),this.g=ts(e.g),this.b=ts(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Ze){return Jt.workingToColorSpace(Ys.copy(this),e),65536*Math.round(It(255*Ys.r,0,255))+256*Math.round(It(255*Ys.g,0,255))+Math.round(It(255*Ys.b,0,255))}getHexString(e=Ze){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Jt.workingColorSpace){Jt.workingToColorSpace(Ys.copy(this),t);const s=Ys.r,i=Ys.g,r=Ys.b,n=Math.max(s,i,r),a=Math.min(s,i,r);let o,l;const h=(a+n)/2;if(a===n)o=0,l=0;else{const e=n-a;switch(l=h<=.5?e/(n+a):e/(2-n-a),n){case s:o=(i-r)/e+(i<r?6:0);break;case i:o=(r-s)/e+2;break;case r:o=(s-i)/e+4}o/=6}return e.h=o,e.s=l,e.l=h,e}getRGB(e,t=Jt.workingColorSpace){return Jt.workingToColorSpace(Ys.copy(this),t),e.r=Ys.r,e.g=Ys.g,e.b=Ys.b,e}getStyle(e=Ze){Jt.workingToColorSpace(Ys.copy(this),e);const t=Ys.r,s=Ys.g,i=Ys.b;return e!==Ze?`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(Ws),this.setHSL(Ws.h+e,Ws.s+t,Ws.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(Ws),e.getHSL(Hs);const s=kt(Ws.h,Hs.h,t),i=kt(Ws.s,Hs.s,t),r=kt(Ws.l,Hs.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 Ys=new Xs;Xs.NAMES=js;class Ks extends zs{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 Ss,this.environmentIntensity=1,this.environmentRotation=new Ss,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()),t.object.backgroundBlurriness=this.backgroundBlurriness,t.object.backgroundIntensity=this.backgroundIntensity,t.object.backgroundRotation=this.backgroundRotation.toArray(),t.object.environmentIntensity=this.environmentIntensity,t.object.environmentRotation=this.environmentRotation.toArray(),t}}const Qs=new Wt,Zs=new Wt,Js=new Wt,ei=new Wt,ti=new Wt,si=new Wt,ii=new Wt,ri=new Wt,ni=new Wt,ai=new Wt,oi=new us,li=new us,hi=new us;class ui{constructor(e=new Wt,t=new Wt,s=new Wt){this.a=e,this.b=t,this.c=s}static getNormal(e,t,s,i){i.subVectors(s,t),Qs.subVectors(e,t),i.cross(Qs);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){Qs.subVectors(i,t),Zs.subVectors(s,t),Js.subVectors(e,t);const n=Qs.dot(Qs),a=Qs.dot(Zs),o=Qs.dot(Js),l=Zs.dot(Zs),h=Zs.dot(Js),u=n*l-a*a;if(0===u)return r.set(0,0,0),null;const c=1/u,d=(l*o-a*h)*c,p=(n*h-a*o)*c;return r.set(1-d-p,p,d)}static containsPoint(e,t,s,i){return null!==this.getBarycoord(e,t,s,i,ei)&&(ei.x>=0&&ei.y>=0&&ei.x+ei.y<=1)}static getInterpolation(e,t,s,i,r,n,a,o){return null===this.getBarycoord(e,t,s,i,ei)?(o.x=0,o.y=0,"z"in o&&(o.z=0),"w"in o&&(o.w=0),null):(o.setScalar(0),o.addScaledVector(r,ei.x),o.addScaledVector(n,ei.y),o.addScaledVector(a,ei.z),o)}static getInterpolatedAttribute(e,t,s,i,r,n){return oi.setScalar(0),li.setScalar(0),hi.setScalar(0),oi.fromBufferAttribute(e,t),li.fromBufferAttribute(e,s),hi.fromBufferAttribute(e,i),n.setScalar(0),n.addScaledVector(oi,r.x),n.addScaledVector(li,r.y),n.addScaledVector(hi,r.z),n}static isFrontFacing(e,t,s,i){return Qs.subVectors(s,t),Zs.subVectors(e,t),Qs.cross(Zs).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 Qs.subVectors(this.c,this.b),Zs.subVectors(this.a,this.b),.5*Qs.cross(Zs).length()}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return ui.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return ui.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,s,i,r){return ui.getInterpolation(e,this.a,this.b,this.c,t,s,i,r)}containsPoint(e){return ui.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return ui.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,a;ti.subVectors(i,s),si.subVectors(r,s),ri.subVectors(e,s);const o=ti.dot(ri),l=si.dot(ri);if(o<=0&&l<=0)return t.copy(s);ni.subVectors(e,i);const h=ti.dot(ni),u=si.dot(ni);if(h>=0&&u<=h)return t.copy(i);const c=o*u-h*l;if(c<=0&&o>=0&&h<=0)return n=o/(o-h),t.copy(s).addScaledVector(ti,n);ai.subVectors(e,r);const d=ti.dot(ai),p=si.dot(ai);if(p>=0&&d<=p)return t.copy(r);const m=d*l-o*p;if(m<=0&&l>=0&&p<=0)return a=l/(l-p),t.copy(s).addScaledVector(si,a);const f=h*p-d*u;if(f<=0&&u-h>=0&&d-p>=0)return ii.subVectors(r,i),a=(u-h)/(u-h+(d-p)),t.copy(i).addScaledVector(ii,a);const g=1/(f+m+c);return n=m*g,a=c*g,t.copy(s).addScaledVector(ti,n).addScaledVector(si,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}class ci{constructor(e=new Wt(1/0,1/0,1/0),t=new Wt(-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(pi.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,s=e.count;t<s;t++)this.expandByPoint(pi.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=pi.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,pi):pi.fromBufferAttribute(i,t),pi.applyMatrix4(e.matrixWorld),this.expandByPoint(pi);else void 0!==e.boundingBox?(null===e.boundingBox&&e.computeBoundingBox(),mi.copy(e.boundingBox)):(null===s.boundingBox&&s.computeBoundingBox(),mi.copy(s.boundingBox)),mi.applyMatrix4(e.matrixWorld),this.union(mi)}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,pi),pi.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(vi),Ti.subVectors(this.max,vi),fi.subVectors(e.a,vi),gi.subVectors(e.b,vi),yi.subVectors(e.c,vi),bi.subVectors(gi,fi),_i.subVectors(yi,gi),xi.subVectors(fi,yi);let t=[0,-bi.z,bi.y,0,-_i.z,_i.y,0,-xi.z,xi.y,bi.z,0,-bi.x,_i.z,0,-_i.x,xi.z,0,-xi.x,-bi.y,bi.x,0,-_i.y,_i.x,0,-xi.y,xi.x,0];return!!Mi(t,fi,gi,yi,Ti)&&(t=[1,0,0,0,1,0,0,0,1],!!Mi(t,fi,gi,yi,Ti)&&(Si.crossVectors(bi,_i),t=[Si.x,Si.y,Si.z],Mi(t,fi,gi,yi,Ti)))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,pi).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=.5*this.getSize(pi).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()||(di[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),di[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),di[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),di[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),di[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),di[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),di[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),di[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(di)),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 di=[new Wt,new Wt,new Wt,new Wt,new Wt,new Wt,new Wt,new Wt],pi=new Wt,mi=new ci,fi=new Wt,gi=new Wt,yi=new Wt,bi=new Wt,_i=new Wt,xi=new Wt,vi=new Wt,Ti=new Wt,Si=new Wt,wi=new Wt;function Mi(e,t,s,i,r){for(let n=0,a=e.length-3;n<=a;n+=3){wi.fromArray(e,n);const a=r.x*Math.abs(wi.x)+r.y*Math.abs(wi.y)+r.z*Math.abs(wi.z),o=t.dot(wi),l=s.dot(wi),h=i.dot(wi);if(Math.max(-Math.max(o,l,h),Math.min(o,l,h))>a)return!1}return!0}const Ei=Ai();function Ai(){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),a=new Uint32Array(64),o=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)a[e]=e<<23;a[31]=1199570944,a[32]=2147483648;for(let e=33;e<63;++e)a[e]=2147483648+(e-32<<23);a[63]=3347054592;for(let e=1;e<64;++e)32!==e&&(o[e]=1024);return{floatView:t,uint32View:s,baseTable:i,shiftTable:r,mantissaTable:n,exponentTable:a,offsetTable:o}}function Ni(e){Math.abs(e)>65504&&Et("DataUtils.toHalfFloat(): Value out of range."),e=It(e,-65504,65504),Ei.floatView[0]=e;const t=Ei.uint32View[0],s=t>>23&511;return Ei.baseTable[s]+((8388607&t)>>Ei.shiftTable[s])}function Ci(e){const t=e>>10;return Ei.uint32View[0]=Ei.mantissaTable[Ei.offsetTable[t]+(1023&e)]+Ei.exponentTable[t],Ei.floatView[0]}const Ri=new Wt,Pi=new $t;let Bi=0;class Fi extends Pt{constructor(e,t,s=!1){if(super(),Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:Bi++}),this.name="",this.array=e,this.itemSize=t,this.count=void 0!==e?e.length/t:0,this.normalized=s,this.usage=ct,this.updateRanges=[],this.gpuType=Q,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++)Pi.fromBufferAttribute(this,t),Pi.applyMatrix3(e),this.setXY(t,Pi.x,Pi.y);else if(3===this.itemSize)for(let t=0,s=this.count;t<s;t++)Ri.fromBufferAttribute(this,t),Ri.applyMatrix3(e),this.setXYZ(t,Ri.x,Ri.y,Ri.z);return this}applyMatrix4(e){for(let t=0,s=this.count;t<s;t++)Ri.fromBufferAttribute(this,t),Ri.applyMatrix4(e),this.setXYZ(t,Ri.x,Ri.y,Ri.z);return this}applyNormalMatrix(e){for(let t=0,s=this.count;t<s;t++)Ri.fromBufferAttribute(this,t),Ri.applyNormalMatrix(e),this.setXYZ(t,Ri.x,Ri.y,Ri.z);return this}transformDirection(e){for(let t=0,s=this.count;t<s;t++)Ri.fromBufferAttribute(this,t),Ri.transformDirection(e),this.setXYZ(t,Ri.x,Ri.y,Ri.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=zt(s,this.array)),s}setComponent(e,t,s){return this.normalized&&(s=Vt(s,this.array)),this.array[e*this.itemSize+t]=s,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=zt(t,this.array)),t}setX(e,t){return this.normalized&&(t=Vt(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=zt(t,this.array)),t}setY(e,t){return this.normalized&&(t=Vt(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=zt(t,this.array)),t}setZ(e,t){return this.normalized&&(t=Vt(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=zt(t,this.array)),t}setW(e,t){return this.normalized&&(t=Vt(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,s){return e*=this.itemSize,this.normalized&&(t=Vt(t,this.array),s=Vt(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=Vt(t,this.array),s=Vt(s,this.array),i=Vt(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=Vt(t,this.array),s=Vt(s,this.array),i=Vt(i,this.array),r=Vt(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 e.name=this.name,e.usage=this.usage,e.gpuType=this.gpuType,e}dispose(){this.dispatchEvent({type:"dispose"})}}class Li extends Fi{constructor(e,t,s){super(new Uint16Array(e),t,s)}}class Di extends Fi{constructor(e,t,s){super(new Uint32Array(e),t,s)}}class Oi extends Fi{constructor(e,t,s){super(new Uint16Array(e),t,s),this.isFloat16BufferAttribute=!0}getX(e){let t=Ci(this.array[e*this.itemSize]);return this.normalized&&(t=zt(t,this.array)),t}setX(e,t){return this.normalized&&(t=Vt(t,this.array)),this.array[e*this.itemSize]=Ni(t),this}getY(e){let t=Ci(this.array[e*this.itemSize+1]);return this.normalized&&(t=zt(t,this.array)),t}setY(e,t){return this.normalized&&(t=Vt(t,this.array)),this.array[e*this.itemSize+1]=Ni(t),this}getZ(e){let t=Ci(this.array[e*this.itemSize+2]);return this.normalized&&(t=zt(t,this.array)),t}setZ(e,t){return this.normalized&&(t=Vt(t,this.array)),this.array[e*this.itemSize+2]=Ni(t),this}getW(e){let t=Ci(this.array[e*this.itemSize+3]);return this.normalized&&(t=zt(t,this.array)),t}setW(e,t){return this.normalized&&(t=Vt(t,this.array)),this.array[e*this.itemSize+3]=Ni(t),this}setXY(e,t,s){return e*=this.itemSize,this.normalized&&(t=Vt(t,this.array),s=Vt(s,this.array)),this.array[e+0]=Ni(t),this.array[e+1]=Ni(s),this}setXYZ(e,t,s,i){return e*=this.itemSize,this.normalized&&(t=Vt(t,this.array),s=Vt(s,this.array),i=Vt(i,this.array)),this.array[e+0]=Ni(t),this.array[e+1]=Ni(s),this.array[e+2]=Ni(i),this}setXYZW(e,t,s,i,r){return e*=this.itemSize,this.normalized&&(t=Vt(t,this.array),s=Vt(s,this.array),i=Vt(i,this.array),r=Vt(r,this.array)),this.array[e+0]=Ni(t),this.array[e+1]=Ni(s),this.array[e+2]=Ni(i),this.array[e+3]=Ni(r),this}}class Ii extends Fi{constructor(e,t,s){super(new Float32Array(e),t,s)}}const Ui=new ci,ki=new Wt,zi=new Wt;class Vi{constructor(e=new Wt,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):Ui.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;ki.subVectors(e,this.center);const t=ki.lengthSq();if(t>this.radius*this.radius){const e=Math.sqrt(t),s=.5*(e-this.radius);this.center.addScaledVector(ki,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):(zi.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(ki.copy(e.center).add(zi)),this.expandByPoint(ki.copy(e.center).sub(zi))),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}}let Gi=0;const $i=new ps,ji=new zs,Wi=new Wt,Hi=new ci,qi=new ci,Xi=new Wt;class Yi extends Pt{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:Gi++}),this.uuid=Ot(),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={},this._transformed=!1}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(function(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}(e)?Di:Li)(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 Xt).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._transformed=!0,this}applyQuaternion(e){return $i.makeRotationFromQuaternion(e),this.applyMatrix4($i),this}rotateX(e){return $i.makeRotationX(e),this.applyMatrix4($i),this}rotateY(e){return $i.makeRotationY(e),this.applyMatrix4($i),this}rotateZ(e){return $i.makeRotationZ(e),this.applyMatrix4($i),this}translate(e,t,s){return $i.makeTranslation(e,t,s),this.applyMatrix4($i),this}scale(e,t,s){return $i.makeScale(e,t,s),this.applyMatrix4($i),this}lookAt(e){return ji.lookAt(e),ji.updateMatrix(),this.applyMatrix4(ji.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Wi).negate(),this.translate(Wi.x,Wi.y,Wi.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 Ii(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&&Et("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 ci);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return At("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),void this.boundingBox.set(new Wt(-1/0,-1/0,-1/0),new Wt(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];Hi.setFromBufferAttribute(s),this.morphTargetsRelative?(Xi.addVectors(this.boundingBox.min,Hi.min),this.boundingBox.expandByPoint(Xi),Xi.addVectors(this.boundingBox.max,Hi.max),this.boundingBox.expandByPoint(Xi)):(this.boundingBox.expandByPoint(Hi.min),this.boundingBox.expandByPoint(Hi.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&At('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 Vi);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return At("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),void this.boundingSphere.set(new Wt,1/0);if(e){const s=this.boundingSphere.center;if(Hi.setFromBufferAttribute(e),t)for(let e=0,s=t.length;e<s;e++){const s=t[e];qi.setFromBufferAttribute(s),this.morphTargetsRelative?(Xi.addVectors(Hi.min,qi.min),Hi.expandByPoint(Xi),Xi.addVectors(Hi.max,qi.max),Hi.expandByPoint(Xi)):(Hi.expandByPoint(qi.min),Hi.expandByPoint(qi.max))}Hi.getCenter(s);let i=0;for(let t=0,r=e.count;t<r;t++)Xi.fromBufferAttribute(e,t),i=Math.max(i,s.distanceToSquared(Xi));if(t)for(let r=0,n=t.length;r<n;r++){const n=t[r],a=this.morphTargetsRelative;for(let t=0,r=n.count;t<r;t++)Xi.fromBufferAttribute(n,t),a&&(Wi.fromBufferAttribute(e,t),Xi.add(Wi)),i=Math.max(i,s.distanceToSquared(Xi))}this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius)&&At('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 At("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");const s=t.position,i=t.normal,r=t.uv;let n=this.getAttribute("tangent");void 0!==n&&n.count===s.count||(n=new Fi(new Float32Array(4*s.count),4),this.setAttribute("tangent",n));const a=[],o=[];for(let e=0;e<s.count;e++)a[e]=new Wt,o[e]=new Wt;const l=new Wt,h=new Wt,u=new Wt,c=new $t,d=new $t,p=new $t,m=new Wt,f=new Wt;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),a[e].add(m),a[t].add(m),a[i].add(m),o[e].add(f),o[t].add(f),o[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 Wt,_=new Wt,x=new Wt,v=new Wt;function T(e){x.fromBufferAttribute(i,e),v.copy(x);const t=a[e];b.copy(t),b.sub(x.multiplyScalar(x.dot(t))).normalize(),_.crossVectors(v,t);const s=_.dot(o[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)T(e.getX(t+0)),T(e.getX(t+1)),T(e.getX(t+2))}this._transformed=!0}computeVertexNormals(){const e=this.index,t=this.getAttribute("position");if(void 0!==t){let s=this.getAttribute("normal");if(void 0===s||s.count!==t.count)s=new Fi(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 Wt,r=new Wt,n=new Wt,a=new Wt,o=new Wt,l=new Wt,h=new Wt,u=new Wt;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),a.fromBufferAttribute(s,d),o.fromBufferAttribute(s,p),l.fromBufferAttribute(s,m),a.add(h),o.add(h),l.add(h),s.setXYZ(d,a.x,a.y,a.z),s.setXYZ(p,o.x,o.y,o.z),s.setXYZ(m,l.x,l.y,l.z)}else for(let e=0,a=t.count;e<a;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++)Xi.fromBufferAttribute(e,t),Xi.normalize(),e.setXYZ(t,Xi.x,Xi.y,Xi.z)}toNonIndexed(){function e(e,t){const s=e.array,i=e.itemSize,r=e.normalized,n=new s.constructor(t.length*i);let a=0,o=0;for(let r=0,l=t.length;r<l;r++){a=e.isInterleavedBufferAttribute?t[r]*e.data.stride+e.offset:t[r]*i;for(let e=0;e<i;e++)n[o++]=s[a++]}return new Fi(n,i,r)}if(null===this.index)return Et("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new Yi,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=[],a=r[i];for(let t=0,i=a.length;t<i;t++){const i=e(a[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=void 0!==this.parameters&&!0===this._transformed?"BufferGeometry":this.type,e.name=this.name,Object.keys(this.userData).length>0&&(e.userData=this.userData),void 0!==this.parameters&&!0!==this._transformed){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 a=this.boundingSphere;return null!==a&&(e.data.boundingSphere=a.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 a=e.boundingBox;null!==a&&(this.boundingBox=a.clone());const o=e.boundingSphere;return null!==o&&(this.boundingSphere=o.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this._transformed=e._transformed,this}dispose(){this.dispatchEvent({type:"dispose"})}}class Ki{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=void 0!==e?e.length/t:0,this.usage=ct,this.updateRanges=[],this.version=0,this.uuid=Ot()}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=Ot()),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){void 0===e.arrayBuffers&&(e.arrayBuffers={}),void 0===this.array.buffer._uuid&&(this.array.buffer._uuid=Ot()),void 0===e.arrayBuffers[this.array.buffer._uuid]&&(e.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer)));const t={uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride};return t.usage=this.usage,t}}const Qi=new Wt;class Zi{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++)Qi.fromBufferAttribute(this,t),Qi.applyMatrix4(e),this.setXYZ(t,Qi.x,Qi.y,Qi.z);return this}applyNormalMatrix(e){for(let t=0,s=this.count;t<s;t++)Qi.fromBufferAttribute(this,t),Qi.applyNormalMatrix(e),this.setXYZ(t,Qi.x,Qi.y,Qi.z);return this}transformDirection(e){for(let t=0,s=this.count;t<s;t++)Qi.fromBufferAttribute(this,t),Qi.transformDirection(e),this.setXYZ(t,Qi.x,Qi.y,Qi.z);return this}getComponent(e,t){let s=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(s=zt(s,this.array)),s}setComponent(e,t,s){return this.normalized&&(s=Vt(s,this.array)),this.data.array[e*this.data.stride+this.offset+t]=s,this}setX(e,t){return this.normalized&&(t=Vt(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=Vt(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=Vt(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=Vt(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=zt(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=zt(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=zt(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=zt(t,this.array)),t}setXY(e,t,s){return e=e*this.data.stride+this.offset,this.normalized&&(t=Vt(t,this.array),s=Vt(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=Vt(t,this.array),s=Vt(s,this.array),i=Vt(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=Vt(t,this.array),s=Vt(s,this.array),i=Vt(i,this.array),r=Vt(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){wt("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 Fi(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 Zi(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(void 0===e){wt("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}}}const Ji=new Wt,er=new Wt,tr=new Xt;class sr{constructor(e=new Wt(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=Ji.subVectors(s,t).cross(er.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,s=!0){const i=e.delta(Ji),r=this.normal.dot(i);if(0===r)return 0===this.distanceToPoint(e.start)?t.copy(e.start):null;const n=-(e.start.dot(this.normal)+this.constant)/r;return!0===s&&(n<0||n>1)?null:t.copy(e.start).addScaledVector(i,n)}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||tr.getNormalMatrix(e),i=this.coplanarPoint(Ji).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)}toJSON(){return{normal:this.normal.toArray(),constant:this.constant}}fromJSON(e){return this.normal.fromArray(e.normal),this.constant=e.constant,this}}let ir=0;class rr extends Pt{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:ir++}),this.uuid=Ot(),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=204,this.blendDst=205,this.blendEquation=n,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new Xs(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=st,this.stencilZFail=st,this.stencilZPass=st,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){Et(`Material: parameter '${t}' has value of undefined.`);continue}const i=this[t];void 0!==i?i&&i.isColor?i.set(s):i&&i.isVector2&&s&&s.isVector2||i&&i.isEuler&&s&&s.isEuler||i&&i.isVector3&&s&&s.isVector3?i.copy(s):this[t]=s:Et(`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,s.blending=this.blending,s.side=this.side,s.shadowSide=this.shadowSide,s.vertexColors=this.vertexColors,s.opacity=this.opacity,s.transparent=this.transparent,s.blendSrc=this.blendSrc,s.blendDst=this.blendDst,s.blendEquation=this.blendEquation,s.blendSrcAlpha=this.blendSrcAlpha,s.blendDstAlpha=this.blendDstAlpha,s.blendEquationAlpha=this.blendEquationAlpha,s.blendColor=this.blendColor.getHex(),s.blendAlpha=this.blendAlpha,s.depthFunc=this.depthFunc,s.depthTest=this.depthTest,s.depthWrite=this.depthWrite,s.colorWrite=this.colorWrite,s.clipIntersection=this.clipIntersection,s.clipShadows=this.clipShadows,s.stencilWriteMask=this.stencilWriteMask,s.stencilFunc=this.stencilFunc,s.stencilRef=this.stencilRef,s.stencilFuncMask=this.stencilFuncMask,s.stencilFail=this.stencilFail,s.stencilZFail=this.stencilZFail,s.stencilZPass=this.stencilZPass,s.stencilWrite=this.stencilWrite,s.polygonOffset=this.polygonOffset,s.polygonOffsetFactor=this.polygonOffsetFactor,s.polygonOffsetUnits=this.polygonOffsetUnits,s.dithering=this.dithering,s.alphaTest=this.alphaTest,s.alphaHash=this.alphaHash,s.alphaToCoverage=this.alphaToCoverage,s.premultipliedAlpha=this.premultipliedAlpha,s.forceSinglePass=this.forceSinglePass,s.allowOverride=this.allowOverride,s.visible=this.visible,s.toneMapped=this.toneMapped,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&&(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.retroreflectivity&&(s.retroreflectivity=this.retroreflectivity),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&&(s.attenuationDistance=this.attenuationDistance),void 0!==this.attenuationColor&&(s.attenuationColor=this.attenuationColor.getHex()),void 0!==this.size&&(s.size=this.size),void 0!==this.sizeAttenuation&&(s.sizeAttenuation=this.sizeAttenuation),Array.isArray(this.clippingPlanes)&&this.clippingPlanes.length>0&&(s.clippingPlanes=this.clippingPlanes.map(e=>e.toJSON())),void 0!==this.rotation&&(s.rotation=this.rotation),void 0!==this.depthPacking&&(s.depthPacking=this.depthPacking),void 0!==this.linewidth&&(s.linewidth=this.linewidth),void 0!==this.linecap&&(s.linecap=this.linecap),void 0!==this.linejoin&&(s.linejoin=this.linejoin),void 0!==this.dashSize&&(s.dashSize=this.dashSize),void 0!==this.gapSize&&(s.gapSize=this.gapSize),void 0!==this.scale&&(s.scale=this.scale),void 0!==this.wireframe&&(s.wireframe=this.wireframe),void 0!==this.wireframeLinewidth&&(s.wireframeLinewidth=this.wireframeLinewidth),void 0!==this.wireframeLinecap&&(s.wireframeLinecap=this.wireframeLinecap),void 0!==this.wireframeLinejoin&&(s.wireframeLinejoin=this.wireframeLinejoin),void 0!==this.flatShading&&(s.flatShading=this.flatShading),void 0!==this.fog&&(s.fog=this.fog),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}fromJSON(e,t){if(void 0!==e.uuid&&(this.uuid=e.uuid),void 0!==e.name&&(this.name=e.name),void 0!==e.color&&void 0!==this.color&&this.color.setHex(e.color),void 0!==e.roughness&&(this.roughness=e.roughness),void 0!==e.metalness&&(this.metalness=e.metalness),void 0!==e.sheen&&(this.sheen=e.sheen),void 0!==e.sheenColor&&(this.sheenColor=(new Xs).setHex(e.sheenColor)),void 0!==e.sheenRoughness&&(this.sheenRoughness=e.sheenRoughness),void 0!==e.emissive&&void 0!==this.emissive&&this.emissive.setHex(e.emissive),void 0!==e.specular&&void 0!==this.specular&&this.specular.setHex(e.specular),void 0!==e.specularIntensity&&(this.specularIntensity=e.specularIntensity),void 0!==e.specularColor&&void 0!==this.specularColor&&this.specularColor.setHex(e.specularColor),void 0!==e.shininess&&(this.shininess=e.shininess),void 0!==e.clearcoat&&(this.clearcoat=e.clearcoat),void 0!==e.clearcoatRoughness&&(this.clearcoatRoughness=e.clearcoatRoughness),void 0!==e.dispersion&&(this.dispersion=e.dispersion),void 0!==e.retroreflectivity&&(this.retroreflectivity=e.retroreflectivity),void 0!==e.iridescence&&(this.iridescence=e.iridescence),void 0!==e.iridescenceIOR&&(this.iridescenceIOR=e.iridescenceIOR),void 0!==e.iridescenceThicknessRange&&(this.iridescenceThicknessRange=e.iridescenceThicknessRange),void 0!==e.transmission&&(this.transmission=e.transmission),void 0!==e.thickness&&(this.thickness=e.thickness),void 0!==e.attenuationDistance&&(this.attenuationDistance=e.attenuationDistance),void 0!==e.attenuationColor&&void 0!==this.attenuationColor&&this.attenuationColor.setHex(e.attenuationColor),void 0!==e.anisotropy&&(this.anisotropy=e.anisotropy),void 0!==e.anisotropyRotation&&(this.anisotropyRotation=e.anisotropyRotation),void 0!==e.fog&&(this.fog=e.fog),void 0!==e.flatShading&&(this.flatShading=e.flatShading),void 0!==e.blending&&(this.blending=e.blending),void 0!==e.combine&&(this.combine=e.combine),void 0!==e.side&&(this.side=e.side),void 0!==e.shadowSide&&(this.shadowSide=e.shadowSide),void 0!==e.opacity&&(this.opacity=e.opacity),void 0!==e.transparent&&(this.transparent=e.transparent),void 0!==e.alphaTest&&(this.alphaTest=e.alphaTest),void 0!==e.alphaHash&&(this.alphaHash=e.alphaHash),void 0!==e.depthFunc&&(this.depthFunc=e.depthFunc),void 0!==e.depthTest&&(this.depthTest=e.depthTest),void 0!==e.depthWrite&&(this.depthWrite=e.depthWrite),void 0!==e.colorWrite&&(this.colorWrite=e.colorWrite),void 0!==e.clippingPlanes&&(this.clippingPlanes=e.clippingPlanes.map(e=>(new sr).fromJSON(e))),void 0!==e.clipIntersection&&(this.clipIntersection=e.clipIntersection),void 0!==e.clipShadows&&(this.clipShadows=e.clipShadows),void 0!==e.depthPacking&&(this.depthPacking=e.depthPacking),void 0!==e.blendSrc&&(this.blendSrc=e.blendSrc),void 0!==e.blendDst&&(this.blendDst=e.blendDst),void 0!==e.blendEquation&&(this.blendEquation=e.blendEquation),void 0!==e.blendSrcAlpha&&(this.blendSrcAlpha=e.blendSrcAlpha),void 0!==e.blendDstAlpha&&(this.blendDstAlpha=e.blendDstAlpha),void 0!==e.blendEquationAlpha&&(this.blendEquationAlpha=e.blendEquationAlpha),void 0!==e.blendColor&&void 0!==this.blendColor&&this.blendColor.setHex(e.blendColor),void 0!==e.blendAlpha&&(this.blendAlpha=e.blendAlpha),void 0!==e.stencilWriteMask&&(this.stencilWriteMask=e.stencilWriteMask),void 0!==e.stencilFunc&&(this.stencilFunc=e.stencilFunc),void 0!==e.stencilRef&&(this.stencilRef=e.stencilRef),void 0!==e.stencilFuncMask&&(this.stencilFuncMask=e.stencilFuncMask),void 0!==e.stencilFail&&(this.stencilFail=e.stencilFail),void 0!==e.stencilZFail&&(this.stencilZFail=e.stencilZFail),void 0!==e.stencilZPass&&(this.stencilZPass=e.stencilZPass),void 0!==e.stencilWrite&&(this.stencilWrite=e.stencilWrite),void 0!==e.wireframe&&(this.wireframe=e.wireframe),void 0!==e.wireframeLinewidth&&(this.wireframeLinewidth=e.wireframeLinewidth),void 0!==e.wireframeLinecap&&(this.wireframeLinecap=e.wireframeLinecap),void 0!==e.wireframeLinejoin&&(this.wireframeLinejoin=e.wireframeLinejoin),void 0!==e.rotation&&(this.rotation=e.rotation),void 0!==e.linewidth&&(this.linewidth=e.linewidth),void 0!==e.linecap&&(this.linecap=e.linecap),void 0!==e.linejoin&&(this.linejoin=e.linejoin),void 0!==e.dashSize&&(this.dashSize=e.dashSize),void 0!==e.gapSize&&(this.gapSize=e.gapSize),void 0!==e.scale&&(this.scale=e.scale),void 0!==e.polygonOffset&&(this.polygonOffset=e.polygonOffset),void 0!==e.polygonOffsetFactor&&(this.polygonOffsetFactor=e.polygonOffsetFactor),void 0!==e.polygonOffsetUnits&&(this.polygonOffsetUnits=e.polygonOffsetUnits),void 0!==e.dithering&&(this.dithering=e.dithering),void 0!==e.alphaToCoverage&&(this.alphaToCoverage=e.alphaToCoverage),void 0!==e.premultipliedAlpha&&(this.premultipliedAlpha=e.premultipliedAlpha),void 0!==e.forceSinglePass&&(this.forceSinglePass=e.forceSinglePass),void 0!==e.allowOverride&&(this.allowOverride=e.allowOverride),void 0!==e.visible&&(this.visible=e.visible),void 0!==e.toneMapped&&(this.toneMapped=e.toneMapped),void 0!==e.userData&&(this.userData=e.userData),void 0!==e.vertexColors&&("number"==typeof e.vertexColors?this.vertexColors=e.vertexColors>0:this.vertexColors=e.vertexColors),void 0!==e.size&&(this.size=e.size),void 0!==e.sizeAttenuation&&(this.sizeAttenuation=e.sizeAttenuation),void 0!==e.map&&(this.map=t[e.map]||null),void 0!==e.matcap&&(this.matcap=t[e.matcap]||null),void 0!==e.alphaMap&&(this.alphaMap=t[e.alphaMap]||null),void 0!==e.bumpMap&&(this.bumpMap=t[e.bumpMap]||null),void 0!==e.bumpScale&&(this.bumpScale=e.bumpScale),void 0!==e.normalMap&&(this.normalMap=t[e.normalMap]||null),void 0!==e.normalMapType&&(this.normalMapType=e.normalMapType),void 0!==e.normalScale){let t=e.normalScale;!1===Array.isArray(t)&&(t=[t,t]),this.normalScale=(new $t).fromArray(t)}return void 0!==e.displacementMap&&(this.displacementMap=t[e.displacementMap]||null),void 0!==e.displacementScale&&(this.displacementScale=e.displacementScale),void 0!==e.displacementBias&&(this.displacementBias=e.displacementBias),void 0!==e.roughnessMap&&(this.roughnessMap=t[e.roughnessMap]||null),void 0!==e.metalnessMap&&(this.metalnessMap=t[e.metalnessMap]||null),void 0!==e.emissiveMap&&(this.emissiveMap=t[e.emissiveMap]||null),void 0!==e.emissiveIntensity&&(this.emissiveIntensity=e.emissiveIntensity),void 0!==e.specularMap&&(this.specularMap=t[e.specularMap]||null),void 0!==e.specularIntensityMap&&(this.specularIntensityMap=t[e.specularIntensityMap]||null),void 0!==e.specularColorMap&&(this.specularColorMap=t[e.specularColorMap]||null),void 0!==e.envMap&&(this.envMap=t[e.envMap]||null),void 0!==e.envMapRotation&&this.envMapRotation.fromArray(e.envMapRotation),void 0!==e.envMapIntensity&&(this.envMapIntensity=e.envMapIntensity),void 0!==e.reflectivity&&(this.reflectivity=e.reflectivity),void 0!==e.refractionRatio&&(this.refractionRatio=e.refractionRatio),void 0!==e.lightMap&&(this.lightMap=t[e.lightMap]||null),void 0!==e.lightMapIntensity&&(this.lightMapIntensity=e.lightMapIntensity),void 0!==e.aoMap&&(this.aoMap=t[e.aoMap]||null),void 0!==e.aoMapIntensity&&(this.aoMapIntensity=e.aoMapIntensity),void 0!==e.gradientMap&&(this.gradientMap=t[e.gradientMap]||null),void 0!==e.clearcoatMap&&(this.clearcoatMap=t[e.clearcoatMap]||null),void 0!==e.clearcoatRoughnessMap&&(this.clearcoatRoughnessMap=t[e.clearcoatRoughnessMap]||null),void 0!==e.clearcoatNormalMap&&(this.clearcoatNormalMap=t[e.clearcoatNormalMap]||null),void 0!==e.clearcoatNormalScale&&(this.clearcoatNormalScale=(new $t).fromArray(e.clearcoatNormalScale)),void 0!==e.iridescenceMap&&(this.iridescenceMap=t[e.iridescenceMap]||null),void 0!==e.iridescenceThicknessMap&&(this.iridescenceThicknessMap=t[e.iridescenceThicknessMap]||null),void 0!==e.transmissionMap&&(this.transmissionMap=t[e.transmissionMap]||null),void 0!==e.thicknessMap&&(this.thicknessMap=t[e.thicknessMap]||null),void 0!==e.anisotropyMap&&(this.anisotropyMap=t[e.anisotropyMap]||null),void 0!==e.sheenColorMap&&(this.sheenColorMap=t[e.sheenColorMap]||null),void 0!==e.sheenRoughnessMap&&(this.sheenRoughnessMap=t[e.sheenRoughnessMap]||null),this}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 nr extends rr{constructor(e){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new Xs(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}}const ar=new Wt,or=new Wt,lr=new Wt,hr=new Wt;class ur{constructor(e=new Wt,t=new Wt(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,ar)),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=ar.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(ar.copy(this.origin).addScaledVector(this.direction,t),ar.distanceToSquared(e))}distanceSqToSegment(e,t,s,i){or.copy(e).add(t).multiplyScalar(.5),lr.copy(t).sub(e).normalize(),hr.copy(this.origin).sub(or);const r=.5*e.distanceTo(t),n=-this.direction.dot(lr),a=hr.dot(this.direction),o=-hr.dot(lr),l=hr.lengthSq(),h=Math.abs(1-n*n);let u,c,d,p;if(h>0)if(u=n*o-a,c=n*a-o,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*a)+c*(n*u+c+2*o)+l}else c=r,u=Math.max(0,-(n*c+a)),d=-u*u+c*(c+2*o)+l;else c=-r,u=Math.max(0,-(n*c+a)),d=-u*u+c*(c+2*o)+l;else c<=-p?(u=Math.max(0,-(-n*r+a)),c=u>0?-r:Math.min(Math.max(-r,-o),r),d=-u*u+c*(c+2*o)+l):c<=p?(u=0,c=Math.min(Math.max(-r,-o),r),d=c*(c+2*o)+l):(u=Math.max(0,-(n*r+a)),c=u>0?r:Math.min(Math.max(-r,-o),r),d=-u*u+c*(c+2*o)+l);else c=n>0?-r:r,u=Math.max(0,-(n*c+a)),d=-u*u+c*(c+2*o)+l;return s&&s.copy(this.origin).addScaledVector(this.direction,u),i&&i.copy(or).addScaledVector(lr,c),d}intersectSphere(e,t){if(e.radius<0)return null;ar.subVectors(e.center,this.origin);const s=ar.dot(this.direction),i=ar.dot(ar)-s*s,r=e.radius*e.radius;if(i>r)return null;const n=Math.sqrt(r-i),a=s-n,o=s+n;return o<0?null:a<0?this.at(o,t):this.at(a,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,a,o;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?(a=(e.min.z-c.z)*u,o=(e.max.z-c.z)*u):(a=(e.max.z-c.z)*u,o=(e.min.z-c.z)*u),s>o||a>i?null:((a>s||s!=s)&&(s=a),(o<i||i!=i)&&(i=o),i<0?null:this.at(s>=0?s:i,t)))}intersectsBox(e){return null!==this.intersectBox(e,ar)}intersectTriangle(e,t,s,i,r){const n=this.origin,a=this.direction,o=a.x,l=a.y,h=a.z,u=e.x-n.x,c=e.y-n.y,d=e.z-n.z,p=t.x-n.x,m=t.y-n.y,f=t.z-n.z,g=s.x-n.x,y=s.y-n.y,b=s.z-n.z,_=Math.abs(o),x=Math.abs(l),v=Math.abs(h);let T,S,w,M,E,A,N,C,R,P,B,F;if(_>=x&&_>=v?(w=o,A=u,R=p,F=g,o>=0?(T=l,S=h,M=c,E=d,N=m,C=f,P=y,B=b):(T=h,S=l,M=d,E=c,N=f,C=m,P=b,B=y)):x>=v?(w=l,A=c,R=m,F=y,l>=0?(T=h,S=o,M=d,E=u,N=f,C=p,P=b,B=g):(T=o,S=h,M=u,E=d,N=p,C=f,P=g,B=b)):(w=h,A=d,R=f,F=b,h>=0?(T=o,S=l,M=u,E=c,N=p,C=m,P=g,B=y):(T=l,S=o,M=c,E=u,N=m,C=p,P=y,B=g)),0===w)return null;const L=T/w,D=S/w,O=M-L*A,I=E-D*A,U=N-L*R,k=C-D*R,z=P-L*F,V=B-D*F,G=z*k-V*U,$=O*V-I*z,j=U*I-k*O;if(i){if(G<0||$<0||j<0)return null}else if((G<0||$<0||j<0)&&(G>0||$>0||j>0))return null;const W=G+$+j;if(0===W)return null;const H=1/w*(G*A+$*R+j*F);return(W>0?H<0:H>0)?null:this.at(H/W,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 cr extends rr{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Xs(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 Ss,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 dr=new ps,pr=new ur,mr=new Vi,fr=new Wt,gr=new Wt,yr=new Wt,br=new Wt,_r=new Wt,xr=new Wt,vr=new Wt,Tr=new Wt;class Sr extends zs{constructor(e=new Yi,t=new cr){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 a=this.morphTargetInfluences;if(r&&a){xr.set(0,0,0);for(let s=0,i=r.length;s<i;s++){const i=a[s],o=r[s];0!==i&&(_r.fromBufferAttribute(o,e),n?xr.addScaledVector(_r,i):xr.addScaledVector(_r.sub(t),i))}t.add(xr)}return t}intersectsFrustum(e){return e.intersectsObject(this)}raycast(e,t){const s=this.geometry,i=this.material,r=this.matrixWorld;if(void 0!==i){if(null===s.boundingSphere&&s.computeBoundingSphere(),mr.copy(s.boundingSphere),mr.applyMatrix4(r),pr.copy(e.ray).recast(e.near),!1===mr.containsPoint(pr.origin)){if(null===pr.intersectSphere(mr,fr))return;if(pr.origin.distanceToSquared(fr)>(e.far-e.near)**2)return}dr.copy(r).invert(),pr.copy(e.ray).applyMatrix4(dr),null!==s.boundingBox&&!1===pr.intersectsBox(s.boundingBox)||this._computeIntersections(e,t,pr)}}_computeIntersections(e,t,s){let i;const r=this.geometry,n=this.material,a=r.index,o=r.attributes.position,l=r.attributes.uv,h=r.attributes.uv1,u=r.attributes.normal,c=r.groups,d=r.drawRange;if(null!==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=wr(this,p,e,s,l,h,u,a.getX(r),a.getX(r+1),a.getX(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=wr(this,n,e,s,l,h,u,a.getX(r),a.getX(r+1),a.getX(r+2)),i&&(i.faceIndex=Math.floor(r/3),t.push(i))}}else if(void 0!==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=wr(this,p,e,s,l,h,u,r,r+1,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=wr(this,n,e,s,l,h,u,r,r+1,r+2),i&&(i.faceIndex=Math.floor(r/3),t.push(i))}}}}function wr(e,t,s,i,r,n,a,o,l,h){e.getVertexPosition(o,gr),e.getVertexPosition(l,yr),e.getVertexPosition(h,br);const u=function(e,t,s,i,r,n,a,o){let l;if(l=1===t.side?i.intersectTriangle(a,n,r,!0,o):i.intersectTriangle(r,n,a,0===t.side,o),null===l)return null;Tr.copy(o),Tr.applyMatrix4(e.matrixWorld);const h=s.ray.origin.distanceTo(Tr);return h<s.near||h>s.far?null:{distance:h,point:Tr.clone(),object:e}}(e,t,s,i,gr,yr,br,vr);if(u){const e=new Wt;ui.getBarycoord(vr,gr,yr,br,e),r&&(u.uv=ui.getInterpolatedAttribute(r,o,l,h,e,new $t)),n&&(u.uv1=ui.getInterpolatedAttribute(n,o,l,h,e,new $t)),a&&(u.normal=ui.getInterpolatedAttribute(a,o,l,h,e,new Wt),u.normal.dot(i.direction)>0&&u.normal.multiplyScalar(-1));const t={a:o,b:l,c:h,normal:new Wt,materialIndex:0};ui.getNormal(gr,yr,br,t.normal),u.face=t,u.barycoord=e}return u}class Mr extends hs{constructor(e=null,t=1,s=1,i,r,n,a,o,l=1003,h=1003,u,c){super(null,n,a,o,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 Er extends Fi{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 Ar=new Vi,Nr=new $t(.5,.5),Cr=new Wt;class Rr{constructor(e=new sr,t=new sr,s=new sr,i=new sr,r=new sr,n=new sr){this.planes=[e,t,s,i,r,n]}set(e,t,s,i,r,n){const a=this.planes;return a[0].copy(e),a[1].copy(t),a[2].copy(s),a[3].copy(i),a[4].copy(r),a[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],a=r[1],o=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],_=r[14],x=r[15];if(i[0].setComponents(l-n,d-h,g-p,x-y).normalize(),i[1].setComponents(l+n,d+h,g+p,x+y).normalize(),i[2].setComponents(l+a,d+u,g+m,x+b).normalize(),i[3].setComponents(l-a,d-u,g-m,x-b).normalize(),s)i[4].setComponents(o,c,f,_).normalize(),i[5].setComponents(l-o,d-c,g-f,x-_).normalize();else if(i[4].setComponents(l-o,d-c,g-f,x-_).normalize(),t===pt)i[5].setComponents(l+o,d+c,g+f,x+_).normalize();else{if(t!==mt)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);i[5].setComponents(o,c,f,_).normalize()}return this}intersectsObject(e){if(void 0!==e.boundingSphere)null===e.boundingSphere&&e.computeBoundingSphere(),Ar.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;null===t.boundingSphere&&t.computeBoundingSphere(),Ar.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Ar)}intersectsSprite(e){Ar.center.set(0,0,0);const t=Nr.distanceTo(e.center);return Ar.radius=.7071067811865476+t,Ar.applyMatrix4(e.matrixWorld),this.intersectsSphere(Ar)}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(Cr.x=i.normal.x>0?e.max.x:e.min.x,Cr.y=i.normal.y>0?e.max.y:e.min.y,Cr.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(Cr)<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 Pr=new ps;class Br{constructor(){this.coordinateSystem=pt,this._frustums=[],this._count=0}setFromArrayCamera(e){const t=e.cameras,s=this._frustums;for(let e=0;e<t.length;e++){const i=t[e];Pr.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),void 0===s[e]&&(s[e]=new Rr),s[e].setFromProjectionMatrix(Pr,i.coordinateSystem,i.reversedDepth)}return this._count=t.length,this}intersectsObject(e){const t=this._frustums;for(let s=0;s<this._count;s++)if(t[s].intersectsObject(e))return!0;return!1}intersectsSprite(e){const t=this._frustums;for(let s=0;s<this._count;s++)if(t[s].intersectsSprite(e))return!0;return!1}intersectsSphere(e){const t=this._frustums;for(let s=0;s<this._count;s++)if(t[s].intersectsSphere(e))return!0;return!1}intersectsBox(e){const t=this._frustums;for(let s=0;s<this._count;s++)if(t[s].intersectsBox(e))return!0;return!1}containsPoint(e){const t=this._frustums;for(let s=0;s<this._count;s++)if(t[s].containsPoint(e))return!0;return!1}copy(e){this.coordinateSystem=e.coordinateSystem;const t=this._frustums,s=e._frustums;for(let i=0;i<e._count;i++)void 0===t[i]&&(t[i]=new Rr),t[i].copy(s[i]);return this._count=e._count,this}clone(){return(new Br).copy(this)}}class Fr extends rr{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new Xs(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 Lr extends rr{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new Xs(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 Dr extends hs{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=k,this.minFilter=k,this.generateMipmaps=!1,this.needsUpdate=!0}}class Or extends hs{constructor(e=[],t=301,s,i,r,n,a,o,l,h){super(e,t,s,i,r,n,a,o,l,h),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class Ir extends hs{constructor(e,t,s=1014,i,r,n,a=1003,o=1003,l,h=1026,u=1){if(h!==oe&&h!==le)throw new Error("THREE.DepthTexture: format must be either THREE.DepthFormat or THREE.DepthStencilFormat");super({width:e,height:t,depth:u},i,r,n,a,o,h,s,l),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new ns(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return t.compareFunction=this.compareFunction,t}}class Ur extends Ir{constructor(e,t=1014,s=301,i,r,n=1003,a=1003,o,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,a,o,l),this.image=u,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}}class kr extends Yi{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 a=this;i=Math.floor(i),r=Math.floor(r),n=Math.floor(n);const o=[],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,_=p/g,x=n/2,v=p/2,T=m/2,S=f+1,w=g+1;let M=0,E=0;const A=new Wt;for(let n=0;n<w;n++){const a=n*_-v;for(let o=0;o<S;o++){const c=o*b-x;A[e]=c*i,A[t]=a*r,A[s]=T,l.push(A.x,A.y,A.z),A[e]=0,A[t]=0,A[s]=m>0?1:-1,h.push(A.x,A.y,A.z),u.push(o/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+S*e,i=c+t+S*(e+1),r=c+(t+1)+S*(e+1),n=c+(t+1)+S*e;o.push(s,i,n),o.push(i,r,n),E+=6}a.addGroup(d,E,y),d+=E,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(o),this.setAttribute("position",new Ii(l,3)),this.setAttribute("normal",new Ii(h,3)),this.setAttribute("uv",new Ii(u,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new kr(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}class zr extends Yi{constructor(e=1,t=1,s=1,i=32,r=1,n=!1,a=0,o=2*Math.PI){super(),this.type="CylinderGeometry",this.parameters={radiusTop:e,radiusBottom:t,height:s,radialSegments:i,heightSegments:r,openEnded:n,thetaStart:a,thetaLength:o};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 $t,m=new Wt;let y=0;const b=!0===s?e:t,_=!0===s?1:-1;for(let e=1;e<=i;e++)u.push(0,f*_,0),c.push(0,_,0),d.push(.5,.5),p++;const x=p;for(let e=0;e<=i;e++){const t=e/i*o+a,s=Math.cos(t),r=Math.sin(t);m.x=b*r,m.y=f*_,m.z=b*s,u.push(m.x,m.y,m.z),c.push(0,_,0),n.x=.5*s+.5,n.y=.5*r*_+.5,d.push(n.x,n.y),p++}for(let e=0;e<i;e++){const t=r+e,i=x+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 Wt,y=new Wt;let b=0;const _=(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*o+a,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,_,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],a=m[i+1][s],o=m[i+1][s+1],l=m[i][s+1];(e>0||0!==i)&&(h.push(n,a,l),b+=3),(t>0||i!==r-1)&&(h.push(a,o,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 Ii(u,3)),this.setAttribute("normal",new Ii(c,3)),this.setAttribute("uv",new Ii(d,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new zr(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class Vr extends Yi{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,a=Math.floor(s),o=Math.floor(i),l=a+1,h=o+1,u=e/a,c=t/o,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/a),f.push(1-e/o)}}for(let e=0;e<o;e++)for(let t=0;t<a;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 Ii(p,3)),this.setAttribute("normal",new Ii(m,3)),this.setAttribute("uv",new Ii(f,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Vr(e.width,e.height,e.widthSegments,e.heightSegments)}}class Gr extends Yi{constructor(e=1,t=32,s=16,i=0,r=2*Math.PI,n=0,a=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:e,widthSegments:t,heightSegments:s,phiStart:i,phiLength:r,thetaStart:n,thetaLength:a},t=Math.max(3,Math.floor(t)),s=Math.max(2,Math.floor(s));const o=Math.min(n+a,Math.PI);let l=0;const h=[],u=new Wt,c=new Wt,d=[],p=[],m=[],f=[];for(let d=0;d<=s;d++){const g=[],y=d/s,b=n+y*a,_=e*Math.cos(b),x=Math.sqrt(e*e-_*_);let v=0;0===d&&0===n?v=.5/t:d===s&&o===Math.PI&&(v=-.5/t);for(let e=0;e<=t;e++){const s=e/t,n=i+s*r;u.x=-x*Math.cos(n),u.y=_,u.z=x*Math.sin(n),p.push(u.x,u.y,u.z),c.copy(u).normalize(),m.push(c.x,c.y,c.z),f.push(s+v,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],a=h[e+1][i],l=h[e+1][i+1];(0!==e||n>0)&&d.push(t,r,l),(e!==s-1||o<Math.PI)&&d.push(r,a,l)}this.setIndex(d),this.setAttribute("position",new Ii(p,3)),this.setAttribute("normal",new Ii(m,3)),this.setAttribute("uv",new Ii(f,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Gr(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}}class $r extends rr{constructor(e){super(),this.isShadowMaterial=!0,this.type="ShadowMaterial",this.color=new Xs(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 jr extends rr{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new Xs(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 Xs(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new $t(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 Ss,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 Wr extends jr{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 $t(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return It(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 Xs(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 Xs(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new Xs(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._retroreflectivity=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 retroreflectivity(){return this._retroreflectivity}set retroreflectivity(e){this._retroreflectivity>0!=e>0&&this.version++,this._retroreflectivity=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.retroreflectivity=e.retroreflectivity,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 Hr extends rr{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new Xs(16777215),this.specular=new Xs(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Xs(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new $t(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Ss,this.combine=0,this.reflectivity=1,this.envMapIntensity=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.envMapIntensity=e.envMapIntensity,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 qr extends rr{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new Xs(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Xs(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new $t(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 Xr extends rr{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new $t(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 Yr extends rr{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new Xs(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Xs(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new $t(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Ss,this.combine=0,this.reflectivity=1,this.envMapIntensity=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.envMapIntensity=e.envMapIntensity,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 Kr extends rr{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new Xs(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new $t(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 Qr extends Fr{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 Zr extends zs{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new Xs(e),this.intensity=t}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 Jr extends Zr{constructor(e,t,s){super(e,s),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(zs.DEFAULT_UP),this.updateMatrix(),this.groundColor=new Xs(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 en=new ps,tn=new Wt,sn=new Wt;class rn{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.biasNode=null,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new $t(512,512),this.mapType=W,this.map=null,this.mapPass=null,this.matrix=new ps,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new Rr,this._frameExtents=new $t(1,1),this._viewportCount=1,this._viewports=[new us(0,0,1,1)]}getViewportCount(){return this._viewportCount}getCamera(){return this.camera}getFrustum(){return this._frustum}updateMatrices(e){const t=this.camera;tn.setFromMatrixPosition(e.matrixWorld),t.position.copy(tn),sn.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(sn),t.updateMatrixWorld(),this._updateMatrix(t,this.matrix,this._frustum)}_updateMatrix(e,t,s,i){en.multiplyMatrices(e.projectionMatrix,e.matrixWorldInverse),s.setFromProjectionMatrix(en,e.coordinateSystem,e.reversedDepth);const r=this._frameExtents,n=i?i.z/r.x:1,a=i?i.w/r.y:1,o=i?i.x/r.x:0,l=i?i.y/r.y:0;e.coordinateSystem===mt||e.reversedDepth?t.set(.5*n,0,0,.5*n+o,0,.5*a,0,.5*a+l,0,0,1,0,0,0,0,1):t.set(.5*n,0,0,.5*n+o,0,.5*a,0,.5*a+l,0,0,.5,.5,0,0,0,1),t.multiply(en)}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.biasNode=e.biasNode,this}clone(){return(new this.constructor).copy(this)}toJSON(){const e={};return e.intensity=this.intensity,e.bias=this.bias,e.normalBias=this.normalBias,e.radius=this.radius,e.blurSamples=this.blurSamples,e.mapSize=this.mapSize.toArray(),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}}const nn=new Wt,an=new jt,on=new Wt;class ln extends zs{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new ps,this.projectionMatrix=new ps,this.projectionMatrixInverse=new ps,this.coordinateSystem=pt,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.matrixWorld.decompose(nn,an,on),1===on.x&&1===on.y&&1===on.z?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(nn,an,on.set(1,1,1)).invert()}updateWorldMatrix(e,t,s=!1){super.updateWorldMatrix(e,t,s),this.matrixWorld.decompose(nn,an,on),1===on.x&&1===on.y&&1===on.z?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(nn,an,on.set(1,1,1)).invert()}clone(){return(new this.constructor).copy(this)}}const hn=new Wt,un=new $t,cn=new $t;class dn extends ln{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*Dt*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(.5*Lt*this.fov);return.5*this.getFilmHeight()/e}getEffectiveFOV(){return 2*Dt*Math.atan(Math.tan(.5*Lt*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){hn.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(hn.x,hn.y).multiplyScalar(-e/hn.z),hn.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),s.set(hn.x,hn.y).multiplyScalar(-e/hn.z)}getViewSize(e,t){return this.getViewBounds(e,un,cn),t.subVectors(cn,un)}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*Lt*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,a=n.fullHeight;r+=n.offsetX*i/e,t-=n.offsetY*s/a,i*=n.width/e,s*=n.height/a}const a=this.filmOffset;0!==a&&(r+=e*a/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}}class pn extends rn{constructor(){super(new dn(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1,this.aspect=1}updateMatrices(e){const t=this.camera,s=2*Dt*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.aspect=e.aspect,this}toJSON(){const e=super.toJSON();return e.focus=this.focus,e.aspect=this.aspect,e}}class mn extends Zr{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(zs.DEFAULT_UP),this.updateMatrix(),this.target=new zs,this.distance=s,this.angle=i,this.penumbra=r,this.decay=n,this.map=null,this.shadow=new pn}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 fn extends rn{constructor(){super(new dn(90,1,.5,500)),this.isPointLightShadow=!0}}class gn extends Zr{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 fn}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 yn extends ln{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,a=i+t,o=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,a-=t*this.view.offsetY,o=a-t*this.view.height}this.projectionMatrix.makeOrthographic(r,n,a,o,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 bn extends rn{constructor(){super(new yn(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class _n extends Zr{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(zs.DEFAULT_UP),this.updateMatrix(),this.target=new zs,this.shadow=new bn}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 xn extends Zr{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type="AmbientLight"}}class vn extends Zr{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 Tn{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let e=0;e<9;e++)this.coefficients.push(new Wt)}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 Sn extends Zr{constructor(e=new Tn,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}}const wn=-90;class Mn extends zs{constructor(e,t,s){super(),this.type="CubeCamera",this.renderTarget=s,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new dn(wn,1,e,t);i.layers=this.layers,this.add(i);const r=new dn(wn,1,e,t);r.layers=this.layers,this.add(r);const n=new dn(wn,1,e,t);n.layers=this.layers,this.add(n);const a=new dn(wn,1,e,t);a.layers=this.layers,this.add(a);const o=new dn(wn,1,e,t);o.layers=this.layers,this.add(o);const l=new dn(wn,1,e,t);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[s,i,r,n,a,o]=t;for(const e of t)this.remove(e);if(e===pt)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),a.up.set(0,1,0),a.lookAt(0,0,1),o.up.set(0,1,0),o.lookAt(0,0,-1);else{if(e!==mt)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),a.up.set(0,-1,0),a.lookAt(0,0,1),o.up.set(0,-1,0),o.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,a,o,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;let f=!1;f=!0===e.isWebGLRenderer?e.state.buffers.depth.getReversed():e.reversedDepthBuffer,e.setRenderTarget(s,0,i),f&&!1===e.autoClear&&e.clearDepth(),e.render(t,r),e.setRenderTarget(s,1,i),f&&!1===e.autoClear&&e.clearDepth(),e.render(t,n),e.setRenderTarget(s,2,i),f&&!1===e.autoClear&&e.clearDepth(),e.render(t,a),e.setRenderTarget(s,3,i),f&&!1===e.autoClear&&e.clearDepth(),e.render(t,o),e.setRenderTarget(s,4,i),f&&!1===e.autoClear&&e.clearDepth(),e.render(t,l),s.texture.generateMipmaps=m,e.setRenderTarget(s,5,i),f&&!1===e.autoClear&&e.clearDepth(),e.render(t,h),e.setRenderTarget(u,c,d),e.xr.enabled=p,s.texture.needsPMREMUpdate=!0}}class En extends dn{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class An extends Ki{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 Nn{static{Nn.prototype.isMatrix2=!0}constructor(e,t,s,i){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 Cn(e,t,s,i){const r=function(e){switch(e){case W:case H:return{byteLength:1,components:1};case X:case q:case Z:return{byteLength:2,components:1};case J:case ee:return{byteLength:2,components:4};case K:case Y:case Q:return{byteLength:4,components:1};case se:case ie:return{byteLength:4,components:3}}throw new Error(`THREE.TextureUtils: Unknown texture type ${e}.`)}(i);switch(s){case re:return e*t;case he:case ue:return e*t/r.components*r.byteLength;case ce:case de:return e*t*2/r.components*r.byteLength;case ne:return e*t*3/r.components*r.byteLength;case ae:case me:return e*t*4/r.components*r.byteLength;case fe:case ge:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case ye:case be:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case xe:case Te:return Math.max(e,16)*Math.max(t,8)/4;case _e:case ve:return Math.max(e,8)*Math.max(t,8)/2;case Se:case we:case Ee:case Ae:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case Me:case Ne:case Ce:case Re:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case Pe:return Math.floor((e+4)/5)*Math.floor((t+3)/4)*16;case Be:return Math.floor((e+4)/5)*Math.floor((t+4)/5)*16;case Fe:return Math.floor((e+5)/6)*Math.floor((t+4)/5)*16;case Le:return Math.floor((e+5)/6)*Math.floor((t+5)/6)*16;case De:return Math.floor((e+7)/8)*Math.floor((t+4)/5)*16;case Oe:return Math.floor((e+7)/8)*Math.floor((t+5)/6)*16;case Ie:return Math.floor((e+7)/8)*Math.floor((t+7)/8)*16;case Ue:return Math.floor((e+9)/10)*Math.floor((t+4)/5)*16;case ke:return Math.floor((e+9)/10)*Math.floor((t+5)/6)*16;case ze:return Math.floor((e+9)/10)*Math.floor((t+7)/8)*16;case Ve:return Math.floor((e+9)/10)*Math.floor((t+9)/10)*16;case Ge:return Math.floor((e+11)/12)*Math.floor((t+9)/10)*16;case $e:return Math.floor((e+11)/12)*Math.floor((t+11)/12)*16;case je:case We:case He:return Math.ceil(e/4)*Math.ceil(t/4)*16;case qe:case Xe:return Math.ceil(e/4)*Math.ceil(t/4)*8;case Ye:case Ke: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:t}})),"undefined"!=typeof window&&(window.__THREE__?Et("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=t);const Rn=["alphaMap","alphaTest","anisotropy","anisotropyMap","anisotropyRotation","aoMap","aoMapIntensity","attenuationColor","attenuationDistance","bumpMap","bumpScale","clearcoat","clearcoatMap","clearcoatNormalMap","clearcoatNormalScale","clearcoatRoughness","color","dashOffset","dashSize","dispersion","displacementBias","displacementMap","displacementScale","emissive","emissiveIntensity","emissiveMap","envMap","envMapIntensity","envMapRotation","gapSize","gradientMap","ior","iridescence","iridescenceIOR","iridescenceMap","iridescenceThickness","iridescenceThicknessMap","lightMap","lightMapIntensity","linewidth","map","matcap","metalness","metalnessMap","normalMap","normalScale","opacity","reflectivity","retroreflectivity","rotation","roughness","roughnessMap","scale","sheen","sheenColor","sheenColorMap","sheenRoughness","sheenRoughnessMap","shininess","size","specular","specularColor","specularColorMap","specularIntensity","specularIntensityMap","specularMap","steps","thickness","transmission","transmissionMap","wireframe"],Pn=new WeakMap,Bn=new WeakMap,Fn=new WeakMap,Ln=new WeakMap;class Dn{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=!0===e.object.isSkinnedMesh,this.refreshUniforms=Rn,this.renderId=0}firstInitialization(e){return!1===this.renderObjects.has(e)&&(this.getRenderObjectData(e),!0)}hasDynamicInstancing(e){return!0===e.isInstancedMesh&&(e.instanceMatrix.usage===dt||null!==e.instanceColor&&e.instanceColor.usage===dt)}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,object:i}=e;t={geometryId:s.id,geometryVersion:this.getGeometryData(s)._version,materialVersion:this.getMaterialData(e.material)._version,worldMatrix:i.matrixWorld.clone()},i.center&&(t.center=i.center.clone()),i.morphTargetInfluences&&(t.morphTargetInfluences=i.morphTargetInfluences.slice()),!0===i.isInstancedMesh&&(t.instanceMatrixVersion=i.instanceMatrix.version,t.instanceColorVersion=null!==i.instanceColor?i.instanceColor.version:null,t.morphTextureVersion=null!==i.morphTexture?i.morphTexture.version:null),!0===i.isBatchedMesh&&(t.matricesTextureVersion=i._matricesTexture.version,t.colorsTextureVersion=null!==i._colorsTexture?i._colorsTexture.version:null,t.indirectTextureVersion=i._indirectTexture.version),null!==e.bundle&&(t.version=e.bundle.version);const{width:r,height:n}=e.context;t.bufferWidth=r,t.bufferHeight=n;const{environmentIntensity:a,environmentRotation:o}=e.scene;t.environmentIntensity=a,t.environmentRotation=o.clone(),t.lights=this.getLightsData(e.lightsNode.getBuiltinLights(),[]),this.renderObjects.set(e,t)}return t}getAttributesData(e){const t={};for(const s in e){const i=e[s];t[s]={id:i.isInterleavedBufferAttribute?i.data.uuid:i.id,version:i.isInterleavedBufferAttribute?i.data.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)}getGeometryData(e){let t=Fn.get(e);return void 0===t&&(t={_renderId:-1,_version:0,attributes:this.getAttributesData(e.attributes),indexId:e.index?e.index.id:null,indexVersion:e.index?e.index.version:null,drawRange:{start:e.drawRange.start,count:e.drawRange.count}},e.addEventListener("dispose",()=>{t._version++}),Fn.set(e,t)),t}getTextureData(e){let t=Ln.get(e);if(void 0===t){t={_version:0};const s=()=>{t._version++};null!==e.renderTarget?e.renderTarget.addEventListener("dispose",s):e.addEventListener("dispose",s),Ln.set(e,t)}return t}getMaterialData(e){let t=Bn.get(e);if(void 0===t){t={_renderId:-1,_version:0};for(const s of this.refreshUniforms){const i=e[s];void 0!==i&&(null===i?t[s]=null:"object"==typeof i&&void 0!==i.clone?!0===i.isTexture?t[s]={id:i.id,version:0,cacheVersion:this.getTextureData(i)._version}:t[s]=i.clone():t[s]=i)}Bn.set(e,t)}return t}equals(e,t,s){const{object:i,material:r,geometry:n}=e,a=this.getRenderObjectData(e);if(!0!==a.worldMatrix.equals(i.matrixWorld))return a.worldMatrix.copy(i.matrixWorld),!1;const o=this.getMaterialData(e.material);if(o._renderId!==s){o._renderId=s;let e=!1;for(const t in o){const s=o[t],i=r[t];if("_renderId"!==t&&"_version"!==t)if(null===s||null==i)s!==(void 0===i?null:i)&&(null==i?o[t]=null:!0===i.isTexture?o[t]={id:i.id,version:i.version,cacheVersion:this.getTextureData(i)._version}:"object"==typeof i&&void 0!==i.clone?o[t]=i.clone():o[t]=i,e=!0);else if(void 0!==s.equals)!1===s.equals(i)&&(s.copy(i),e=!0);else if(!0===i.isTexture){const t=this.getTextureData(i);s.id===i.id&&s.version===i.version&&s.cacheVersion===t._version||(s.id=i.id,s.version=i.version,s.cacheVersion=t._version,e=!0)}else s!==i&&(o[t]=i,e=!0)}!0===e&&o._version++}if(a.materialVersion!==o._version)return a.materialVersion=o._version,!1;const{width:l,height:h}=e.context;if(a.bufferWidth!==l||a.bufferHeight!==h)return a.bufferWidth=l,a.bufferHeight=h,!1;if(a.geometryId!==n.id)return a.geometryId=n.id,a.geometryVersion=this.getGeometryData(n)._version,!1;const u=this.getGeometryData(e.geometry);if(u._renderId!==s){u._renderId=s;let e=!1;const t=n.attributes,i=u.attributes;let r=0,a=0;for(const e in t)r++;for(const s in i){a++;const r=i[s],n=t[s];if(void 0===n){delete i[s],e=!0;continue}const o=n.isInterleavedBufferAttribute?n.data.uuid:n.id,l=n.isInterleavedBufferAttribute?n.data.version:n.version;r.id===o&&r.version===l||(r.id=o,r.version=l,e=!0)}a!==r&&(u.attributes=this.getAttributesData(t),e=!0);const o=n.index,l=o?o.id:null,h=o?o.version:null;u.indexId===l&&u.indexVersion===h||(u.indexId=l,u.indexVersion=h,e=!0),u.drawRange.start===n.drawRange.start&&u.drawRange.count===n.drawRange.count||(u.drawRange.start=n.drawRange.start,u.drawRange.count=n.drawRange.count,e=!0),!0===e&&u._version++}if(a.geometryVersion!==u._version)return a.geometryVersion=u._version,!1;if(a.morphTargetInfluences){let e=!1;for(let t=0;t<a.morphTargetInfluences.length;t++)a.morphTargetInfluences[t]!==i.morphTargetInfluences[t]&&(a.morphTargetInfluences[t]=i.morphTargetInfluences[t],e=!0);if(e)return!1}if(!0===i.isInstancedMesh){const e=null!==i.instanceColor?i.instanceColor.version:null,t=null!==i.morphTexture?i.morphTexture.version:null;if(a.instanceMatrixVersion!==i.instanceMatrix.version||a.instanceColorVersion!==e||a.morphTextureVersion!==t)return a.instanceMatrixVersion=i.instanceMatrix.version,a.instanceColorVersion=e,a.morphTextureVersion=t,!1}if(!0===i.isBatchedMesh){const e=null!==i._colorsTexture?i._colorsTexture.version:null;if(a.matricesTextureVersion!==i._matricesTexture.version||a.colorsTextureVersion!==e||a.indirectTextureVersion!==i._indirectTexture.version)return a.matricesTextureVersion=i._matricesTexture.version,a.colorsTextureVersion=e,a.indirectTextureVersion=i._indirectTexture.version,!1}if(a.lights)for(let e=0;e<t.length;e++){const s=a.lights[e],i=t[e];if(s.map!==i.map||s.cacheVersion!==i.cacheVersion||s.shadowMapWidth!==i.shadowMapWidth||s.shadowMapHeight!==i.shadowMapHeight)return s.map=i.map,s.cacheVersion=i.cacheVersion,s.shadowMapWidth=i.shadowMapWidth,s.shadowMapHeight=i.shadowMapHeight,!1}const c=e.scene;return null===c.environment||null!==r.envMap||a.environmentIntensity===c.environmentIntensity&&!1!==a.environmentRotation.equals(c.environmentRotation)?a.center&&!1===a.center.equals(i.center)?(a.center.copy(i.center),!1):(null!==e.bundle&&(a.version=e.bundle.version),!0):(a.environmentIntensity=c.environmentIntensity,a.environmentRotation.copy(c.environmentRotation),!1)}getLightsData(e,t){t.length=0;for(const s of e){let e=null;!0===s.isSpotLight&&null!==s.map&&(e={map:s.map.version,cacheVersion:this.getTextureData(s.map)._version}),!0===s.castShadow&&void 0!==s.shadow&&(null===e&&(e={}),e.shadowMapWidth=s.shadow.mapSize.width,e.shadowMapHeight=s.shadow.mapSize.height),null!==e&&t.push(e)}return t}getLights(e,t){let s=Pn.get(e);return void 0===s&&(s={renderId:-1,lightsData:[]},Pn.set(e,s)),s.renderId===t||(s.renderId=t,this.getLightsData(e.getBuiltinLights(),s.lightsData)),s.lightsData}needsRefresh(e,t){if(this.hasNode||this.hasAnimation||this.hasDynamicInstancing(e.object)||this.firstInitialization(e)||this.needsVelocity(t.renderer))return xt;const{renderId:s}=t;let i=bt;this.renderId!==s&&(this.renderId=s,i=_t);const r=!0===e.object.static,n=null!==e.bundle&&!0===e.bundle.static&&this.getRenderObjectData(e).version===e.bundle.version;if(r||n)return i;const a=this.getLights(e.lightsNode,s);return!1===this.equals(e,a,s)&&(i=xt),i}}const On=[/^StackTrace\.js$/,/^TSLCore\.js$/,/^.*Node\.js$/,/^three\.webgpu.*\.js$/];class In{constructor(e=null){this.isStackTrace=!0,this.stack=function(e){const t=/(?:at\s+(.+?)\s+\()?(?:(.+?)@)?([^@\s()]+):(\d+):(\d+)/;return e.split("\n").map(e=>{const s=e.match(t);if(!s)return null;const i=s[1]||s[2]||"",r=s[3].split("?")[0],n=parseInt(s[4],10),a=parseInt(s[5],10);return{fn:i,file:r.split("/").pop(),line:n,column:a}}).filter(e=>e&&!On.some(t=>t.test(e.file)))}(e||(new Error).stack)}getLocation(){if(0===this.stack.length)return"[Unknown location]";const e=this.stack[0],t=e.fn;return`${t?`"${t}()" at `:""}"${e.file}:${e.line}"`}getError(e){if(0===this.stack.length)return e;return`${e}\n${this.stack.map(e=>{const t=`${e.file}:${e.line}:${e.column}`;return e.fn?` at ${e.fn} (${t})`:` at ${t}`}).join("\n")}`}}function Un(e,t=0){let s=3735928559^t,i=1103547991^t;if(Array.isArray(e))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 kn=e=>Un(e),zn=e=>Un(e),Vn=(...e)=>Un(e),Gn=new Map([[1,"float"],[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),$n=new WeakMap;function jn(e){return Gn.get(e)}function Wn(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 Hn(e){if(!0===e.isDepthTexture)return"float";const t=e.format;let s,i;if(s=t===he||t===ue||t===oe||t===le||t===re?1:t===ce||t===de?2:t===ne||t===pe?3:4,i=e.type===K?"uint":e.type===Y?"int":"float",1===s)return i;let r=jn(s);return"float"!==i&&(r=i[0]+r),r}function qn(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 Xs(...t):"vec2"===s?new $t(...t):"vec3"===s?new Wt(...t):"vec4"===s?new us(...t):"mat2"===s?new Nn(...t):"mat3"===s?new Xt(...t):"mat4"===s?new ps(...t):"bool"===e?t[0]||!1:"float"===e||"int"===e||"uint"===e?t[0]||0:"string"===e?t[0]||"":"ArrayBuffer"===e?(i=t[0],Uint8Array.from(atob(i),e=>e.charCodeAt(0)).buffer):null;var i}function Xn(e){let t=$n.get(e);return void 0===t&&(t={},$n.set(e,t)),t}function Yn(e){return void 0!==e[0]&&null!==e[0]&&(e[0].isNode||Object.getPrototypeOf(e[0])!==Object.prototype)}const Kn="vertex",Qn="none",Zn="frame",Jn="render",ea="object",ta="readOnly",sa="writeOnly",ia="readWrite",ra=["setup","analyze","generate"],na=["fragment","vertex","compute"],aa=["x","y","z","w"],oa={analyze:"setup",generate:"analyze"};let la=0;class ha extends Pt{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=Qn,this.updateBeforeType=Qn,this.updateAfterType=Qn,this.version=0,this.name="",this.global=!1,this.parents=!1,this.isNode=!0,this._beforeNodes=null,this._cacheKey=null,this._uuid=null,this._cacheKeyVersion=0,this.id=la++,this.stackTrace=null,!0===ha.captureStackTrace&&(this.stackTrace=new In)}set needsUpdate(e){!0===e&&this.version++}get uuid(){return null===this._uuid&&(this._uuid=Gt.generateUUID()),this._uuid}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,Zn)}onRenderUpdate(e){return this.onUpdate(e,Jn)}onObjectUpdate(e){return this.onUpdate(e,ea)}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(kn(i.slice(0,-4)),r.getCacheKey(e,t));this._cacheKey=Vn(zn(s),this.customCacheKey()),this._cacheKeyVersion=this.version}return this._cacheKey}customCacheKey(){return this.id}getScope(){return this}getHash(){return String(this.id)}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,t=null){const s=e.getDataFromNode(this);let i;return null!==t?(s.typeFromOutput=s.typeFromOutput||{},i=s.typeFromOutput[t],void 0===i&&(i=this.generateNodeType(e,t),s.typeFromOutput[t]=i)):(i=s.type,void 0===i&&(i=this.generateNodeType(e),s.type=i)),i}generateNodeType(e,t=null){const s=e.getNodeProperties(this);return s.outputNode?s.outputNode.getNodeType(e,t):this.nodeType}getShared(e){const t=this.getHash(e),s=e.getNodeFromHash(t);let i=null;if(s&&s!==this)i=s;else if(e.context.overrideNodes){const t=e.context.overrideNodes.get(this);if(t){const s=e.getDataFromNode(this);!0!==s.isOverwritten?(s.isOverwritten=!0,i=t(e).overrideNode(this,null),s.sharedNode=i):i=s.sharedNode}}return i||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(){Et("Abstract function.")}updateAfter(){Et("Abstract function.")}update(){Et("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=oa[e.buildStage];if(r&&!0!==i.buildStages[r]){const t=e.getBuildStage();e.setBuildStage(r),this.build(e),e.setBuildStage(t)}e.addChain(this);let n=null;const a=e.getBuildStage();if("setup"===a){e.addNode(this),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)}e.addSequentialNode(this)}n=t.outputNode}else if("analyze"===a)this.analyze(e,t);else if("generate"===a){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):(Et("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&&(At(`TSL: Invalid generated code, expected a "${t}".`),n=e.generateConst(t))}return e.removeChain(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}}ha.captureStackTrace=!1;class ua extends ha{static get type(){return"ArrayElementNode"}constructor(e,t){super(),this.node=e,this.indexNode=t,this.isArrayElementNode=!0}generateNodeType(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 ca extends ha{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}generateNodeType(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 da extends ha{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),a=e.getPropertyName(n);return e.addLineFlowCode(`${a} = ${r}`,this),i.snippet=r,i.propertyName=a,e.format(i.propertyName,s,t)}}return super.build(e,t)}}class pa extends da{static get type(){return"JoinNode"}constructor(e=[],t=null){super(t),this.nodes=e}generateNodeType(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),a=[];let o=0;for(const t of r){if(o>=i){At(`TSL: Length of parameters exceeds maximum length of function '${s}()' type.`,this.stackTrace);break}let r,l=t.getNodeType(e),h=e.getTypeLength(l);o+h>i&&(At(`TSL: Length of '${s}()' data exceeds maximum length of output type.`,this.stackTrace),h=i-o,l=e.getTypeFromLength(h)),o+=h,r=t.build(e,l);if(e.getComponentType(l)!==n){const t=e.getTypeFromLength(h,n);r=e.format(r,l,t)}a.push(r)}const l=`${e.getType(s)}( ${a.join(", ")} )`;return e.format(l,s,t)}}const ma=aa.join("");class fa extends ha{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(aa.indexOf(t)+1,e);return e}getComponentType(e){return e.getComponentType(this.node.getNodeType(e))}generateNodeType(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 a=s.build(e,n);r=this.components.length===i&&this.components===ma.slice(0,this.components.length)?e.format(a,n,t):e.format(`${a}.${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 ga extends da{static get type(){return"SetNode"}constructor(e,t,s){super(),this.sourceNode=e,this.components=t,this.targetNode=s}generateNodeType(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)),a=e.getTypeFromLength(s.length,n),o=i.build(e,a),l=t.build(e,r),h=e.getTypeLength(r),u=[];for(let e=0;e<h;e++){const t=aa[e];t===s[0]?(u.push(o),e+=s.length-1):u.push(l+"."+t)}return`${e.getType(r)}( ${u.join(", ")} )`}}class ya extends da{static get type(){return"FlipNode"}constructor(e,t){super(),this.sourceNode=e,this.components=t}generateNodeType(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),a=e.getPropertyName(n);e.addLineFlowCode(a+" = "+r,this);const o=e.getTypeLength(i),l=[];let h=0;for(let e=0;e<o;e++){const s=aa[e];s===t[h]?(l.push("1.0 - "+a+"."+s),h++):l.push(a+"."+s)}return`${e.getType(i)}( ${l.join(", ")} )`}}class ba extends ha{static get type(){return"InputNode"}constructor(e,t=null){super(t),this.isInputNode=!0,this.value=e,this.precision=null}generateNodeType(){return null===this.nodeType?Wn(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=Wn(this.value),e.nodeType=this.nodeType,"ArrayBuffer"===e.valueType&&(e.value=function(e){let t="";const s=new Uint8Array(e);for(let e=0;e<s.length;e++)t+=String.fromCharCode(s[e]);return btoa(t)}(e.value)),e.precision=this.precision}deserialize(e){super.deserialize(e),this.nodeType=e.nodeType,this.value=Array.isArray(e.value)?qn(e.valueType,...e.value):e.value,this.precision=e.precision||null,this.value&&this.value.fromArray&&(this.value=this.value.fromArray(e.value))}generate(){Et("Abstract function.")}}const _a=/float|u?int/;class xa extends ba{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 _a.test(s)&&_a.test(t)?e.generateConst(t,this.value):e.format(this.generateConst(e),s,t)}}class va extends ha{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)}generateNodeType(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)){Et(`TSL: Member "${this.property}" does not exist in struct.`,this.stackTrace);const t=this.getNodeType(e);return e.generateConst(t)}return this.structNode.build(e)+"."+this.property}}let Ta=null;const Sa=new Map;function wa(e,t){if(Sa.has(e))Et(`TSL: Redefinition of method chaining '${e}'.`);else{if("function"!=typeof t)throw new Error(`THREE.TSL: Node element ${e} is not a function`);Sa.set(e,t),"assign"!==e&&(ha.prototype[e]=function(...e){return this.isStackNode?this.addToStack(t(...e)):t(this,...e)},ha.prototype[e+"Assign"]=function(...e){return this.isStackNode?this.assign(e[0],t(...e)):this.assign(t(this,...e))})}}const Ma=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("");ha.prototype.assign=function(...e){if(!0!==this.isStackNode)return null!==Ta?Ta.assign(this,...e):At("TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().",new In),this;{const t=Sa.get("assign");return this.addToStack(t(...e))}},ha.prototype.toVarIntent=function(){return this},ha.prototype.get=function(e){return new va(this,e)};const Ea={};function Aa(e,t,s){Ea[e]=Ea[t]=Ea[s]={get(){this._cache=this._cache||{};let t=this._cache[e];return void 0===t&&(t=new fa(this,e),this._cache[e]=t),t},set(t){this[e].assign(Qa(t))}};const i=e.toUpperCase(),r=t.toUpperCase(),n=s.toUpperCase();ha.prototype["set"+i]=ha.prototype["set"+r]=ha.prototype["set"+n]=function(t){const s=Ma(e);return new ga(this,s,Qa(t))},ha.prototype["flip"+i]=ha.prototype["flip"+r]=ha.prototype["flip"+n]=function(){const t=Ma(e);return new ya(this,t)}}const Na=["x","y","z","w"],Ca=["r","g","b","a"],Ra=["s","t","p","q"];for(let e=0;e<4;e++){let t=Na[e],s=Ca[e],i=Ra[e];Aa(t,s,i);for(let r=0;r<4;r++){t=Na[e]+Na[r],s=Ca[e]+Ca[r],i=Ra[e]+Ra[r],Aa(t,s,i);for(let n=0;n<4;n++){t=Na[e]+Na[r]+Na[n],s=Ca[e]+Ca[r]+Ca[n],i=Ra[e]+Ra[r]+Ra[n],Aa(t,s,i);for(let a=0;a<4;a++)t=Na[e]+Na[r]+Na[n]+Na[a],s=Ca[e]+Ca[r]+Ca[n]+Ca[a],i=Ra[e]+Ra[r]+Ra[n]+Ra[a],Aa(t,s,i)}}}for(let e=0;e<32;e++)Ea[e]={get(){this._cache=this._cache||{};let t=this._cache[e];return void 0===t&&(t=new ua(this,new xa(e,"uint")),this._cache[e]=t),t},set(t){this[e].assign(Qa(t))}};Object.defineProperties(ha.prototype,Ea);const Pa=function(e,t=null){for(const s in e)e[s]=Qa(e[s],t);return e},Ba=function(e,t=null){const s=e.length;for(let i=0;i<s;i++)e[i]=Qa(e[i],t);return e},Fa=function(e,t=null,s=null,i=null){function r(e){return null!==i?(e=Qa(Object.assign(e,i)),!0===i.intent&&(e=e.toVarIntent())):e=Qa(e),e}let n,a,o,l=t;function h(t){let s;return s=l?/[a-z]/i.test(l)?l+"()":l:e.type,void 0!==a&&t.length<a?(At(`TSL: "${s}" parameter length is less than minimum required.`,new In),t.concat(new Array(a-t.length).fill(0))):void 0!==o&&t.length>o?(At(`TSL: "${s}" parameter length exceeds limit.`,new In),t.slice(0,o)):t}return null===t?n=(...t)=>r(new e(...eo(h(t)))):null!==s?(s=Qa(s),n=(...i)=>r(new e(t,...eo(h(i)),s))):n=(...s)=>r(new e(t,...eo(h(s)))),n.setParameterLength=(...e)=>(1===e.length?a=o=e[0]:2===e.length&&([a,o]=e),n),n.setName=e=>(l=e,n),n},La=function(e,...t){return new e(...eo(t))};class Da extends ha{constructor(e,t){super(),this.shaderNode=e,this.rawInputs=t,this.isShaderCallNodeInternal=!0}generateNodeType(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 a=e.subBuildFn,o=e.fnCall;e.subBuildFn=r,e.fnCall=this;let l=null;if(t.layout){if(s){const i=t.layout.inputs;if(Yn(s)){const t=s;for(let s=0;s<i.length;s++){const i=t[s];i&&i.isNode&&i.build(e)}}else{const t=s[0];for(const s of i){const i=t[s.name];i&&i.isNode&&i.build(e)}}}const i=e.buildFunctionNode(t);e.addInclude(i);const r=s?function(e){let t;Ja(e),t=Yn(e)?[...e]:e[0];return t}(s):null;l=i.call(r)}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 Ja(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 Qa(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 ha&&(n=void 0===e[i]?e[t++]:Reflect.get(e,i,r));else n=Reflect.get(s,i,r);n=Qa(n)}return n}})}(s):null,n=Array.isArray(s)?s.length>0:null!==s,a=t.jsFunc,o=n||a.length>1?a(r,i):a(i);l=Qa(o)}return e.subBuildFn=a,e.fnCall=o,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),a=this.getOutputNode(e),o=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?a.build(e,t):"generate"===i&&(s=a.build(e,t)||"");return e.fnCall=o,s}}class Oa extends ha{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 Da(this,e)}setup(){return this.call()}}const Ia=[!1,!0],Ua=[0,1,2,3],ka=[-1,-2],za=[.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],Va=new Map;for(const e of Ia)Va.set(e,new xa(e));const Ga=new Map;for(const e of Ua)Ga.set(e,new xa(e,"uint"));const $a=new Map([...Ga].map(e=>new xa(e.value,"int")));for(const e of ka)$a.set(e,new xa(e,"int"));const ja=new Map([...$a].map(e=>new xa(e.value)));for(const e of za)ja.set(e,new xa(e));for(const e of za)ja.set(-e,new xa(-e));const Wa={bool:Va,uint:Ga,ints:$a,float:ja},Ha=new Map([...Va,...ja]),qa=(e,t)=>Ha.has(e)?Ha.get(e):!0===e.isNode?e:new xa(e,t),Xa=function(e,t=null){return(...s)=>{for(const t of s)if(void 0===t)return At(`TSL: Invalid parameter for the type "${e}".`,new In),new xa(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=[qn(e,...s)]),1===s.length&&null!==t&&t.has(s[0]))return Za(t.get(s[0]));if(1===s.length){const t=qa(s[0],e);return t.nodeType===e?Za(t):Za(new ca(t,e))}const i=s.map(e=>qa(e));return Za(new pa(i,e))}};function Ya(e){return e&&e.isNode&&e.traverse(t=>{t.isConstNode&&(e=t.value)}),Boolean(e)}function Ka(e,t){return new Oa(e,t)}const Qa=(e,t=null)=>function(e,t=null){const s=Wn(e);return"node"===s?e:null===t&&("float"===s||"boolean"===s)||s&&"shader"!==s&&"string"!==s?Qa(qa(e,t)):"shader"===s?e.isFn?e:ao(e):e}(e,t),Za=(e,t=null)=>Qa(e,t).toVarIntent(),Ja=(e,t=null)=>new Pa(e,t),eo=(e,t=null)=>new Ba(e,t),to=(e,t=null,s=null,i=null)=>new Fa(e,t,s,i),so=(e,...t)=>new La(e,...t),io=(e,t=null,s=null,i={})=>new Fa(e,t,s,{...i,intent:!0});let ro=0;class no extends ha{constructor(e,t=null){super();let s=null;null!==t&&("object"==typeof t?s=t.return:("string"==typeof t?s=t:At("TSL: Invalid layout type.",new In),t=null)),this.shaderNode=new Ka(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"+ro++,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}generateNodeType(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 At('TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".',this.stackTrace),e.generateConst(t)}}function ao(e,t=null){const s=new no(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 oo=e=>{Ta=e},lo=()=>Ta,ho=(...e)=>Ta.If(...e);wa("toStack",function(e){return Ta&&Ta.addToStack(e),e});const uo=new Xa("color"),co=new Xa("float",Wa.float),po=new Xa("int",Wa.ints),mo=new Xa("uint",Wa.uint),fo=new Xa("bool",Wa.bool),go=new Xa("vec2"),yo=new Xa("ivec2"),bo=new Xa("uvec2"),_o=new Xa("bvec2"),xo=new Xa("vec3"),vo=new Xa("ivec3"),To=new Xa("uvec3"),So=new Xa("bvec3"),wo=new Xa("vec4"),Mo=new Xa("ivec4"),Eo=new Xa("uvec4"),Ao=new Xa("bvec4"),No=new Xa("mat2"),Co=new Xa("mat3"),Ro=new Xa("mat4");wa("toColor",uo),wa("toFloat",co),wa("toInt",po),wa("toUint",mo),wa("toBool",fo),wa("toVec2",go),wa("toIVec2",yo),wa("toUVec2",bo),wa("toBVec2",_o),wa("toVec3",xo),wa("toIVec3",vo),wa("toUVec3",To),wa("toBVec3",So),wa("toVec4",wo),wa("toIVec4",Mo),wa("toUVec4",Eo),wa("toBVec4",Ao),wa("toMat2",No),wa("toMat3",Co),wa("toMat4",Ro);wa("element",to(ua).setParameterLength(2)),wa("convert",(e,t)=>new ca(Qa(e),t));class Po extends ha{static get type(){return"PropertyNode"}constructor(e,t=null,s=!1,i=null){super(e),this.name=t,this.varying=s,this.placeholderNode=Qa(i),this.isPropertyNode=!0,this.global=!0}getNodeType(e){const t=super.getNodeType(e);return"output"===t?e.getOutputType():t}customCacheKey(){return kn(this.type+":"+(this.name||"")+":"+(this.varying?"1":"0"))}getHash(e){return this.name||super.getHash(e)}generate(e){let t;if(!0===this.varying)t=e.getVaryingFromNode(this,this.name),t.needsInterpolation=!0;else if(t=e.getVarFromNode(this,this.name),null!==this.placeholderNode&&!1===e.hasWriteUsage(this)){const s=this.placeholderNode.build(e,this.getNodeType(e));e.addLineFlowCode(`${e.getPropertyName(t)} = ${s}`,this)}return e.getPropertyName(t)}}const Bo=(e,t,s=null)=>new Po(e,t,!1,s),Fo=(e,t,s=null)=>new Po(e,t,!0,s),Lo=so(Po,"vec4","DiffuseColor"),Do=so(Po,"vec3","DiffuseContribution"),Oo=so(Po,"vec3","EmissiveColor"),Io=so(Po,"float","Roughness"),Uo=so(Po,"float","Metalness"),ko=so(Po,"float","Clearcoat"),zo=so(Po,"float","ClearcoatRoughness"),Vo=so(Po,"vec3","Sheen"),Go=so(Po,"float","SheenRoughness"),$o=so(Po,"float","Iridescence"),jo=so(Po,"float","IridescenceIOR"),Wo=so(Po,"float","IridescenceThickness"),Ho=so(Po,"float","AlphaT"),qo=so(Po,"float","Anisotropy"),Xo=so(Po,"vec3","AnisotropyT"),Yo=so(Po,"vec3","AnisotropyB"),Ko=so(Po,"color","SpecularColor"),Qo=so(Po,"color","SpecularColorBlended"),Zo=so(Po,"float","SpecularF90"),Jo=so(Po,"float","Shininess"),el=so(Po,"output","Output"),tl=so(Po,"float","dashSize"),sl=so(Po,"float","gapSize"),il=so(Po,"float","IOR"),rl=so(Po,"float","Transmission"),nl=so(Po,"float","Thickness"),al=so(Po,"float","AttenuationDistance"),ol=so(Po,"color","AttenuationColor"),ll=so(Po,"float","Dispersion"),hl=so(Po,"float","Retroreflectivity"),ul=so(Po,"float","AmbientOcclusion",!1,1);class cl extends ha{static get type(){return"UniformGroupNode"}constructor(e,t=!1,s=1,i=null){super("string"),this.name=e,this.shared=t,this.order=s,this.updateType=i,this.isUniformGroup=!0}update(){this.needsUpdate=!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 dl=(e,t=1,s=null)=>new cl(e,!1,t,s),pl=(e,t=0,s=null)=>new cl(e,!0,t,s),ml=pl("render",0,Jn),fl=dl("object",1,ea);class gl extends ba{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=fl}setName(e){return this.name=e,this}label(e){return Et('TSL: "label()" has been deprecated. Use "setName()" instead.',new In),this.setName(e)}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}getSharedNode(e){const t=this.getUniformHash(e);let s=e.getNodeFromHash(t);return void 0===s&&(e.setHashNode(this,t),s=this),s}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.getSharedNode(e),r=i.getInputType(e),n=e.getUniformFromNode(i,r,e.shaderStage,this.name||e.context.nodeName),a=e.getPropertyName(n);void 0!==e.context.nodeName&&delete e.context.nodeName;let o=a;if("bool"===s){const t=e.getDataFromNode(this);let i=t.propertyName;if(void 0===i){const n=e.getVarFromNode(this,null,"bool");i=e.getPropertyName(n),t.propertyName=i,o=e.format(a,r,s),e.addLineFlowCode(`${i} = ${o}`,this)}o=i}return e.format(o,s,t)}}const yl=(e,t)=>{const s=(e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null)(t||e);if(s===e&&(e=qn(s)),e&&!0===e.isNode){let t=e.value;e.traverse(e=>{!0===e.isConstNode&&(t=e.value)}),e=t}return new gl(e,s)};class bl extends da{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}generateNodeType(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 _l=(...e)=>{let t;if(1===e.length){const s=e[0].map(e=>Qa(e));t=new bl(null,s.length,s)}else{const s=e[0],i=e[1];t=new bl(s,i)}return t};wa("toArray",(e,t)=>_l(Array(t).fill(e)));class xl extends da{static get type(){return"AssignNode"}constructor(e,t){super(),this.targetNode=e,this.sourceNode=t,this.isAssignNode=!0}hasDependencies(){return!1}generateNodeType(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 aa.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),a=s.getNodeType(e),o=i.build(e,a),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,a),r=e.getPropertyName(i);e.addLineFlowCode(`${r} = ${o}`,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} = ${o}`,"void"!==t&&"void"!==l||(e.addLineFlowCode(u,this),"void"!==t&&(u=n));return h.initialized=!0,e.format(u,a,t)}}wa("assign",to(xl).setParameterLength(2));class vl extends da{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}generateNodeType(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)At("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(At("TSL: The number of provided parameters is less than the expected number of inputs in 'Fn()'.");r.length<i.length;)r.push(co(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)):(At(`TSL: Input '${e.name}' not found in 'Fn()'.`),t.push(n(co(0),e)))}return`${s.build(e,"property")}( ${t.join(", ")} )`}}wa("call",(e,...t)=>(t=t.length>1||t[0]&&!0===t[0].isNode?eo(t):Ja(t[0]),new vl(Qa(e),t)));const Tl={"==":"equal","!=":"notEqual","<":"lessThan",">":"greaterThan","<=":"lessThanEqual",">=":"greaterThanEqual","%":"mod"};class Sl extends da{static get type(){return"OperatorNode"}constructor(e,t,s,...i){if(super(),i.length>0){let r=new Sl(e,t,s);for(let t=0;t<i.length-1;t++)r=new Sl(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(Tl[this.op],t)}generateNodeType(e,t=null){const s=this.op,i=this.aNode,r=this.bNode,n=i.getNodeType(e),a=r?r.getNodeType(e):null;if("void"===n||"void"===a)return t||"void";if("%"===s)return n;if("~"===s||"&"===s||"|"===s||"^"===s||">>"===s||"<<"===s)return e.getIntegerType(n);if("&&"===s||"||"===s||"^^"===s)return"bool";if("!"===s){const t=e.getTypeLength(n);return t>1?`bvec${t}`:"bool"}if("=="===s||"!="===s||"<"===s||">"===s||"<="===s||">="===s){const t=Math.max(e.getTypeLength(n),e.getTypeLength(a));return t>1?`bvec${t}`:"bool"}if(e.isMatrix(n)){if("float"===a)return n;if(e.isVector(a))return e.getVectorFromMatrix(n);if(e.isMatrix(a))return n}else if(e.isMatrix(a)){if("float"===n)return a;if(e.isVector(n))return e.getVectorFromMatrix(a)}return e.getTypeLength(a)>e.getTypeLength(n)?a:n}generate(e,t){const s=this.op,{aNode:i,bNode:r}=this,n=this.getNodeType(e,t);let a=null,o=null;"void"!==n?(a=i.getNodeType(e),o=r?r.getNodeType(e):null,"<"===s||">"===s||"<="===s||">="===s||"=="===s||"!="===s?e.isVector(a)?o=a:e.isVector(o)?a=o:a!==o&&(a=o="float"):">>"===s||"<<"===s?(a=n,o=e.changeComponentType(o,"uint")):"%"===s?(a=n,o=e.isInteger(a)&&e.isInteger(o)?o:a):e.isMatrix(a)?"float"===o?o="float":e.isVector(o)?o=e.getVectorFromMatrix(a):e.isMatrix(o)||(a=o=n):a=e.isMatrix(o)?"float"===a?"float":e.isVector(a)?e.getVectorFromMatrix(o):o=n:o=n):a=o=n;const l=i.build(e,a),h=r?r.build(e,o):null,u=e.getFunctionOperator(s);if("void"!==t){const i=e.renderer.coordinateSystem===pt;if("=="===s||"!="===s||"<"===s||">"===s||"<="===s||">="===s)return i&&e.isVector(a)?e.format(`${this.getOperatorMethod(e,t)}( ${l}, ${h} )`,n,t):e.format(`( ${l} ${s} ${h} )`,n,t);if("%"===s)return e.isInteger(o)?e.format(`( ${l} % ${h} )`,n,t):e.format(`${this.getOperatorMethod(e,n)}( ${l}, ${h} )`,n,t);if("!"===s)return i&&e.isVector(a)?e.format(`not( ${l} )`,t):e.format(`( ${s} ${l} )`,a,t);if("~"===s)return e.format(`( ${s} ${l} )`,a,t);if(u)return e.format(`${u}( ${l}, ${h} )`,n,t);if(e.isMatrix(a)&&"float"===o)return e.format(`( ${h} ${s} ${l} )`,n,t);if("float"===a&&e.isMatrix(o))return e.format(`${l} ${s} ${h}`,n,t);{let r=`( ${l} ${s} ${h} )`;return!i&&"bool"===n&&e.isVector(a)&&e.isVector(o)&&(r=`all${r}`),e.format(r,n,t)}}if("void"!==a)return u?e.format(`${u}( ${l}, ${h} )`,n,t):e.isMatrix(a)&&"float"===o?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 wl=io(Sl,"+").setParameterLength(2,1/0).setName("add"),Ml=io(Sl,"-").setParameterLength(2,1/0).setName("sub"),El=io(Sl,"*").setParameterLength(2,1/0).setName("mul"),Al=io(Sl,"/").setParameterLength(2,1/0).setName("div"),Nl=io(Sl,"%").setParameterLength(2).setName("mod"),Cl=io(Sl,"==").setParameterLength(2).setName("equal"),Rl=io(Sl,"!=").setParameterLength(2).setName("notEqual"),Pl=io(Sl,"<").setParameterLength(2).setName("lessThan"),Bl=io(Sl,">").setParameterLength(2).setName("greaterThan"),Fl=io(Sl,"<=").setParameterLength(2).setName("lessThanEqual"),Ll=io(Sl,">=").setParameterLength(2).setName("greaterThanEqual"),Dl=io(Sl,"&&").setParameterLength(2,1/0).setName("and"),Ol=io(Sl,"||").setParameterLength(2,1/0).setName("or"),Il=io(Sl,"!").setParameterLength(1).setName("not"),Ul=io(Sl,"^^").setParameterLength(2).setName("xor"),kl=io(Sl,"&").setParameterLength(2).setName("bitAnd"),zl=io(Sl,"~").setParameterLength(1).setName("bitNot"),Vl=io(Sl,"|").setParameterLength(2).setName("bitOr"),Gl=io(Sl,"^").setParameterLength(2).setName("bitXor"),$l=io(Sl,"<<").setParameterLength(2).setName("shiftLeft"),jl=io(Sl,">>").setParameterLength(2).setName("shiftRight"),Wl=ao(([e])=>(e.addAssign(1),e)),Hl=ao(([e])=>(e.subAssign(1),e)),ql=ao(([e])=>{const t=po(e).toConst();return e.addAssign(1),t}),Xl=ao(([e])=>{const t=po(e).toConst();return e.subAssign(1),t});wa("add",wl),wa("sub",Ml),wa("mul",El),wa("div",Al),wa("mod",Nl),wa("equal",Cl),wa("notEqual",Rl),wa("lessThan",Pl),wa("greaterThan",Bl),wa("lessThanEqual",Fl),wa("greaterThanEqual",Ll),wa("and",Dl),wa("or",Ol),wa("not",Il),wa("xor",Ul),wa("bitAnd",kl),wa("bitNot",zl),wa("bitOr",Vl),wa("bitXor",Gl),wa("shiftLeft",$l),wa("shiftRight",jl),wa("incrementBefore",Wl),wa("decrementBefore",Hl),wa("increment",ql),wa("decrement",Xl);class Yl extends da{static get type(){return"MathNode"}constructor(e,t,s=null,i=null){if(super(),(e===Yl.MAX||e===Yl.MIN)&&arguments.length>3){let r=new Yl(e,t,s);for(let t=3;t<arguments.length-1;t++)r=new Yl(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),a=e.isMatrix(i)?0:e.getTypeLength(i);return r>n&&r>a?t:n>a?s:a>r?i:t}generateNodeType(e){const t=this.method;return t===Yl.LENGTH||t===Yl.DISTANCE||t===Yl.DOT||t===Yl.DETERMINANT?"float":t===Yl.CROSS?"vec3":t===Yl.ALL||t===Yl.ANY?"bool":t===Yl.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===Yl.ONE_MINUS)r=Ml(1,t);else if(i===Yl.RECIPROCAL)r=Al(1,t);else if(i===Yl.DIFFERENCE)r=wh(Ml(t,s));else if(i===Yl.TRANSFORM_DIRECTION){let i,n;e.isMatrix(t.getNodeType(e))?(i=t,n=s):(i=s,n=t),r=uh(El(i,wo(xo(n),0)).xyz)}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,a=this.bNode,o=this.cNode,l=e.renderer.coordinateSystem;if(s===Yl.NEGATE)return e.format("( - "+n.build(e,r)+" )",i,t);{const h=[];return s===Yl.CROSS?h.push(n.build(e,i),a.build(e,i)):l===pt&&s===Yl.STEP?h.push(n.build(e,1===e.getTypeLength(n.getNodeType(e))?"float":r),a.build(e,r)):l!==pt||s!==Yl.MIN&&s!==Yl.MAX?s===Yl.REFRACT?h.push(n.build(e,r),a.build(e,r),o.build(e,"float")):s===Yl.MIX?h.push(n.build(e,r),a.build(e,r),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":r)):(l===mt&&s===Yl.ATAN&&null!==a&&(s="atan2"),"fragment"===e.shaderStage||s!==Yl.DFDX&&s!==Yl.DFDY||(At(`TSL: '${s}' is not supported in the ${e.shaderStage} stage.`,this.stackTrace),s="/*"+s+"*/"),h.push(n.build(e,r)),null!==a&&h.push(a.build(e,r)),null!==o&&h.push(o.build(e,r))):h.push(n.build(e,r),a.build(e,1===e.getTypeLength(a.getNodeType(e))?e.getComponentType(r):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}}Yl.ALL="all",Yl.ANY="any",Yl.RADIANS="radians",Yl.DEGREES="degrees",Yl.EXP="exp",Yl.EXP2="exp2",Yl.LOG="log",Yl.LOG2="log2",Yl.SQRT="sqrt",Yl.INVERSE_SQRT="inversesqrt",Yl.FLOOR="floor",Yl.CEIL="ceil",Yl.NORMALIZE="normalize",Yl.FRACT="fract",Yl.SIN="sin",Yl.SINH="sinh",Yl.COS="cos",Yl.COSH="cosh",Yl.TAN="tan",Yl.TANH="tanh",Yl.ASIN="asin",Yl.ASINH="asinh",Yl.ACOS="acos",Yl.ACOSH="acosh",Yl.ATAN="atan",Yl.ATANH="atanh",Yl.ABS="abs",Yl.SIGN="sign",Yl.LENGTH="length",Yl.NEGATE="negate",Yl.ONE_MINUS="oneMinus",Yl.DFDX="dFdx",Yl.DFDY="dFdy",Yl.ROUND="round",Yl.RECIPROCAL="reciprocal",Yl.TRUNC="trunc",Yl.FWIDTH="fwidth",Yl.TRANSPOSE="transpose",Yl.DETERMINANT="determinant",Yl.INVERSE="inverse",Yl.EQUALS="equals",Yl.MIN="min",Yl.MAX="max",Yl.STEP="step",Yl.REFLECT="reflect",Yl.DISTANCE="distance",Yl.DIFFERENCE="difference",Yl.DOT="dot",Yl.CROSS="cross",Yl.POW="pow",Yl.TRANSFORM_DIRECTION="transformDirection",Yl.MIX="mix",Yl.CLAMP="clamp",Yl.REFRACT="refract",Yl.SMOOTHSTEP="smoothstep",Yl.FACEFORWARD="faceforward";const Kl=co(1e-6),Ql=co(Math.PI),Zl=io(Yl,Yl.ALL).setParameterLength(1),Jl=io(Yl,Yl.ANY).setParameterLength(1),eh=io(Yl,Yl.RADIANS).setParameterLength(1),th=io(Yl,Yl.DEGREES).setParameterLength(1),sh=io(Yl,Yl.EXP).setParameterLength(1),ih=io(Yl,Yl.EXP2).setParameterLength(1),rh=io(Yl,Yl.LOG).setParameterLength(1),nh=io(Yl,Yl.LOG2).setParameterLength(1),ah=io(Yl,Yl.SQRT).setParameterLength(1),oh=io(Yl,Yl.INVERSE_SQRT).setParameterLength(1),lh=io(Yl,Yl.FLOOR).setParameterLength(1),hh=io(Yl,Yl.CEIL).setParameterLength(1),uh=io(Yl,Yl.NORMALIZE).setParameterLength(1),ch=io(Yl,Yl.FRACT).setParameterLength(1),dh=io(Yl,Yl.SIN).setParameterLength(1),ph=io(Yl,Yl.SINH).setParameterLength(1),mh=io(Yl,Yl.COS).setParameterLength(1),fh=io(Yl,Yl.COSH).setParameterLength(1),gh=io(Yl,Yl.TAN).setParameterLength(1),yh=io(Yl,Yl.TANH).setParameterLength(1),bh=io(Yl,Yl.ASIN).setParameterLength(1),_h=io(Yl,Yl.ASINH).setParameterLength(1),xh=io(Yl,Yl.ACOS).setParameterLength(1),vh=io(Yl,Yl.ACOSH).setParameterLength(1),Th=io(Yl,Yl.ATAN).setParameterLength(1,2),Sh=io(Yl,Yl.ATANH).setParameterLength(1),wh=io(Yl,Yl.ABS).setParameterLength(1),Mh=io(Yl,Yl.SIGN).setParameterLength(1),Eh=io(Yl,Yl.LENGTH).setParameterLength(1),Ah=io(Yl,Yl.NEGATE).setParameterLength(1),Nh=io(Yl,Yl.ONE_MINUS).setParameterLength(1),Ch=io(Yl,Yl.DFDX).setParameterLength(1),Rh=io(Yl,Yl.DFDY).setParameterLength(1),Ph=io(Yl,Yl.ROUND).setParameterLength(1),Bh=io(Yl,Yl.RECIPROCAL).setParameterLength(1),Fh=io(Yl,Yl.TRUNC).setParameterLength(1),Lh=io(Yl,Yl.FWIDTH).setParameterLength(1),Dh=io(Yl,Yl.TRANSPOSE).setParameterLength(1),Oh=io(Yl,Yl.DETERMINANT).setParameterLength(1),Ih=io(Yl,Yl.INVERSE).setParameterLength(1),Uh=io(Yl,Yl.MIN).setParameterLength(2,1/0),kh=io(Yl,Yl.MAX).setParameterLength(2,1/0),zh=io(Yl,Yl.STEP).setParameterLength(2),Vh=io(Yl,Yl.REFLECT).setParameterLength(2),Gh=io(Yl,Yl.DISTANCE).setParameterLength(2),$h=io(Yl,Yl.DIFFERENCE).setParameterLength(2),jh=io(Yl,Yl.DOT).setParameterLength(2),Wh=io(Yl,Yl.CROSS).setParameterLength(2),Hh=io(Yl,Yl.POW).setParameterLength(2),qh=e=>El(e,e),Xh=e=>El(e,e,e,e),Yh=io(Yl,Yl.TRANSFORM_DIRECTION).setParameterLength(2),Kh=io(Yl,Yl.MIX).setParameterLength(3),Qh=(e,t=0,s=1)=>new Yl(Yl.CLAMP,Qa(e),Qa(t),Qa(s)),Zh=e=>Qh(e),Jh=io(Yl,Yl.REFRACT).setParameterLength(3),eu=io(Yl,Yl.SMOOTHSTEP).setParameterLength(3),tu=io(Yl,Yl.FACEFORWARD).setParameterLength(3),su=ao(([e])=>{const t=jh(e.xy,go(12.9898,78.233)),s=Nl(t,Ql);return ch(dh(s).mul(43758.5453))});wa("all",Zl),wa("any",Jl),wa("radians",eh),wa("degrees",th),wa("exp",sh),wa("exp2",ih),wa("log",rh),wa("log2",nh),wa("sqrt",ah),wa("inverseSqrt",oh),wa("floor",lh),wa("ceil",hh),wa("normalize",uh),wa("fract",ch),wa("sin",dh),wa("sinh",ph),wa("cos",mh),wa("cosh",fh),wa("tan",gh),wa("tanh",yh),wa("asin",bh),wa("asinh",_h),wa("acos",xh),wa("acosh",vh),wa("atan",Th),wa("atanh",Sh),wa("abs",wh),wa("sign",Mh),wa("length",Eh),wa("lengthSq",e=>jh(e,e)),wa("negate",Ah),wa("oneMinus",Nh),wa("dFdx",Ch),wa("dFdy",Rh),wa("round",Ph),wa("reciprocal",Bh),wa("trunc",Fh),wa("fwidth",Lh),wa("min",Uh),wa("max",kh),wa("step",(e,t)=>zh(t,e)),wa("reflect",Vh),wa("distance",Gh),wa("dot",jh),wa("cross",Wh),wa("pow",Hh),wa("pow2",qh),wa("pow3",e=>El(e,e,e)),wa("pow4",Xh),wa("transformDirection",Yh),wa("transformNormalByViewMatrix",(e,t)=>uh(El(t,wo(xo(e),0)).xyz)),wa("transformNormalByInverseViewMatrix",(e,t)=>uh(wo(xo(e),0).mul(t).xyz)),wa("mix",(e,t,s)=>Kh(t,s,e)),wa("clamp",Qh),wa("refract",Jh),wa("smoothstep",(e,t,s)=>eu(t,s,e)),wa("faceForward",tu),wa("difference",$h),wa("saturate",Zh),wa("cbrt",e=>El(Mh(e),Hh(wh(e),1/3))),wa("transpose",Dh),wa("determinant",Oh),wa("inverse",Ih),wa("rand",su);class iu extends ha{static get type(){return"ConditionalNode"}constructor(e,t,s=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=s}generateNodeType(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,a=e.getNodeProperties(this);a.condNode=t,a.ifNode=n?s:s.context({nodeBlock:s}),a.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:a}=e.getNodeProperties(this),o=e.currentFunctionNode,l="void"!==t,h=l?Bo(s).build(e):"";i.nodeProperty=h;const u=r.build(e,"bool");if(e.context.uniformFlow&&null!==a){const i=n.build(e,s),r=a.build(e,s),o=e.getTernary(u,i,r);return e.format(o,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===o&&(Et("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.",this.stackTrace),c="// "+c))),e.removeFlowTab().addFlowCode(e.tab+"\t"+c+"\n\n"+e.tab+"}"),null!==a){e.addFlowCode(" else {\n\n").addFlowTab();let t=a.build(e,s);t&&(l?t=h+" = "+t+";":(t="return "+t+";",null===o&&(Et("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.",this.stackTrace),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 ru=to(iu).setParameterLength(2,3);wa("select",ru);class nu extends ha{static get type(){return"ContextNode"}constructor(e=null,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}generateNodeType(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){if(1===e.increaseUsage(this)){const t=e.addContext(this.value);this.node.build(e,this),e.setContext(t)}}setup(e){const t=e.addContext(this.value),s=this.node.build(e);return e.setContext(t),s}generate(e,t){const s=e.addContext(this.value),i=this.node.build(e,t);return e.setContext(s),i}}const au=(e=null,t={})=>{let s=e;return null!==s&&!0===s.isNode||(t=s||t,s=null),new nu(s,t)},ou=(e,t)=>au(e,{nodeName:t});wa("context",au),wa("label",function(e,t){return Et('TSL: "label()" has been deprecated. Use "setName()" instead.'),ou(e,t)}),wa("uniformFlow",e=>au(e,{uniformFlow:!0})),wa("setName",ou),wa("builtinShadowContext",(e,t,s)=>function(e,t,s=null){return au(s,{getShadow:({light:s,shadowColorNode:i})=>t===s?i.mul(e):i})}(t,s,e)),wa("builtinAOContext",(e,t)=>function(e,t=null){return au(t,{getAO:(t,{material:s})=>!0===s.transparent?t:null!==t?t.mul(e):e})}(t,e)),wa("builtinGIContext",(e,t,s)=>function(e,t,s=null){const i=e.max(.001);return au(s,{getAO:(e,{material:t})=>!0===t.transparent?e:null!==e?e.mul(i):i,getGI:(e,{material:s})=>{if(!0===s.transparent)return e;const r=t.div(i);return null!==e?e.add(r):r}})}(t,s,e));class lu extends ha{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)}generateNodeType(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],s=this.getShared(t);if(this!==s)return s.build(...e);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 a=!1,o=!1;i&&(a=e.isDeterministic(t),o=n?i:a);const l=this.getNodeType(e);if("void"==l){!0!==this.isIntent(e)&&At('TSL: ".toVar()" can not be used with void type.',this.stackTrace);return t.build(e)}const h=e.getVectorType(l),u=t.build(e,h),c=e.getVarFromNode(this,s,h,void 0,o),d=e.getPropertyName(c);let p=d;if(o)if(n)p=a?`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 hu=to(lu);wa("toVar",(e,t=null)=>hu(e,t).toStack()),wa("toConst",(e,t=null)=>hu(e,t,!0).toStack()),wa("toVarIntent",e=>hu(e).setIntent(!0).toStack());class uu extends ha{static get type(){return"SubBuild"}constructor(e,t,s=null){super(s),this.node=e,this.name=t,this.isSubBuildNode=!0}generateNodeType(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 cu=(e,t,s=null)=>new uu(Qa(e),t,s);class du extends ha{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=cu(e,"VERTEX"),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)}generateNodeType(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,a=this.interpolationSampling;t.varying=s=e.getVaryingFromNode(this,i,r,n,a),t.node=cu(this.node,"VERTEX")}return s.needsInterpolation||(s.needsInterpolation="fragment"===e.shaderStage),s}setup(e){this.setupVarying(e),e.flowNodeFromShaderStage(Kn,this.node)}analyze(e){this.setupVarying(e),e.flowNodeFromShaderStage(Kn,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,Kn);if(e.shaderStage===Kn){const t=s.node.build(e,r);e.addLineFlowCode(`${n} = ${t}`,this)}else e.flowNodeFromShaderStage(Kn,s.node,r,n);s[t]=n}return e.getPropertyName(i)}}const pu=to(du).setParameterLength(1,2);wa("toVarying",pu),wa("toVertexStage",e=>pu(e));const mu=ao(([e])=>{const t=e.mul(.9478672986).add(.0521327014).pow(2.4),s=e.mul(.0773993808),i=e.lessThanEqual(.04045);return Kh(t,s,i)}).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),fu=ao(([e])=>{const t=e.pow(.41666).mul(1.055).sub(.055),s=e.mul(12.92),i=e.lessThanEqual(.0031308);return Kh(t,s,i)}).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),gu="WorkingColorSpace";class yu extends da{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===gu?Jt.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!==Jt.enabled&&s!==i&&s&&i?(Jt.getTransfer(s)===tt&&(r=wo(mu(r.rgb),r.a)),Jt.getPrimaries(s)!==Jt.getPrimaries(i)&&(r=wo(Co(Jt._getMatrix(new Xt,s,i)).mul(r.rgb),r.a)),Jt.getTransfer(i)===tt&&(r=wo(fu(r.rgb),r.a)),r):r}}const bu=(e,t)=>new yu(Qa(e),t,gu);wa("workingToColorSpace",(e,t)=>new yu(Qa(e),gu,t)),wa("colorSpaceToWorking",bu);class _u extends ua{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}generateNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),s=this.referenceNode.getNodeType(e),i=this.getNodeType(e);return e.format(t,s,i)}}class xu extends ha{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=ea}setGroup(e){return this.group=e,this}element(e){return new _u(this,Qa(e))}setNodeType(e){const t=yl(null,e);null!==this.group&&t.setGroup(this.group),this.node=t}generateNodeType(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 vu extends xu{static get type(){return"RendererReferenceNode"}constructor(e,t,s=null){super(e,t,s),this.renderer=s,this.setGroup(ml)}updateReference(e){return this.reference=null!==this.renderer?this.renderer:e.renderer,this.reference}}const Tu=(e,t,s=null)=>new vu(e,t,s);class Su extends da{static get type(){return"ToneMappingNode"}constructor(e,t=wu,s=null){super("vec3"),this._toneMapping=e,this.exposureNode=t,this.colorNode=s}customCacheKey(){return Vn(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=wo(r(t.rgb,this.exposureNode),t.a):(At("ToneMappingNode: Unsupported Tone Mapping configuration.",s),i=t),i}}const wu=Tu("toneMappingExposure","float");wa("toneMapping",(e,t,s)=>((e,t,s)=>new Su(e,Qa(t),Qa(s)))(t,s,e));const Mu=new WeakMap;function Eu(e,t){let s=Mu.get(e);return void 0===s&&(s=new Ki(e,t),Mu.set(e,s)),s}class Au extends ba{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=ct,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){let t;if(0===this.bufferStride&&0===this.bufferOffset){let s=e.globalCache.getData(this.value);void 0===s&&(s={node:this},e.globalCache.setData(this.value,s)),t=s.node.id}else t=this.id;return String(t)}generateNodeType(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 a;a=!0===i.isInterleavedBuffer?i:!0===i.isBufferAttribute?Eu(i.array,r):Eu(i,r);const o=new Zi(a,s,n);a.setUsage(this.usage),this.attribute=o,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){const t=this.getNodeType(e),s=e.context.nodeName;void 0!==s&&delete e.context.nodeName;const i=e.getBufferAttributeFromNode(this,t,s),r=e.getPropertyName(i);let n=null;if("vertex"===e.shaderStage||"compute"===e.shaderStage)this.name=r,n=r;else{let i;s&&(i=s+"Varying");n=pu(this,i).build(e,t)}return n}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 Nu(e,t=null,s=0,i=0,r=35044,n=!1){return"mat3"===t||null===t&&9===e.itemSize?Co(new Au(e,"vec3",9,0).setUsage(r).setInstanced(n),new Au(e,"vec3",9,3).setUsage(r).setInstanced(n),new Au(e,"vec3",9,6).setUsage(r).setInstanced(n)):"mat4"===t||null===t&&16===e.itemSize?Ro(new Au(e,"vec4",16,0).setUsage(r).setInstanced(n),new Au(e,"vec4",16,4).setUsage(r).setInstanced(n),new Au(e,"vec4",16,8).setUsage(r).setInstanced(n),new Au(e,"vec4",16,12).setUsage(r).setInstanced(n)):new Au(e,t,s,i).setUsage(r)}const Cu=(e,t=null,s=0,i=0)=>Nu(e,t,s,i),Ru=(e,t=null,s=0,i=0)=>Nu(e,t,s,i,ct,!0),Pu=(e,t=null,s=0,i=0)=>Nu(e,t,s,i,dt,!0);wa("toAttribute",e=>Cu(e.value,e.bufferType));class Bu extends ha{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===Bu.VERTEX)i=e.getVertexIndex();else if(s===Bu.INSTANCE)i=e.getInstanceIndex();else if(s===Bu.DRAW)i=e.getDrawIndex();else if(s===Bu.INVOCATION_LOCAL)i=e.getInvocationLocalIndex();else if(s===Bu.INVOCATION_SUBGROUP)i=e.getInvocationSubgroupIndex();else{if(s!==Bu.SUBGROUP)throw new Error("THREE.IndexNode: Unknown scope: "+s);i=e.getSubgroupIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)r=i;else{r=pu(this).build(e,t)}return r}}Bu.VERTEX="vertex",Bu.INSTANCE="instance",Bu.SUBGROUP="subgroup",Bu.INVOCATION_LOCAL="invocationLocal",Bu.INVOCATION_SUBGROUP="invocationSubgroup",Bu.DRAW="draw";const Fu=so(Bu,Bu.VERTEX),Lu=so(Bu,Bu.INSTANCE);Bu.SUBGROUP,Bu.INVOCATION_SUBGROUP,Bu.INVOCATION_LOCAL;const Du=so(Bu,Bu.DRAW);class Ou extends ha{static get type(){return"ComputeNode"}constructor(e,t){super("void"),this.isComputeNode=!0,this.computeNode=e,this.workgroupSize=t,this.count=null,this.dispatchSize=null,this.version=1,this.name="",this.onInitFunction=null,this.countNode=null,this.updateBeforeType=Zn}setName(e){return this.name=e,this}label(e){return Et('TSL: "label()" has been deprecated. Use "setName()" instead.',new In),this.setName(e)}onInit(e){return this.onInitFunction=e,this}getUpdateBeforeType(e){return e.compute!==this?this.updateBeforeType:Qn}updateBefore({renderer:e}){e.compute(this)}setup(e){null!==this.count&&null===this.countNode&&(this.countNode=yl(this.count,"uint").onObjectUpdate(()=>this.count));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");if(""!==t&&e.addLineFlowCode(t,this),null!==this.count&&!0===e.allowEarlyReturns){const t=this.countNode.build(e,"uint"),s=Lu.build(e,"uint");e.flow.code=`${e.tab}if ( ${s} >= ${t} ) { return; }\n\n${e.flow.code}`}}else{const s=e.getNodeProperties(this).outputComputeNode;if(s)return s.build(e,t)}}}const Iu=(e,t=[64])=>{(0===t.length||t.length>3)&&At("TSL: compute() workgroupSize must have 1, 2, or 3 elements",new In);for(let e=0;e<t.length;e++){const s=t[e];("number"!=typeof s||s<=0||!Number.isInteger(s))&&At(`TSL: compute() workgroupSize element at index [ ${e} ] must be a positive integer`,new In)}for(;t.length<3;)t.push(1);return new Ou(Qa(e),t)};wa("compute",(e,t,s)=>{const i=Iu(e,s);return"number"==typeof t?i.count=t:i.dispatchSize=t,i}),wa("computeKernel",Iu);class Uu extends ha{static get type(){return"IsolateNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isIsolateNode=!0}generateNodeType(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 ku=e=>new Uu(Qa(e));wa("cache",function(e,t=!0){return Et('TSL: "cache()" has been deprecated. Use "isolate()" instead.'),ku(e).setParent(t)}),wa("isolate",ku);class zu extends ha{static get type(){return"BypassNode"}constructor(e,t){super(),this.isBypassNode=!0,this.outputNode=e,this.callNode=t}generateNodeType(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)}}wa("bypass",to(zu).setParameterLength(2));const Vu=ao(([e,t,s,i=co(0),r=co(1),n=fo(!1)])=>{let a=e.sub(t).div(s.sub(t));return Ya(n)&&(a=a.clamp()),a.mul(r.sub(i)).add(i)});wa("remap",Vu),wa("remapClamp",function(e,t,s,i=co(0),r=co(1)){return Vu(e,t,s,i,r,!0)});class Gu extends ha{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 $u=to(Gu).setParameterLength(1,2);wa("discard",e=>(e?ru(e,$u("discard")):$u("discard")).toStack());const ju=ao(([e])=>wo(e.rgb.mul(e.a),e.a),{color:"vec4",return:"vec4"}),Wu=ao(([e])=>e.a.equal(0).select(wo(0),wo(e.rgb.div(e.a),e.a)),{color:"vec4",return:"vec4"});class Hu extends da{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;t=wo(t.rgb,t.a.clamp(0,1)),t=Wu(t);const s=(null!==this._toneMapping?this._toneMapping:e.toneMapping)||0,i=(null!==this.outputColorSpace?this.outputColorSpace:e.outputColorSpace)||Qe;return 0!==s&&(t=t.toneMapping(s)),i!==Qe&&i!==Jt.workingColorSpace&&(t=t.workingToColorSpace(i)),t=ju(t),t}}const qu=(e,t=null,s=null)=>new Hu(Qa(e),t,s);wa("renderOutput",qu);class Xu extends da{static get type(){return"DebugNode"}constructor(e,t=null){super(),this.node=e,this.callback=t}generateNodeType(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);if(null!==t)t(e,s);else{const t="--- TSL debug - "+e.shaderStage+" shader ---",i="-".repeat(t.length);let r="";r+="// #"+t+"#\n",r+=e.flow.code.replace(/^\t/gm,"")+"\n",r+="/* ... */ "+s+" /* ... */\n",r+="// #"+i+"#\n",wt(r)}return s}}wa("debug",(e,t=null)=>new Xu(Qa(e),t).toStack());class Yu extends Pt{constructor(){super(),this._renderer=null,this.currentFrame=null,this.isRunning=!1,this.enabled=!0}get nodeFrame(){return this._renderer._nodes.nodeFrame}setRenderer(e){return this._renderer=e,this}getRenderer(){return this._renderer}begin(){this.isRunning=!0}finish(){this.isRunning=!1}inspect(){}computeAsync(){}beginCompute(){}finishCompute(){}beginRender(){}finishRender(){}copyTextureToTexture(){}copyFramebufferToTexture(){}dispose(){!0===this.isRunning&&this.finish(),this.dispatchEvent({type:"dispose"})}}class Ku extends ha{static get type(){return"InspectorNode"}constructor(e,t="",s=null){super(),this.node=e,this.name=t,this.callback=s,this.updateType=Zn,this.isInspectorNode=!0}getName(){return this.name||this.node.name}update(e){e.renderer.inspector.inspect(this)}generateNodeType(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!==Yu&&Nt('TSL: ".toInspector()" is only available with WebGPU.'),t}}wa("toInspector",function(e,t="",s=null){return(e=Qa(e)).before(new Ku(e,t,s))});class Qu extends ha{static get type(){return"AttributeNode"}constructor(e,t=null){super(t),this.global=!0,this._attributeName=e}getHash(e){return this.getAttributeName(e)}generateNodeType(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 pu(this).build(e,s)}return Et(`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 Zu=(e,t=null)=>new Qu(e,t),Ju=(e=0)=>Zu("uv"+(e>0?e:""),"vec2");class ec extends ha{static get type(){return"TextureSizeNode"}constructor(e,t=null){super("uvec2"),this.isTextureSizeNode=!0,this.textureNode=e,this.levelNode=t}generate(e){const t=this.textureNode.build(e,"property"),s=null===this.levelNode?"0":this.levelNode.build(e,"int"),i=e.generateTextureSize(this.textureNode.value,t,s);return e.format(i,this.getNodeType(e))}}const tc=to(ec).setParameterLength(1,2);class sc extends gl{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=Zn}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 ic=to(sc).setParameterLength(1);class rc extends Error{constructor(e,t=null){super(e),this.name="NodeError",this.stackTrace=t}}const nc=new hs;class ac extends gl{static get type(){return"TextureNode"}constructor(e=nc,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.gatherNode=null,this.offsetNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=Qn,this.referenceNode=null,this._value=e,this._matrixUniform=null,this._flipYUniform=null,this._samplerComparison=!1,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}generateNodeType(){return null!==this.gatherNode?"vec4":Hn(this.value)}getInputType(){return"texture"}getDefaultUV(){return Ju(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return null===this._matrixUniform&&(this._matrixUniform=yl(this.value.matrix)),this._matrixUniform.mul(xo(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this}setupUV(e,t){return e.isFlipY()&&(null===this._flipYUniform&&(this._flipYUniform=yl(!1)),t=t.toVar(),t=this.sampler?this._flipYUniform.select(t.flipY(),t):this._flipYUniform.select(t.setY(po(tc(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 rc("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().",this.stackTrace);const i=ao(()=>{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?ea:Qn,t})();let r=this.levelNode;null===r&&e.context.getTextureLevel&&(r=e.context.getTextureLevel(this));let n=null,a=null;if(null!==this.compareNode)if(e.renderer.hasCompatibility(yt))n=this.compareNode;else{const e=s.compareFunction;null===e||513===e||e===at||e===ot||e===ht?a=this.compareNode:(n=this.compareNode,Nt('TSL: Only "LessCompare", "LessEqualCompare", "GreaterCompare" and "GreaterEqualCompare" are supported for depth texture comparison fallback.'))}t.uvNode=i,t.levelNode=r,t.biasNode=this.biasNode,t.compareNode=n,t.compareStepNode=a,t.gradNode=this.gradNode,t.gatherNode=this.gatherNode,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,a,o,l,h,u){const c=this.value;let d;return d=r?e.generateTextureBias(c,t,s,r,n,h):o?e.generateTextureGrad(c,t,s,o,n,h):l?a?e.generateTextureGatherCompare(c,t,s,a,n,h,u):e.generateTextureGather(c,t,s,l,n,h,u):a?e.generateTextureCompare(c,t,s,a,n,h):!1===this.sampler?e.generateTextureLoad(c,t,s,i,n,h):i?e.generateTextureLevel(c,t,s,i,n,h):e.generateTexture(c,t,s,n,h),d}generate(e,t){const s=this.value,i=e.getNodeProperties(this),r=super.generate(e,"property");if(/^sampler/.test(t)){if("samplerComparison"===t){this._samplerComparison=!0;this.getSharedNode(e)._samplerComparison=!0}return r+"_sampler"}if(e.isReference(t))return r;{const n=e.getDataFromNode(this),a=this.getNodeType(e);let o=n.propertyName;if(void 0===o){const{uvNode:t,levelNode:l,biasNode:h,compareNode:u,compareStepNode:c,depthNode:d,gradNode:p,gatherNode:m,offsetNode:f}=i,g=this.generateUV(e,t),y=l?l.build(e,"float"):null,b=h?h.build(e,"float"):null,_=d?d.build(e,"int"):null,x=u?u.build(e,"float"):null,v=c?c.build(e,"float"):null,T=p?[p[0].build(e,"vec2"),p[1].build(e,"vec2")]:null,S=m?m.build(e,"int"):null,w=f?this.generateOffset(e,f):null,M=this._flipYUniform?this._flipYUniform.build(e,"bool"):null;let E=_;null===E&&s.isArrayTexture&&!0!==this.isTexture3DNode&&(E="0");const A=e.getVarFromNode(this);o=e.getPropertyName(A);let N,C=this.generateSnippet(e,r,g,y,b,E,x,T,S,w,M);if(N=!0===s.isDepthTexture&&null===S?"float":s.type===K?"uvec4":s.type===Y?"ivec4":"vec4",C=e.format(C,N,a),null!==v){const t=s.compareFunction;C=t===ot||t===ht?zh($u(C,a),$u(v,"float")).build(e,a):zh($u(v,"float"),$u(C,a)).build(e,a)}e.addLineFlowCode(`${o} = ${C}`,this),n.snippet=C,n.propertyName=o}let l=o;return e.needsToWorkingColorSpace(s)&&(l=bu($u(l,a),s.colorSpace).setup(e).build(e,a)),e.format(l,a,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}sample(e){const t=this.clone();return t.uvNode=Qa(e),t.referenceNode=this.getBase(),Qa(t)}load(e){return this.sample(e).setSampler(!1)}blur(e){const t=this.clone();t.biasNode=Qa(e).mul(ic(t)),t.referenceNode=this.getBase();const s=t.value;return!1===t.generateMipmaps&&(s&&!1===s.generateMipmaps||s.minFilter===k||s.magFilter===k)&&(Et("TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture."),t.biasNode=null),Qa(t)}level(e){const t=this.clone();return t.levelNode=Qa(e),t.referenceNode=this.getBase(),Qa(t)}size(e){return tc(this,e)}bias(e){const t=this.clone();return t.biasNode=Qa(e),t.referenceNode=this.getBase(),Qa(t)}getBase(){return this.referenceNode?this.referenceNode.getBase():this}compare(e){const t=this.clone();return t.compareNode=Qa(e),t.referenceNode=this.getBase(),Qa(t)}grad(e,t){const s=this.clone();return s.gradNode=[Qa(e),Qa(t)],s.referenceNode=this.getBase(),Qa(s)}gather(e=0){const t=this.clone();return t.gatherNode=Qa(e),t.referenceNode=this.getBase(),Qa(t)}isSampleCompare(){return null!==this.compareNode||!0===this._samplerComparison}depth(e){const t=this.clone();return t.depthNode=Qa(e),t.referenceNode=this.getBase(),Qa(t)}offset(e){const t=this.clone();return t.offsetNode=Qa(e),t.referenceNode=this.getBase(),Qa(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.gatherNode=this.gatherNode,e.offsetNode=this.offsetNode,e}}const oc=to(ac).setParameterLength(1,4).setName("texture"),lc=(e=nc,t=null,s=null,i=null)=>{let r;return e&&!0===e.isTextureNode?(r=Qa(e.clone()),r.referenceNode=e.getBase(),null!==t&&(r.uvNode=Qa(t)),null!==s&&(r.levelNode=Qa(s)),null!==i&&(r.biasNode=Qa(i))):r=oc(e,t,s,i),r},hc=(...e)=>lc(...e).setSampler(!1);class uc extends gl{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 cc=(e,t,s)=>new uc(e,t,s);class dc extends ua{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),s=this.getNodeType(e),i=this.node.getPaddedType();return e.format(t,i,s)}}class pc extends uc{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=null===t?Wn(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=Jn,this.isArrayBufferNode=!0}generateNodeType(){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(){this.updateBuffer()}onUpdate(e,t){return e=e.bind(this),super.onUpdate((t,s)=>{e(t,s),this.updateBuffer()},t)}updateBuffer(){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,this.updateBuffer(),super.setup(e)}element(e){return new dc(this,Qa(e))}}const mc=(e,t)=>new pc(e,t);class fc extends ha{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}}const gc=to(fc).setParameterLength(1);let yc,bc;class _c extends ha{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this.isViewportNode=!0}generateNodeType(){return this.scope===_c.VIEWPORT?"vec4":"vec2"}update({renderer:e}){const t=e.getRenderTarget();this.scope===_c.VIEWPORT?null!==t?bc.copy(t.viewport):(e.getViewport(bc),bc.multiplyScalar(e.getPixelRatio())):null!==t?(yc.width=t.width,yc.height=t.height):e.getDrawingBufferSize(yc)}setup(){const e=this.scope;let t=null;t=e===_c.SIZE?yl(yc||(yc=new $t)).setGroup(ml):e===_c.VIEWPORT?yl(bc||(bc=new us)).setGroup(ml):go(Sc.div(Tc));let s=Qn;return this.scope!==_c.SIZE&&this.scope!==_c.VIEWPORT||(s=Jn),this.updateType=s,t}generate(e){if(this.scope===_c.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const s=e.getNodeProperties(Tc).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${s}.y - ${t}.y )`}return t}return super.generate(e)}}_c.COORDINATE="coordinate",_c.VIEWPORT="viewport",_c.SIZE="size",_c.UV="uv";const xc=yl(1).setGroup(ml).onRenderUpdate(({renderer:e})=>e.getPixelRatio()),vc=so(_c,_c.UV),Tc=so(_c,_c.SIZE),Sc=so(_c,_c.COORDINATE),wc=so(_c,_c.VIEWPORT),Mc=wc.zw;wc.xy;let Ec=null,Ac=null,Nc=null,Cc=null,Rc=null,Pc=null,Bc=null,Fc=null,Lc=null,Dc=null,Oc=null,Ic=null;const Uc=yl(0,"uint").setName("u_cameraIndex").setGroup(pl("cameraIndex")).toVarying("v_cameraIndex"),kc=yl("float").setName("cameraNear").setGroup(ml).onRenderUpdate(({camera:e})=>e.near),zc=yl("float").setName("cameraFar").setGroup(ml).onRenderUpdate(({camera:e})=>e.far),Vc=ao(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(const t of e.cameras)s.push(t.projectionMatrix);null===Ac?Ac=mc(s).setGroup(ml).setName("cameraProjectionMatrices"):Ac.array=s,t=Ac.element(e.isMultiViewCamera?gc("gl_ViewID_OVR"):Uc)}else null===Ec&&(Ec=yl(e.projectionMatrix).setName("cameraProjectionMatrix").setGroup(ml).onRenderUpdate(({camera:e})=>e.projectionMatrix)),t=Ec;return t}).once()(),Gc=ao(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(const t of e.cameras)s.push(t.projectionMatrixInverse);null===Cc?Cc=mc(s).setGroup(ml).setName("cameraProjectionMatricesInverse"):Cc.array=s,t=Cc.element(e.isMultiViewCamera?gc("gl_ViewID_OVR"):Uc)}else null===Nc&&(Nc=yl(e.projectionMatrixInverse).setName("cameraProjectionMatrixInverse").setGroup(ml).onRenderUpdate(({camera:e})=>e.projectionMatrixInverse)),t=Nc;return t}).once()(),$c=ao(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(const t of e.cameras)s.push(t.matrixWorldInverse);null===Pc?Pc=mc(s).setGroup(ml).setName("cameraViewMatrices"):Pc.array=s,t=Pc.element(e.isMultiViewCamera?gc("gl_ViewID_OVR"):Uc)}else null===Rc&&(Rc=yl(e.matrixWorldInverse).setName("cameraViewMatrix").setGroup(ml).onRenderUpdate(({camera:e})=>e.matrixWorldInverse)),t=Rc;return t}).once()(),jc=ao(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(const t of e.cameras)s.push(t.matrixWorld);null===Fc?Fc=mc(s).setGroup(ml).setName("cameraWorldMatrices"):Fc.array=s,t=Fc.element(e.isMultiViewCamera?gc("gl_ViewID_OVR"):Uc)}else null===Bc&&(Bc=yl(e.matrixWorld).setName("cameraWorldMatrix").setGroup(ml).onRenderUpdate(({camera:e})=>e.matrixWorld)),t=Bc;return t}).once()(),Wc=ao(({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 Wt);null===Dc?Dc=mc(s).setGroup(ml).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)}):Dc.array=s,t=Dc.element(e.isMultiViewCamera?gc("gl_ViewID_OVR"):Uc)}else null===Lc&&(Lc=yl(new Wt).setName("cameraPosition").setGroup(ml).onRenderUpdate(({camera:e},t)=>t.value.setFromMatrixPosition(e.matrixWorld))),t=Lc;return t}).once()(),Hc=ao(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(const t of e.cameras)s.push(t.viewport);null===Ic?Ic=mc(s,"vec4").setGroup(ml).setName("cameraViewports"):Ic.array=s,t=Ic.element(Uc)}else null===Oc&&(Oc=wo(0,0,Tc.x,Tc.y).toConst("cameraViewport")),t=Oc;return t}).once()(),qc=new Vi;class Xc extends ha{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=ea,this.uniformNode=new gl(null)}generateNodeType(){const e=this.scope;return e===Xc.WORLD_MATRIX?"mat4":e===Xc.POSITION||e===Xc.VIEW_POSITION||e===Xc.DIRECTION||e===Xc.SCALE?"vec3":e===Xc.RADIUS?"float":void 0}update(e){const t=this.object3d,s=this.uniformNode,i=this.scope;if(i===Xc.WORLD_MATRIX)s.value=t.matrixWorld;else if(i===Xc.POSITION)s.value=s.value||new Wt,s.value.setFromMatrixPosition(t.matrixWorld);else if(i===Xc.SCALE)s.value=s.value||new Wt,s.value.setFromMatrixScale(t.matrixWorld);else if(i===Xc.DIRECTION)s.value=s.value||new Wt,t.getWorldDirection(s.value);else if(i===Xc.VIEW_POSITION){const i=e.camera;s.value=s.value||new Wt,s.value.setFromMatrixPosition(t.matrixWorld),s.value.applyMatrix4(i.matrixWorldInverse)}else if(i===Xc.RADIUS){const i=e.object.geometry;null===i.boundingSphere&&i.computeBoundingSphere(),qc.copy(i.boundingSphere).applyMatrix4(t.matrixWorld),s.value=qc.radius}}generate(e){const t=this.scope;return t===Xc.WORLD_MATRIX?this.uniformNode.nodeType="mat4":t===Xc.POSITION||t===Xc.VIEW_POSITION||t===Xc.DIRECTION||t===Xc.SCALE?this.uniformNode.nodeType="vec3":t===Xc.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}}Xc.WORLD_MATRIX="worldMatrix",Xc.POSITION="position",Xc.SCALE="scale",Xc.VIEW_POSITION="viewPosition",Xc.DIRECTION="direction",Xc.RADIUS="radius";const Yc=new ps;class Kc extends Xc{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const Qc=so(Kc,Kc.WORLD_MATRIX),Zc=yl(new Xt).onObjectUpdate(({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld)),Jc=ao(e=>e.context.modelViewMatrix||ed).once()().toVar("modelViewMatrix"),ed=$c.mul(Qc),td=ao(e=>{e.context.isHighPrecisionModelViewMatrix=!0;const t=e.camera;let s;if(t.isArrayCamera&&t.cameras.length>0){const e=[];for(let s=0;s<t.cameras.length;s++)e.push(new ps);const i=mc(e).onObjectUpdate(({object:e,camera:t},s)=>{const i=t.cameras,r=s.array;for(let t=0,s=i.length;t<s;t++)r[t].multiplyMatrices(i[t].matrixWorldInverse,e.matrixWorld)});s=i.element(t.isMultiViewCamera?gc("gl_ViewID_OVR"):Uc)}else s=yl("mat4").onObjectUpdate(({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld));return s}).once()().toVar("highpModelViewMatrix"),sd=ao(e=>{const t=e.context.isHighPrecisionModelViewMatrix,s=e.camera;let i;if(s.isArrayCamera&&s.cameras.length>0){const e=[];for(let t=0;t<s.cameras.length;t++)e.push(new Xt);const t=mc(e).onObjectUpdate(({object:e,camera:t},s)=>{const i=t.cameras,r=s.array;for(let t=0,s=i.length;t<s;t++)Yc.multiplyMatrices(i[t].matrixWorldInverse,e.matrixWorld),r[t].getNormalMatrix(Yc)});i=t.element(s.isMultiViewCamera?gc("gl_ViewID_OVR"):Uc)}else i=yl("mat3").onObjectUpdate(({object:e,camera:s})=>(!0!==t&&e.modelViewMatrix.multiplyMatrices(s.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix)));return i}).once()().toVar("highpModelNormalViewMatrix"),id=ao(e=>"fragment"!==e.shaderStage?(Nt("TSL: `clipSpace` is only available in fragment stage."),wo()):e.context.clipSpace.toVarying("v_clipSpace")).once()(),rd=Zu("position","vec3"),nd=rd.toVarying("positionLocal"),ad=rd.toVarying("positionPrevious"),od=ao(e=>Qc.mul(nd).xyz.toVarying(e.getSubBuildProperty("v_positionWorld")),"vec3").once(["POSITION"])(),ld=ao(()=>nd.transformDirection(Qc).toVarying("v_positionWorldDirection").normalize().toVar("positionWorldDirection"),"vec3").once(["POSITION"])(),hd=ao(e=>{if("fragment"===e.shaderStage&&e.material.vertexNode){const e=Gc.mul(id);return e.xyz.div(e.w).toVar("positionView")}return e.context.setupPositionView().toVarying("v_positionView")},"vec3").once(["POSITION","VERTEX"])(),ud=ao(e=>{let t;return t=e.camera.isOrthographicCamera?xo(0,0,1):hd.negate().toVarying("v_positionViewDirection").normalize(),t.toVar("positionViewDirection")},"vec3").once(["POSITION"])();class cd extends ha{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 dd=co(so(cd)).mul(2).sub(1),pd=ao(([e],{material:t})=>{const s=t.side;return 1===s?e=e.mul(-1):2===s&&(e=e.mul(dd)),e}),md=Zu("normal","vec3"),fd=ao(e=>!1===e.geometry.hasAttribute("normal")?(Et('TSL: Vertex attribute "normal" not found on geometry.'),xo(0,1,0)):md,"vec3").once()().toVar("normalLocal"),gd=hd.dFdx().cross(hd.dFdy()).normalize().toVar("normalFlat"),yd=ao(e=>{let t;return t=e.isFlatShading()?gd:Sd(fd).toVarying("v_normalViewGeometry").normalize(),t},"vec3").once()().toVar("normalViewGeometry"),bd=ao(e=>{let t=yd.transformNormalByInverseViewMatrix($c);return!0!==e.isFlatShading()&&(t=t.toVarying("v_normalWorldGeometry")),t.normalize().toVar("normalWorldGeometry")},"vec3").once()(),_d=ao(e=>{let t;return"NORMAL"===e.subBuildFn||"VERTEX"===e.subBuildFn?(t=yd,!0!==e.isFlatShading()&&(t=pd(t))):t=e.context.setupNormal().context({getUV:null,getTextureLevel:null}),t},"vec3").once(["NORMAL","VERTEX"])().toVar("normalView"),xd=_d.transformNormalByInverseViewMatrix($c).toVar("normalWorld"),vd=ao(({subBuildFn:e,context:t})=>{let s;return s="NORMAL"===e||"VERTEX"===e?_d:t.setupClearcoatNormal().context({getUV:null,getTextureLevel:null}),s},"vec3").once(["NORMAL","VERTEX"])().toVar("clearcoatNormalView"),Td=ao(([e,t=Qc])=>Co(t).inverse().transpose().mul(e).normalize());wa("transformNormal",Td);const Sd=ao(([e],t)=>{const s=t.context.modelNormalViewMatrix;if(s)return e.transformNormalByViewMatrix(s);return Zc.mul(e).transformNormalByViewMatrix($c)});ao(()=>(Et('TSL: "transformedNormalView" is deprecated. Use "normalView" instead.'),_d)).once(["NORMAL","VERTEX"])(),ao(()=>(Et('TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.'),xd)).once(["NORMAL","VERTEX"])(),ao(()=>(Et('TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.'),vd)).once(["NORMAL","VERTEX"])();const wd=new ps,Md=yl(0).onReference(({material:e})=>e).onObjectUpdate(({material:e})=>e.refractionRatio),Ed=yl(1).onReference(({material:e})=>e).onObjectUpdate(function({material:e,scene:t}){return e.envMap?e.envMapIntensity:t.environmentIntensity}),Ad=yl(new ps).onReference(function(e){return e.material}).onObjectUpdate(function({material:e,scene:t}){const s=(null!==t.environment||t.environmentNode&&t.environmentNode.isNode)&&null===e.envMap?t.environmentRotation:e.envMapRotation;return s?wd.makeRotationFromEuler(s).transpose():wd.identity(),wd}),Nd=ud.negate().reflect(_d),Cd=ud.negate().refract(_d,Md),Rd=Nd.transformDirection(jc).toVar("reflectVector"),Pd=Cd.transformDirection(jc).toVar("refractVector"),Bd=new Or;class Fd extends ac{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===F?Rd:e.mapping===L?Pd:(At('CubeTextureNode: Mapping "%s" not supported.',e.mapping),xo(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const s=this.value;return!0===s.isDepthTexture?e.renderer.coordinateSystem===mt?xo(t.x,t.y.negate(),t.z):t:(t=Ad.mul(t),e.renderer.coordinateSystem!==mt&&s.isRenderTargetTexture||(t=xo(t.x.negate(),t.yz)),t)}generateUV(e,t){return t.build(e,!0===this.sampler?"vec3":"ivec3")}}const Ld=to(Fd).setParameterLength(1,4).setName("cubeTexture"),Dd=(e=Bd,t=null,s=null,i=null)=>{let r;return e&&!0===e.isCubeTextureNode?(r=Qa(e.clone()),r.referenceNode=e,null!==t&&(r.uvNode=Qa(t)),null!==s&&(r.levelNode=Qa(s)),null!==i&&(r.biasNode=Qa(i))):r=Ld(e,t,s,i),r};class Od extends ha{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=ea}element(e){return new _u(this,Qa(e))}setGroup(e){return this.group=e,this}setName(e){return this.name=e,this}label(e){return Et('TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}setNodeType(e){let t=null;null!==this.count?t=cc(null,e,this.count):Array.isArray(this.getValueFromReference())?(t=mc(null,e),t.updateType=ea):t="texture"===e?lc(null):"cubeTexture"===e?Dd(null):yl(null,e),null!==this.group&&t.setGroup(this.group),null!==this.name&&t.setName(this.name),this.node=t}generateNodeType(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 Id=(e,t,s)=>new Od(e,t,s);class Ud extends Od{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 kd=(e,t,s=null)=>new Ud(e,t,s),zd=Ju(),Vd=hd.dFdx(),Gd=hd.dFdy(),$d=zd.dFdx(),jd=zd.dFdy(),Wd=_d,Hd=Gd.cross(Wd),qd=Wd.cross(Vd),Xd=Hd.mul($d.x).add(qd.mul(jd.x)),Yd=Hd.mul($d.y).add(qd.mul(jd.y)),Kd=Xd.dot(Xd).max(Yd.dot(Yd)),Qd=Kd.equal(0).select(0,Kd.inverseSqrt()),Zd=Xd.mul(Qd).toVar("tangentViewFrame"),Jd=Yd.mul(Qd).toVar("bitangentViewFrame"),ep=Zu("tangent","vec4"),tp=ep.xyz.toVar("tangentLocal"),sp=ao(e=>{let t;return t="VERTEX"===e.subBuildFn||e.geometry.hasAttribute("tangent")?Jc.mul(wo(tp,0)).xyz.toVarying("v_tangentView").normalize():Zd,!0!==e.isFlatShading()&&(t=pd(t)),t},"vec3").once(["NORMAL","VERTEX"])().toVar("tangentView"),ip=ao(([e,t],s)=>{let i=e.mul(ep.w).xyz;return"NORMAL"===s.subBuildFn&&!0!==s.isFlatShading()&&(i=i.toVarying(t)),i}).once(["NORMAL"]),rp=Co(sp,ao(e=>{let t;return t="VERTEX"===e.subBuildFn||e.geometry.hasAttribute("tangent")?ip(_d.cross(sp),"v_bitangentView").normalize():Jd,!0!==e.isFlatShading()&&(t=pd(t)),t},"vec3").once(["NORMAL","VERTEX"])().toVar("bitangentView"),_d).toVar("TBNViewMatrix"),np=ao(()=>{let e=Yo.cross(ud);return e=e.cross(Yo).normalize(),e=Kh(e,_d,qo.mul(Io.oneMinus()).oneMinus().pow2().pow2()).normalize(),e}).once()(),ap=e=>xo(e,ah(Zh(co(1).sub(jh(e,e)))));class op extends da{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=0,this.unpackNormalMode=""}setup(e){const{normalMapType:t,scaleNode:s,unpackNormalMode:i}=this;let r=this.node.mul(2).sub(1);if(0===t?"rg"===i?r=ap(r.xy):"ga"===i?r=ap(r.yw):""!==i&&At(`THREE.NodeMaterial: Unexpected unpack normal mode: ${i}`):""!==i&&At(`THREE.NodeMaterial: Normal map type '${t}' is not compatible with unpack normal mode '${i}'`),null!==s){let t=s;!0===e.isFlatShading()&&(t=pd(t)),r=xo(r.xy.mul(t),r.z)}let n=null;return 1===t?n=Sd(r):0===t?n=rp.mul(r).normalize():(At(`NodeMaterial: Unsupported normal map type: ${t}`),n=_d),n}}const lp=to(op).setParameterLength(1,2),hp=ao(({textureNode:e,bumpScale:t})=>{const s=t=>e.isolate().context({getUV:e=>t(e.uvNode||Ju()),forceUVContext:!0}),i=co(s(e=>e));return go(co(s(e=>e.add(e.dFdx()))).sub(i),co(s(e=>e.add(e.dFdy()))).sub(i)).mul(t)}),up=ao(e=>{const{surf_pos:t,surf_norm:s,dHdxy:i}=e,r=t.dFdx().normalize(),n=s,a=t.dFdy().normalize().cross(n),o=n.cross(r),l=r.dot(a).mul(dd),h=l.sign().mul(i.x.mul(a).add(i.y.mul(o)));return l.abs().mul(s).sub(h).normalize()});class cp extends da{static get type(){return"BumpMapNode"}constructor(e,t=null){super("vec3"),this.textureNode=e,this.scaleNode=t}setup(e){if(!0===e.material.wireframe)return _d;const t=null!==this.scaleNode?this.scaleNode:1,s=hp({textureNode:this.textureNode,bumpScale:t});return up({surf_pos:hd,surf_norm:_d,dHdxy:s})}}const dp=to(cp).setParameterLength(1,2),pp=new Map;class mp extends ha{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let s=pp.get(e);return void 0===s&&(s=kd(e,t),pp.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===mp.COLOR){const e=void 0!==t.color?this.getColor(s):xo();i=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(s===mp.OPACITY){const e=this.getFloat(s);i=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(s===mp.SPECULAR_STRENGTH)i=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture("specular").r:co(1);else if(s===mp.SPECULAR_INTENSITY){const e=this.getFloat(s);i=t.specularIntensityMap&&!0===t.specularIntensityMap.isTexture?e.mul(this.getTexture(s).a):e}else if(s===mp.SPECULAR_COLOR){const e=this.getColor(s);i=t.specularColorMap&&!0===t.specularColorMap.isTexture?e.mul(this.getTexture(s).rgb):e}else if(s===mp.ROUGHNESS){const e=this.getFloat(s);i=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(s).g):e}else if(s===mp.METALNESS){const e=this.getFloat(s);i=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(s).b):e}else if(s===mp.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===mp.NORMAL)t.normalMap?(i=lp(this.getTexture("normal"),this.getCache("normalScale","vec2")),i.normalMapType=t.normalMapType,t.normalMap.format!=ce&&t.normalMap.format!=Ye&&t.normalMap.format!=Ne||(i.unpackNormalMode="rg")):i=t.bumpMap?dp(this.getTexture("bump").r,this.getFloat("bumpScale")):_d;else if(s===mp.CLEARCOAT){const e=this.getFloat(s);i=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(s).r):e}else if(s===mp.CLEARCOAT_ROUGHNESS){const e=this.getFloat(s);i=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(s).r):e}else if(s===mp.CLEARCOAT_NORMAL)i=t.clearcoatNormalMap?lp(this.getTexture(s),this.getCache(s+"Scale","vec2")):_d;else if(s===mp.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===mp.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===mp.ANISOTROPY)if(t.anisotropyMap&&!0===t.anisotropyMap.isTexture){const e=this.getTexture(s);i=No(Jp.x,Jp.y,Jp.y.negate(),Jp.x).mul(e.rg.mul(2).sub(go(1)).normalize().mul(e.b))}else i=Jp;else if(s===mp.IRIDESCENCE_THICKNESS){const e=Id("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const r=Id("0","float",t.iridescenceThicknessRange);i=e.sub(r).mul(this.getTexture(s).g).add(r)}else i=e}else if(s===mp.TRANSMISSION){const e=this.getFloat(s);i=t.transmissionMap?e.mul(this.getTexture(s).r):e}else if(s===mp.THICKNESS){const e=this.getFloat(s);i=t.thicknessMap?e.mul(this.getTexture(s).g):e}else if(s===mp.IOR)i=this.getFloat(s);else if(s===mp.LIGHT_MAP)i=t.lightMap?this.getTexture(s).rgb.mul(this.getFloat("lightMapIntensity")):xo(0);else if(s===mp.AO)i=t.aoMap?this.getTexture(s).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1):co(1);else if(s===mp.LINE_DASH_OFFSET)i=t.dashOffset?this.getFloat(s):co(0);else{const t=this.getNodeType(e);i=this.getCache(s,t)}return i}}mp.ALPHA_TEST="alphaTest",mp.COLOR="color",mp.OPACITY="opacity",mp.SHININESS="shininess",mp.SPECULAR="specular",mp.SPECULAR_STRENGTH="specularStrength",mp.SPECULAR_INTENSITY="specularIntensity",mp.SPECULAR_COLOR="specularColor",mp.REFLECTIVITY="reflectivity",mp.ROUGHNESS="roughness",mp.METALNESS="metalness",mp.NORMAL="normal",mp.CLEARCOAT="clearcoat",mp.CLEARCOAT_ROUGHNESS="clearcoatRoughness",mp.CLEARCOAT_NORMAL="clearcoatNormal",mp.EMISSIVE="emissive",mp.ROTATION="rotation",mp.SHEEN="sheen",mp.SHEEN_ROUGHNESS="sheenRoughness",mp.ANISOTROPY="anisotropy",mp.IRIDESCENCE="iridescence",mp.IRIDESCENCE_IOR="iridescenceIOR",mp.IRIDESCENCE_THICKNESS="iridescenceThickness",mp.IOR="ior",mp.TRANSMISSION="transmission",mp.THICKNESS="thickness",mp.ATTENUATION_DISTANCE="attenuationDistance",mp.ATTENUATION_COLOR="attenuationColor",mp.LINE_SCALE="scale",mp.LINE_DASH_SIZE="dashSize",mp.LINE_GAP_SIZE="gapSize",mp.LINE_WIDTH="linewidth",mp.LINE_DASH_OFFSET="dashOffset",mp.POINT_SIZE="size",mp.DISPERSION="dispersion",mp.RETROREFLECTIVITY="retroreflectivity",mp.LIGHT_MAP="light",mp.AO="ao";const fp=so(mp,mp.ALPHA_TEST),gp=so(mp,mp.COLOR),yp=so(mp,mp.SHININESS),bp=so(mp,mp.EMISSIVE),_p=so(mp,mp.OPACITY),xp=so(mp,mp.SPECULAR),vp=so(mp,mp.SPECULAR_INTENSITY),Tp=so(mp,mp.SPECULAR_COLOR),Sp=so(mp,mp.SPECULAR_STRENGTH),wp=so(mp,mp.REFLECTIVITY),Mp=so(mp,mp.ROUGHNESS),Ep=so(mp,mp.METALNESS),Ap=so(mp,mp.NORMAL),Np=so(mp,mp.CLEARCOAT),Cp=so(mp,mp.CLEARCOAT_ROUGHNESS),Rp=so(mp,mp.CLEARCOAT_NORMAL),Pp=so(mp,mp.ROTATION),Bp=so(mp,mp.SHEEN),Fp=so(mp,mp.SHEEN_ROUGHNESS),Lp=so(mp,mp.ANISOTROPY),Dp=so(mp,mp.IRIDESCENCE),Op=so(mp,mp.IRIDESCENCE_IOR),Ip=so(mp,mp.IRIDESCENCE_THICKNESS),Up=so(mp,mp.TRANSMISSION),kp=so(mp,mp.THICKNESS),zp=so(mp,mp.IOR),Vp=so(mp,mp.ATTENUATION_DISTANCE),Gp=so(mp,mp.ATTENUATION_COLOR),$p=so(mp,mp.LINE_SCALE),jp=so(mp,mp.LINE_DASH_SIZE),Wp=so(mp,mp.LINE_GAP_SIZE),Hp=so(mp,mp.LINE_WIDTH),qp=so(mp,mp.LINE_DASH_OFFSET),Xp=so(mp,mp.POINT_SIZE),Yp=so(mp,mp.DISPERSION),Kp=so(mp,mp.RETROREFLECTIVITY),Qp=so(mp,mp.LIGHT_MAP),Zp=so(mp,mp.AO),Jp=yl(new $t).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))}),em=ao(e=>e.context.setupModelViewProjection(),"vec4").once()().toVarying("v_modelViewProjection");class tm extends ha{static get type(){return"EventNode"}constructor(e,t){super("void"),this.eventType=e,this.callback=t,e===tm.OBJECT?this.updateType=ea:e===tm.MATERIAL?this.updateType=Jn:e===tm.FRAME?this.updateType=Zn:e===tm.AFTER_OBJECT?this.updateAfterType=ea:e===tm.BEFORE_OBJECT?this.updateBeforeType=ea:e===tm.BEFORE_MATERIAL?this.updateBeforeType=Jn:e===tm.BEFORE_FRAME&&(this.updateBeforeType=Zn)}setup(e){const{eventType:t,callback:s}=this;if(t===tm.BEFORE_RENDER_PIPELINE){const t=e.context.onBeforePipelineCallbacks;t&&t.push(s)}else if(t===tm.AFTER_RENDER_PIPELINE){const t=e.context.onAfterPipelineCallbacks;t&&t.push(s)}return super.setup(e)}update(e){this.callback(e)}updateBefore(e){this.callback(e)}updateAfter(e){this.callback(e)}}tm.OBJECT="object",tm.MATERIAL="material",tm.FRAME="frame",tm.AFTER_OBJECT="afterObject",tm.BEFORE_OBJECT="beforeObject",tm.BEFORE_MATERIAL="beforeMaterial",tm.BEFORE_FRAME="beforeFrame",tm.BEFORE_RENDER_PIPELINE="beforeRenderPipeline",tm.AFTER_RENDER_PIPELINE="afterRenderPipeline";const sm=(e,t)=>new tm(e,t).toStack(),im=e=>sm(tm.OBJECT,e),rm=e=>sm(tm.AFTER_OBJECT,e);class nm extends ua{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.isContextAssign();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 am=to(nm).setParameterLength(2);class om extends uc{static get type(){return"StorageBufferNode"}constructor(e,t=null,s=0){let i,r=null;t&&t.isStructTypeNode?(i="struct",r=t,(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(s=e.count)):null===t&&(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)?(i=jn(e.itemSize),s=e.count):i=t,super(e,i,s),this.isStorageBufferNode=!0,this.structTypeNode=r,this.access=ia,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){let t;if(0===this.bufferCount){let s=e.globalCache.getData(this.value);void 0===s&&(s={node:this},e.globalCache.setData(this.value,s)),t=s.node.id}else t=this.id;return String(t)}getInputType(){return this.value.isIndirectStorageBufferAttribute?"indirectStorageBuffer":"storageBuffer"}element(e){return am(this,e)}setPBO(e){return this.isPBO=e,this}getPBO(){return this.isPBO}setAccess(e){return this.access=e,this}toReadOnly(){return this.setAccess(ta)}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getAttributeData(){return null===this._attribute&&(this._attribute=Cu(this.value),this._varying=pu(this._attribute)),{attribute:this._attribute,varying:this._varying}}generateNodeType(e){if(null!==this.structTypeNode)return this.structTypeNode.getNodeType(e);if(e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.generateNodeType(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 lm=(e,t=null,s=0)=>new om(e,t,s),hm=new WeakMap,um=new WeakMap,cm=new WeakMap;function dm(e,t){let s;const i=Math.max(t.count,1);if(!0===t.isStorageInstancedBufferAttribute)s=lm(t,"mat4",i).element(Lu);else{if(16*i*4<=e.getUniformBufferLimit())s=cc(t.array,"mat4",i).element(Lu);else{let e=hm.get(t);e||(e=new An(t.array,16,1),hm.set(t,e));const i=t.usage===dt?Pu:Ru,r=[i(e,"vec4",16,0),i(e,"vec4",16,4),i(e,"vec4",16,8),i(e,"vec4",16,12)];s=Ro(...r)}}return s}const pm=Fo("vec3","vInstanceColor"),mm=ao(([e,t=null],s)=>{const i=!0===e.isStorageInstancedBufferAttribute,r=t&&!0===t.isStorageInstancedBufferAttribute,n=dm(s,e);let a=null;if(!i){16*Math.max(e.count,1)*4>s.getUniformBufferLimit()&&(a=hm.get(e))}let o=null,l=null;if(t)if(r)o=lm(t,"vec3",Math.max(t.count,1)).element(Lu);else{let e=um.get(t);e||(e=new Er(t.array,3),um.set(t,e)),l=e;const s=t.usage===dt?Pu:Ru;o=xo(s(e,"vec3",3,0))}var h;null===a&&null===l||(h=()=>{null!==a&&a.version!==e.version&&(a.clearUpdateRanges(),a.updateRanges.push(...e.updateRanges),e.clearUpdateRanges(),a.version=e.version),t&&null!==l&&l.version!==t.version&&(l.clearUpdateRanges(),l.updateRanges.push(...t.updateRanges),t.clearUpdateRanges(),l.version=t.version)},sm(tm.BEFORE_FRAME,h));const u=n.mul(nd).xyz;if(nd.assign(u),s.needsPreviousData()){const t=s.object;rm(({object:t})=>{const{previousInstanceMatrix:s}=cm.get(t);s.array.set(e.array),s.version=e.version;const i=hm.get(s);void 0!==i&&(i.version=e.version)});const i=function(e,t,s){let i=cm.get(e);if(void 0===i){const r=t.clone();i={previousInstanceMatrix:r,node:dm(s,r)},cm.set(e,i)}return i.node}(t,e,s);ad.assign(i.mul(ad).xyz)}if(s.hasGeometryAttribute("normal")){const e=Td(fd,n);fd.assign(e)}null!==o&&pm.assign(o)},"void"),fm=ao(([e])=>{const{instanceMatrix:t,instanceColor:s}=e;mm(t,s)},"void"),gm=new WeakMap,ym=ao(([e,t])=>{const s=po(tc(hc(e),0).x).toConst(),i=po(t),r=i.mod(s).toConst(),n=i.div(s).toConst();return hc(e,yo(r,n))}),bm=ao(([e,t])=>{const s=po(tc(hc(e),0).x).toConst(),i=po(t).mod(s).toConst(),r=po(t).div(s).toConst();return hc(e,yo(i,r)).x});function _m(e,t){const s=po(tc(hc(e),0).x).toConst(),i=co(t).mul(4).toInt().toConst(),r=i.mod(s).toConst(),n=i.div(s).toConst();return Ro(hc(e,yo(r,n)),hc(e,yo(r.add(1),n)),hc(e,yo(r.add(2),n)),hc(e,yo(r.add(3),n)))}const xm=Fo("vec4","vBatchColor"),vm=Fo("uint","vBatchIndirectId"),Tm=ao(([e],t)=>{const s=null===t.getDrawIndex()?Lu:Du,i=bm(e._indirectTexture,po(s));vm.assign(i);const r=_m(e._matricesTexture,i),n=e._colorsTexture;if(null!==n){const e=ym(n,i);xm.assign(e)}const a=Co(r);if(nd.assign(r.mul(nd)),t.needsPreviousData()){rm(({object:e})=>{const t=gm.get(e);t.previousMatricesTexture.image.data.set(e._matricesTexture.image.data),t.previousMatricesTexture.needsUpdate=!0});const t=function(e,t){let s=gm.get(e);if(void 0===s){const{image:i,format:r,type:n}=e._matricesTexture,a=new Mr(i.data.slice(),i.width,i.height,r,n);s={previousMatricesTexture:a,node:_m(a,t)},gm.set(e,s)}return s.node}(e,i);ad.assign(t.mul(ad).xyz)}const o=fd.div(xo(a[0].dot(a[0]),a[1].dot(a[1]),a[2].dot(a[2]))),l=a.mul(o).xyz;fd.assign(l),t.hasGeometryAttribute("tangent")&&tp.mulAssign(a)},"void"),Sm=new WeakMap,wm=new WeakMap;function Mm(e){return{element:t=>{const s=po(tc(e).x).toConst(),i=po(t).mul(4).toConst(),r=i.div(s).toConst(),n=i.sub(r.mul(s)).toConst();return Ro(e.load(yo(n,r)),e.load(yo(n.add(1),r)),e.load(yo(n.add(2),r)),e.load(yo(n.add(3),r)))}}}function Em(e,t){let s;if(16*t.bones.length*4<=e.getUniformBufferLimit())i="skeleton.boneMatrices",r="mat4",n=t.bones.length,s=new Od(i,r,a,n);else{null===t.boneTexture&&t.computeBoneTexture();const e=lc(t.boneTexture);im(({object:t})=>{const s=t.skeleton;null===s.boneTexture&&s.computeBoneTexture(),e.value=s.boneTexture}),s=Mm(e)}var i,r,n,a;return s}function Am(e,t,s,i,r,n){const a=e.element(r.x),o=e.element(r.y),l=e.element(r.z),h=e.element(r.w),u=s.mul(t),c=wl(a.mul(n.x).mul(u),o.mul(n.y).mul(u),l.mul(n.z).mul(u),h.mul(n.w).mul(u));return i.mul(c).xyz}const Nm=ao(([e],t)=>{const s=Zu("skinIndex","uvec4"),i=Zu("skinWeight","vec4"),r=Id("bindMatrix","mat4"),n=Id("bindMatrixInverse","mat4"),a=Em(t,e.skeleton);if(im(({object:e,frameId:t})=>{const s=e.skeleton;if(Sm.get(s)!==t){Sm.set(s,t);const e=wm.get(s);void 0!==e&&(e.previousBoneMatrices.set(s.boneMatrices),null!==e.previousBoneTexture&&(e.previousBoneTexture.needsUpdate=!0)),s.update()}}),t.needsPreviousData()){const a=function(e,t,s,i,r,n){const a=t.skeleton;let o=wm.get(a);if(void 0===o){if(a.update(),16*a.bones.length*4<=e.getUniformBufferLimit()){const e=new Float32Array(a.boneMatrices);o={previousBoneMatrices:e,previousBoneTexture:null,node:cc(e,"mat4",a.bones.length)}}else{null===a.boneTexture&&a.computeBoneTexture();const{width:e,height:t}=a.boneTexture.image,s=new Float32Array(a.boneMatrices),i=new Mr(s,e,t,ae,Q);i.needsUpdate=!0,o={previousBoneMatrices:s,previousBoneTexture:i,node:Mm(lc(i))}}wm.set(a,o)}return Am(o.node,ad,s,i,r,n)}(t,e,r,n,s,i);ad.assign(a)}const o=Am(a,nd,r,n,s,i);if(nd.assign(o),t.hasGeometryAttribute("normal")){const{skinNormal:e,skinTangent:o}=function(e,t,s,i,r,n,a){const o=e.element(n.x),l=e.element(n.y),h=e.element(n.z),u=e.element(n.w);let c=wl(a.x.mul(o),a.y.mul(l),a.z.mul(h),a.w.mul(u));c=r.mul(c).mul(i);const d=Co(c);return{skinNormal:d.mul(t),skinTangent:d.mul(s)}}(a,fd,tp,r,n,s,i);fd.assign(e),t.hasGeometryAttribute("tangent")&&tp.assign(o)}},"void");class Cm extends ha{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={},i=this._getInternalParams();for(let e=0,t=i.length-1;e<t;e++){const t=i[e],r=!0!==t.isNode&&t.name||this.getVarName(e),n=!0!==t.isNode&&t.type||"int";s[r]=$u(r,n)}const r=e.addStack(),n=i[i.length-1](s);t.returnsNode=n.context({nodeLoop:n}),t.stackNode=r;const a=i[0];if(!0!==a.isNode&&"function"==typeof a.update){const e=ao(a.update)(s);t.updateNode=e.context({nodeLoop:e})}return e.removeStack(),t}_getInternalParams(){const e=this.params;return"function"==typeof e[0]?[fo(!0),e[0]]:e}setup(e){if(this.getProperties(e),e.fnCall){e.getDataFromNode(e.fnCall.shaderNode).hasLoop=!0}}generate(e){const t=this.getProperties(e),s=this._getInternalParams(),i=t.stackNode;for(let i=0,r=s.length-1;i<r;i++){const r=s[i];let n,a=!1,o=null,l=null,h=null,u=null,c=null,d=null;if(r.isNode?"bool"===r.getNodeType(e)?(a=!0,u="bool",l=r.build(e,u)):(u="int",h=this.getVarName(i),o="0",l=r.build(e,u),c="<"):(u=r.type||"int",h=r.name||this.getVarName(i),o=r.start,l=r.end,c=r.condition,d=r.update,"number"==typeof o?o=e.generateConst(u,o):o&&o.isNode&&(o=o.build(e,u)),"number"==typeof l?l=e.generateConst(u,l):l&&l.isNode&&(l=l.build(e,u)),void 0!==o&&void 0===l?(o+=" - 1",l="0",c=">="):void 0!==l&&void 0===o&&(o="0",c="<"),void 0===c&&(c=Number(o)>Number(l)?">=":"<")),a)n=`while ( ${l} )`;else{const s={start:o,end:l},i=s.start,r=s.end;let a;const p=()=>c.includes("<")?"+=":"-=";if(null!=d)switch(typeof d){case"function":a=e.flowStagesNode(t.updateNode,"void").code.replace(/\t|;/g,"");break;case"number":a=h+" "+p()+" "+e.generateConst(u,d);break;case"string":a=h+" "+d;break;default:d.isNode?a=h+" "+p()+" "+d.build(e):(At("TSL: 'Loop( { update: ... } )' is not a function, string or number.",this.stackTrace),a="break /* invalid update */")}else d="int"===u||"uint"===u?c.includes("<")?"++":"--":p()+" 1.",a=h+" "+d;n=`for ( ${e.getVar(u,h)+" = "+i}; ${h+" "+c+" "+r}; ${a} )`}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,i=s.length-1;t<i;t++)e.addFlowCode((0===t?"":e.tab)+"}\n\n").removeFlowTab();e.addFlowTab()}}const Rm=(...e)=>new Cm(eo(e,"int")).toStack(),Pm=new WeakMap,Bm=new us,Fm=new WeakMap,Lm=ao(({bufferMap:e,influence:t,stride:s,width:i,depth:r,offset:n})=>{const a=po(Fu).mul(s).add(n),o=a.div(i),l=a.sub(o.mul(i));return hc(e,yo(l,o)).depth(r).xyz.mul(t)});const Dm=ao(([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;if(0===n)return;let a=Fm.get(e);void 0!==a&&a.count===n||(a={base:yl(1),influences:e.morphTargetInfluences?mc(e.morphTargetInfluences,"float"):null,count:n},Fm.set(e,a));const{base:o,influences:l}=a,{texture:h,stride:u,size:c}=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 a=Pm.get(e);if(void 0===a||a.count!==n){void 0!==a&&a.texture.dispose();const o=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 ds(m,c,d,n);f.type=Q,f.needsUpdate=!0;const g=4*u;for(let b=0;b<n;b++){const _=o[b],x=l[b],v=h[b],T=c*d*4*b;for(let S=0;S<_.count;S++){const w=S*g;!0===t&&(Bm.fromBufferAttribute(_,S),m[T+w+0]=Bm.x,m[T+w+1]=Bm.y,m[T+w+2]=Bm.z,m[T+w+3]=0),!0===s&&(Bm.fromBufferAttribute(x,S),m[T+w+4]=Bm.x,m[T+w+5]=Bm.y,m[T+w+6]=Bm.z,m[T+w+7]=0),!0===i&&(Bm.fromBufferAttribute(v,S),m[T+w+8]=Bm.x,m[T+w+9]=Bm.y,m[T+w+10]=Bm.z,m[T+w+11]=4===v.itemSize?Bm.w:1)}}function y(){f.dispose(),Pm.delete(e),e.removeEventListener("dispose",y)}a={count:n,texture:f,stride:u,size:new $t(c,d)},Pm.set(e,a),e.addEventListener("dispose",y)}return a}(t);!0===s&&nd.mulAssign(o),!0===i&&fd.mulAssign(o);const d=po(c.width);Rm(n,({i:t})=>{const r=co(0).toVar();e.count>1&&null!==e.morphTexture&&void 0!==e.morphTexture?r.assign(hc(e.morphTexture,yo(po(t).add(1),po(Lu))).r):r.assign(l.element(t).toVar()),ho(r.notEqual(0),()=>{!0===s&&nd.addAssign(Lm({bufferMap:h,influence:r,stride:u,width:d,depth:t,offset:po(0)})),!0===i&&fd.addAssign(Lm({bufferMap:h,influence:r,stride:u,width:d,depth:t,offset:po(1)}))})}),im(({object:e})=>{const{base:t,influences:s}=a;e.geometry.morphTargetsRelative?t.value=1:t.value=1-e.morphTargetInfluences.reduce((e,t)=>e+t,0),s&&(s.array=e.morphTargetInfluences,s.update())})},"void");class Om extends ha{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class Im extends Om{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class Um extends nu{static get type(){return"LightingContextNode"}constructor(e,t=null,s=[],i=null,r=null){super(e),this.lightingModel=t,this.materialLightings=s,this.backdropNode=i,this.backdropAlphaNode=r,this._value=null}getContext(){const{materialLightings:e,backdropNode:t,backdropAlphaNode:s}=this,i={directDiffuse:xo().toVar("directDiffuse"),directSpecular:xo().toVar("directSpecular"),indirectDiffuse:xo().toVar("indirectDiffuse"),indirectSpecular:xo().toVar("indirectSpecular")};return{radiance:xo().toVar("radiance"),irradiance:xo().toVar("irradiance"),iblIrradiance:xo().toVar("iblIrradiance"),ambientOcclusion:co(1).toVar("ambientOcclusion"),reflectedLight:i,materialLightings:e,backdrop:t,backdropAlpha:s}}setup(e){return this.value=this._value||(this._value=this.getContext()),this.value.lightingModel=this.lightingModel||e.context.lightingModel,super.setup(e)}}const km=to(Um);class zm extends Om{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}const Vm=new $t;class Gm extends ac{static get type(){return"ViewportTextureNode"}constructor(e=vc,t=null,s=null){let i=null;null===s?(i=new Dr,i.minFilter=j,s=i):i=s,super(s,e,t),this.generateMipmaps=!1,this.defaultFramebuffer=i,this.isOutputTextureNode=!0,this.updateBeforeType=Jn,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,s=t.getRenderTarget(),i=t.getCanvasTarget(),r=s||i;return this.value=this.getTextureForReference(r),this.value}updateBefore(e){const t=e.renderer,s=t.getRenderTarget(),i=t.getCanvasTarget(),r=s||i;null===r?t.getDrawingBufferSize(Vm):r.getDrawingBufferSize?r.getDrawingBufferSize(Vm):Vm.set(r.width,r.height);const n=this.getTextureForReference(r);n.image.width===Vm.width&&n.image.height===Vm.height||(n.image.width=Vm.width,n.image.height=Vm.height,n.needsUpdate=!0);const a=n.generateMipmaps;n.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(n),n.generateMipmaps=a}clone(){const e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}}const $m=to(Gm,null,null,{generateMipmaps:!0}).setParameterLength(0,3),jm=$m(),Wm=(e=vc,t=null)=>jm.sample(e,t);let Hm=null;class qm extends Gm{static get type(){return"ViewportDepthTextureNode"}constructor(e=vc,t=null,s=null){null===s&&(null===Hm&&(Hm=new Ir),s=Hm),super(e,t,s)}}const Xm=to(qm).setParameterLength(0,3);class Ym extends ha{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===Ym.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,s=this.valueNode;let i=null;if(t===Ym.DEPTH_BASE)null!==s&&(i=tf().assign(s));else if(t===Ym.DEPTH)i=e.isPerspectiveCamera?Zm(hd.z,kc,zc):Km(hd.z,kc,zc);else if(t===Ym.LINEAR_DEPTH)if(null!==s)if(e.isPerspectiveCamera){const e=Jm(s,kc,zc);i=Km(e,kc,zc)}else i=s;else i=Km(hd.z,kc,zc);return i}}Ym.DEPTH_BASE="depthBase",Ym.DEPTH="depth",Ym.LINEAR_DEPTH="linearDepth";const Km=(e,t,s)=>e.add(t).div(t.sub(s)),Qm=ao(([e,t,s],i)=>!0===i.renderer.reversedDepthBuffer?s.sub(t).mul(e).sub(s):t.sub(s).mul(e).sub(t)),Zm=(e,t,s)=>t.add(e).mul(s).div(s.sub(t).mul(e)),Jm=ao(([e,t,s],i)=>!0===i.renderer.reversedDepthBuffer?t.mul(s).div(t.sub(s).mul(e).sub(t)):t.mul(s).div(s.sub(t).mul(e).sub(s))),ef=(e,t,s)=>{t=t.max(1e-6).toVar();const i=nh(e.negate().div(t)),r=nh(s.div(t));return i.div(r)},tf=to(Ym,Ym.DEPTH_BASE),sf=so(Ym,Ym.DEPTH);Xm(),sf.assign=e=>tf(e);class rf extends ha{static get type(){return"ClippingNode"}constructor(e=rf.DEFAULT){super(),this.scope=e}setup(e){super.setup(e);const t=e.clippingContext,{intersectionPlanes:s,unionPlanes:i}=t;return this.hardwareClipping=e.hardwareClipping,this.scope===rf.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(s,i):this.scope===rf.HARDWARE?this.setupHardwareClipping(i,e):this.setupDefault(s,i)}setupAlphaToCoverage(e,t){return ao(()=>{const s=co().toVar("distanceToPlane"),i=co().toVar("distanceToGradient"),r=co(1).toVar("clipOpacity"),n=t.length;if(!1===this.hardwareClipping&&n>0){const e=mc(t).setGroup(ml);Rm(n,({i:t})=>{const n=e.element(t);s.assign(hd.dot(n.xyz).negate().add(n.w)),i.assign(s.fwidth().div(2)),r.mulAssign(eu(i.negate(),i,s))})}const a=e.length;if(a>0){const t=mc(e).setGroup(ml),n=co(1).toVar("intersectionClipOpacity");Rm(a,({i:e})=>{const r=t.element(e);s.assign(hd.dot(r.xyz).negate().add(r.w)),i.assign(s.fwidth().div(2)),n.mulAssign(eu(i.negate(),i,s).oneMinus())}),r.mulAssign(n.oneMinus())}Lo.a.mulAssign(r),Lo.a.equal(0).discard()})()}setupDefault(e,t){return ao(()=>{const s=t.length;if(!1===this.hardwareClipping&&s>0){const e=mc(t).setGroup(ml);Rm(s,({i:t})=>{const s=e.element(t);hd.dot(s.xyz).greaterThan(s.w).discard()})}const i=e.length;if(i>0){const t=mc(e).setGroup(ml),s=fo(!0).toVar("clipped");Rm(i,({i:e})=>{const i=t.element(e);s.assign(hd.dot(i.xyz).greaterThan(i.w).and(s))}),s.discard()}})()}setupHardwareClipping(e,t){const s=e.length;return t.enableHardwareClipping(s),ao(()=>{const i=mc(e).setGroup(ml),r=gc(t.getClipDistance());Rm(s,({i:e})=>{const t=i.element(e),s=hd.dot(t.xyz).sub(t.w).negate();r.element(e).assign(s)})})()}}rf.ALPHA_TO_COVERAGE="alphaToCoverage",rf.DEFAULT="default",rf.HARDWARE="hardware";const nf=ao(([e])=>ch(El(1e4,dh(El(17,e.x).add(El(.1,e.y)))).mul(wl(.1,wh(dh(El(13,e.y).add(e.x))))))),af=ao(([e])=>nf(go(nf(e.xy),e.z))),of=ao(([e])=>{const t=kh(Eh(Ch(e.xyz)),Eh(Rh(e.xyz))),s=co(1).div(co(.05).mul(t)).toVar("pixScale"),i=go(ih(lh(nh(s))),ih(hh(nh(s)))),r=go(af(lh(i.x.mul(e.xyz))),af(lh(i.y.mul(e.xyz)))),n=ch(nh(s)),a=wl(El(n.oneMinus(),r.x),El(n,r.y)),o=Uh(n,n.oneMinus()),l=xo(a.mul(a).div(El(2,o).mul(Ml(1,o))),a.sub(El(.5,o)).div(Ml(1,o)),Ml(1,Ml(1,a).mul(Ml(1,a)).div(El(2,o).mul(Ml(1,o))))),h=a.lessThan(o.oneMinus()).select(a.lessThan(o).select(l.x,l.y),l.z);return Qh(h,1e-6,1)}).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class lf extends Qu{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 us(1,1,1,1)),s}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}class hf extends rr{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.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.maskShadowNode=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}_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(kn(t.slice(0,-4)),s.getCacheKey());return this.type+zn(e)}build(e){this.setup(e)}setupObserver(e){return new Dn(e)}setup(e){e.context.setupNormal=()=>cu(this.setupNormal(e),"NORMAL","vec3"),e.context.setupPositionView=()=>this.setupPositionView(e),e.context.setupModelViewProjection=()=>this.setupModelViewProjection(e);const t=e.renderer,s=t.getRenderTarget();e.addStack();const i=this.setupVertex(e),r=cu(this.vertexNode||i,"VERTEX");let n;e.context.clipSpace=r,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 a=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.setupAmbientOcclusion(e),this.setupVariants(e);const i=this.setupLighting(e);null!==a&&e.stack.addToStack(a);const r=wo(i,Lo.a).max(0);n=this.setupOutput(e,r),el.assign(n);const o=null!==this.outputNode;if(o&&(n=this.outputNode),e.context.getOutput&&(n=e.context.getOutput(n,e)),null!==s){const e=t.getMRT(),s=this.mrtNode;null!==e?(o&&el.assign(n),n=e,null!==s&&(n=e.merge(s))):null!==s&&(n=s)}}else{let t=this.fragmentNode;!0!==t.isOutputStructNode&&(t=t.convert(e.getOutputType())),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 rf(rf.ALPHA_TO_COVERAGE):e.stack.addToStack(new rf)}return i}setupHardwareClipping(e){if(e.hardwareClipping=!1,null===e.clippingContext)return;const t=e.clippingContext.unionPlanes.length;t>0&&t<=8&&e.isAvailable("clipDistance")&&(e.stack.addToStack(new rf(rf.HARDWARE)),e.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?ef(hd.z,kc,zc):Km(hd.z,kc,zc))}null!==i&&sf.assign(i).toStack()}setupPositionView(){return Jc.mul(nd).xyz}setupModelViewProjection(){return Vc.mul(hd)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.position=e.removeStack(),em}setupPosition(e){const{object:t,geometry:s}=e;if((s.morphAttributes.position||s.morphAttributes.normal||s.morphAttributes.color)&&Dm(t),!0===t.isSkinnedMesh&&Nm(t),this.displacementMap){const e=kd("displacementMap","texture"),t=kd("displacementScale","float"),s=kd("displacementBias","float");nd.addAssign(fd.normalize().mul(e.x.mul(t).add(s)))}return t.isBatchedMesh&&Tm(t),t.isInstancedMesh&&t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&fm(t),null!==this.positionNode&&nd.assign(cu(this.positionNode,"POSITION","vec3")),nd}setupDiffuseColor(e){const{object:t,geometry:s}=e;null!==this.maskNode&&fo(this.maskNode).not().discard();let i=this.colorNode?wo(this.colorNode):gp;!0===this.vertexColors&&s.hasAttribute("color")&&(i=i.mul(((e=0)=>new lf(e))())),t.instanceColor&&(i=pm.mul(i)),t.isBatchedMesh&&t._colorsTexture&&(i=xm.mul(i)),Lo.assign(i);const r=this.opacityNode?co(this.opacityNode):_p;Lo.a.assign(Lo.a.mul(r));let n=null;(null!==this.alphaTestNode||this.alphaTest>0)&&(n=null!==this.alphaTestNode?co(this.alphaTestNode):fp,!0===this.alphaToCoverage?(Lo.a=eu(n,n.add(Lh(Lo.a)),Lo.a),Lo.a.lessThanEqual(0).discard()):Lo.a.lessThanEqual(n).discard()),!0===this.alphaHash&&Lo.a.lessThan(of(nd)).discard(),e.isOpaque()&&Lo.a.assign(1)}setupVariants(){}setupOutgoingLight(){return!0===this.lights?xo(0):Lo.rgb}setupNormal(){return this.normalNode?xo(this.normalNode):Ap}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?kd("envMap","cubeTexture"):kd("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new zm(Qp)),t}setupMaterialLightings(e){const t=[],s=this.setupEnvironment(e);s&&s.isLightingNode&&t.push(s);const i=this.setupLightMap(e);if(i&&i.isLightingNode&&t.push(i),e.context.ambientOcclusion&&t.push(new Im(e.context.ambientOcclusion)),e.context.getGI){const s=e.context.getGI(null,e);null!==s&&t.push(new zm(s))}return t}setupAmbientOcclusion(e){let t=this.aoNode;null===t&&e.material.aoMap&&(t=Zp),e.context.getAO&&(t=e.context.getAO(t,e)),null!==t&&(ul.assign(t),e.context.ambientOcclusion=ul)}setupLightingModel(){}setupLighting(e){const{material:t}=e,{backdropNode:s,backdropAlphaNode:i,emissiveNode:r}=this,n=!0===this.lights&&e.renderer.lighting.enabled,a=n||null!==this.lightsNode,o=n?this.setupMaterialLightings(e):[],l=a?this.lightsNode||e.lightsNode:null;let h=this.setupOutgoingLight(e);if(l&&(o.length>0||l.getScope().hasLights)){const t=this.setupLightingModel(e)||null;h=km(l,t,o,s,i)}else null!==s&&(h=xo(null!==i?Kh(h,s,i):s));return(r&&!0===r.isNode||t.emissive&&!0===t.emissive.isColor)&&(Oo.assign(xo(r||bp)),h=h.add(Oo)),h}setupFog(e,t){const s=e.fogNode;return s&&(el.assign(t),t=wo(s.toVar())),t}setupPremultipliedAlpha(e,t){return ju(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=rr.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){const t=Object.getOwnPropertyDescriptors(this.constructor.prototype);for(const s in t)if(void 0!==t[s].set&&void 0!==e[s]){const t=e[s];this[s]&&void 0!==this[s].copy?this[s].copy(t):this[s]=t}for(const t in this)if(!/^(?:is[A-Z]|_)|^(?:id|uuid|version|type|userData|clippingPlanes)$/.test(t)&&void 0!==this[t]&&void 0!==e[t]){const s=e[t];this[t]&&void 0!==this[t].copy?this[t].copy(s):this[t]=s}return this.clippingPlanes=e.clippingPlanes?e.clippingPlanes.map(e=>e.clone()):null,this.userData=JSON.parse(JSON.stringify(e.userData)),this}}const uf=new Fr;class cf extends hf{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(uf),this.setValues(e)}}const df=new Qr;class pf extends hf{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(df),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?co(this.offsetNode):qp,t=this.dashScaleNode?co(this.dashScaleNode):$p,s=this.dashSizeNode?co(this.dashSizeNode):jp,i=this.gapSizeNode?co(this.gapSizeNode):Wp;tl.assign(s),sl.assign(i);const r=pu(Zu("lineDistance").mul(t));(e?r.add(e):r).mod(tl.add(sl)).greaterThan(tl).discard()}}const mf=Fo("vec3","worldStart"),ff=Fo("vec3","worldEnd"),gf=Fo("float","lineDistance"),yf=Fo("vec4","worldPos"),bf=ao(({start:e,end:t})=>{const s=Vc.element(2).element(2),i=Vc.element(3).element(2);return s.greaterThan(0).select(i.negate().div(s.add(1)),i.mul(-.5).div(s)).sub(e.z).div(t.z.sub(e.z))},{start:"vec4",end:"vec4",return:"float"}),_f=ao(({p1:e,p2:t,p3:s,p4:i})=>{const r=e.sub(s),n=i.sub(s),a=t.sub(e),o=r.dot(n),l=n.dot(a),h=r.dot(a),u=n.dot(n),c=a.dot(a).mul(u).sub(l.mul(l)),d=o.mul(l).sub(h.mul(u)).div(c).clamp(),p=o.add(l.mul(d)).div(u).clamp();return go(d,p)},{p1:"vec3",p2:"vec3",p3:"vec3",p4:"vec3",return:"vec2"});ao(({material:e})=>{const t=e._useDash,s=e._useWorldUnits,i=Zu("instanceStart"),r=Zu("instanceEnd"),n=wo(Jc.mul(wo(i,1))).toVar("start"),a=wo(Jc.mul(wo(r,1))).toVar("end");let o,l;t&&(o=co(Zu("instanceDistanceStart")).toVar("distanceStart"),l=co(Zu("instanceDistanceEnd")).toVar("distanceEnd")),s&&(mf.assign(n.xyz),ff.assign(a.xyz));const h=wc.z.div(wc.w),u=Vc.element(2).element(3).equal(-1);if(ho(u,()=>{ho(n.z.lessThan(0).and(a.z.greaterThan(0)),()=>{const e=bf({start:n,end:a});a.assign(wo(Kh(n.xyz,a.xyz,e),a.w)),t&&l.assign(Kh(o,l,e))}).ElseIf(a.z.lessThan(0).and(n.z.greaterThanEqual(0)),()=>{const e=bf({start:a,end:n});n.assign(wo(Kh(a.xyz,n.xyz,e),n.w)),t&&o.assign(Kh(l,o,e))})}),t){const t=e.dashScaleNode?co(e.dashScaleNode):$p,s=e.offsetNode?co(e.offsetNode):qp;let i=rd.y.lessThan(.5).select(t.mul(o),t.mul(l));i=i.add(s),gf.assign(i)}const c=Vc.mul(n),d=Vc.mul(a),p=c.xyz.div(c.w),m=d.xyz.div(d.w),f=m.xy.sub(p.xy).toVar();f.x.assign(f.x.mul(h)),f.assign(f.normalize());const g=wo().toVar();if(s){const e=a.xyz.sub(n.xyz).normalize(),s=Kh(n.xyz,a.xyz,.5).normalize(),i=e.cross(s).normalize(),r=e.cross(i);yf.assign(rd.y.lessThan(.5).select(n,a));const o=Hp.mul(.5);yf.addAssign(wo(rd.x.lessThan(0).select(i.mul(o),i.mul(o).negate()),0)),t||(yf.addAssign(wo(rd.y.lessThan(.5).select(e.mul(o).negate(),e.mul(o)),0)),yf.addAssign(wo(r.mul(o),0)),ho(rd.y.greaterThan(1).or(rd.y.lessThan(0)),()=>{yf.subAssign(wo(r.mul(2).mul(o),0))})),g.assign(Vc.mul(yf));const l=xo().toVar();l.assign(rd.y.lessThan(.5).select(p,m)),g.z.assign(l.z.mul(g.w))}else{const e=go(f.y,f.x.negate()).toVar("offset");f.x.assign(f.x.div(h)),e.x.assign(e.x.div(h)),e.assign(rd.x.lessThan(0).select(e.negate(),e)),ho(rd.y.lessThan(0),()=>{e.assign(e.sub(f))}).ElseIf(rd.y.greaterThan(1),()=>{e.assign(e.add(f))}),e.assign(e.mul(Hp)),e.assign(e.div(wc.w.div(xc))),g.assign(rd.y.lessThan(.5).select(c,d)),e.assign(e.mul(g.w)),g.assign(g.add(wo(e,0,0)))}return g})(),ao(({material:e,renderer:t})=>{const s=e._useAlphaToCoverage,i=e._useDash,r=e._useWorldUnits,n=Ju();if(i){const t=e.dashSizeNode?co(e.dashSizeNode):jp,s=e.gapSizeNode?co(e.gapSizeNode):Wp;tl.assign(t),sl.assign(s),n.y.lessThan(-1).or(n.y.greaterThan(1)).discard(),gf.mod(tl.add(sl)).greaterThan(tl).discard()}const a=co(1).toVar("alpha");if(r){const e=yf.xyz.normalize().mul(1e5),r=ff.sub(mf),n=_f({p1:mf,p2:ff,p3:xo(0,0,0),p4:e}),o=mf.add(r.mul(n.x)),l=e.mul(n.y),h=o.sub(l).length().div(Hp);if(!i)if(s&&t.currentSamples>0){const e=h.fwidth();a.assign(eu(e.negate().add(.5),e.add(.5),h).oneMinus())}else h.greaterThan(.5).discard()}else if(s&&t.currentSamples>0){const e=n.x,t=n.y.greaterThan(0).select(n.y.sub(1),n.y.add(1)),s=e.mul(e).add(t.mul(t)),i=co(s.fwidth()).toVar("dlen");ho(n.y.abs().greaterThan(1),()=>{a.assign(eu(i.oneMinus(),i.add(1),s).oneMinus())})}else ho(n.y.abs().greaterThan(1),()=>{const e=n.x,t=n.y.greaterThan(0).select(n.y.sub(1),n.y.add(1));e.mul(e).add(t.mul(t)).greaterThan(1).discard()});return a})();const xf=new Xr;class vf extends hf{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(xf),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?co(this.opacityNode):_p;Lo.assign(bu(wo(Qa(_d).mul(.5).add(.5),e),Ze))}}const Tf=ao(([e=ld])=>{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 go(t,s)}),Sf=ao(([e=Ju()])=>{const t=e.x.sub(.5).mul(2*Math.PI),s=e.y.sub(.5).mul(Math.PI),i=s.cos(),r=i.mul(t.cos()),n=s.sin(),a=i.mul(t.sin());return xo(r,n,a)});class wf extends cs{constructor(e=1,t={}){super(e,e,t),this.isCubeRenderTarget=!0;const s={width:e,height:e,depth:1},i=[s,s,s,s,s,s];this.texture=new Or(i),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!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 kr(5,5,5),n=Tf(ld),a=new hf;a.colorNode=lc(t,n,0),a.side=1,a.blending=0;const o=new Sr(r,a),l=new Ks;l.add(o),t.minFilter===j&&(t.minFilter=G);const h=new Mn(1,10,this),u=e.getMRT();return e.setMRT(null),h.update(e,l),e.setMRT(u),t.minFilter=s,t.generateMipmaps=i,o.geometry.dispose(),o.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)}}const Mf=new WeakMap;class Ef extends da{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=Dd(null);const t=new Or;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=Jn}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(Mf.has(e)){const t=Mf.get(e);Nf(t,e.mapping),this._cubeTexture=t}else{const s=e.image;if(function(e){return null!=e&&e.height>0}(s)){const i=new wf(s.height);i.fromEquirectangularTexture(t,e),Nf(i.texture,e.mapping),this._cubeTexture=i.texture,Mf.set(e,i.texture),e.addEventListener("dispose",Af)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function Af(e){const t=e.target;t.removeEventListener("dispose",Af);const s=Mf.get(t);void 0!==s&&(Mf.delete(t),s.dispose())}function Nf(e,t){303===t?e.mapping=F:304===t&&(e.mapping=L)}const Cf=to(Ef).setParameterLength(1);class Rf extends Om{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=Cf(this.envNode)}}class Pf extends Om{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=co(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class Bf{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class Ff extends Bf{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,s=e.reflectedLight,i=e.irradianceLightMap;s.indirectDiffuse.assign(wo(0)),i?s.indirectDiffuse.addAssign(i):s.indirectDiffuse.addAssign(wo(1,1,1,0)),s.indirectDiffuse.mulAssign(t),s.indirectDiffuse.mulAssign(Lo.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(Kh(i.rgb,i.rgb.mul(r.rgb),Sp.mul(wp)));break;case 1:i.rgb.assign(Kh(i.rgb,r.rgb,Sp.mul(wp)));break;case 2:i.rgb.addAssign(r.rgb.mul(Sp.mul(wp)));break;default:Et("BasicLightingModel: Unsupported .combine value:",t.combine)}}}const Lf=new cr;class Df extends hf{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Lf),this.setValues(e)}setupNormal(){return pd(yd)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Rf(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new Pf(Qp)),t}setupOutgoingLight(){return Lo.rgb}setupLightingModel(){return new Ff}}const Of=ao(({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))}),If=ao(e=>e.diffuseColor.mul(1/Math.PI)),Uf=ao(({dotNH:e})=>Jo.mul(co(.5)).add(1).mul(co(1/Math.PI)).mul(e.pow(Jo))),kf=ao(({lightDirection:e})=>{const t=e.add(ud).normalize(),s=_d.dot(t).clamp(),i=ud.dot(t).clamp(),r=Of({f0:Ko,f90:1,dotVH:i}),n=co(.25),a=Uf({dotNH:s});return r.mul(n).mul(a)});class zf extends Ff{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const i=_d.dot(e).clamp().mul(t);s.directDiffuse.addAssign(i.mul(If({diffuseColor:Lo.rgb}))),!0===this.specular&&s.directSpecular.addAssign(i.mul(kf({lightDirection:e})).mul(Sp))}indirect(e){const{ambientOcclusion:t,irradiance:s,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(s.mul(If({diffuseColor:Lo}))),i.indirectDiffuse.mulAssign(t)}}const Vf=new Yr;class Gf extends hf{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Vf),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Rf(t):null}setupLightingModel(){return new zf(!1)}}const $f=new Hr;class jf extends hf{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues($f),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Rf(t):null}setupLightingModel(){return new zf}setupVariants(){const e=(this.shininessNode?co(this.shininessNode):yp).max(1e-4);Jo.assign(e);const t=this.specularNode||xp;Ko.assign(t)}}const Wf=ao(e=>{if(!1===e.geometry.hasAttribute("normal"))return co(0);const t=yd.dFdx().abs().max(yd.dFdy().abs());return t.x.max(t.y).max(t.z)}),Hf=ao(e=>{const{roughness:t}=e,s=Wf();let i=t.max(.0525);return i=i.add(s),i=i.min(1),i}),qf=ao(({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 Al(.5,r.add(n).max(Kl))}).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),Xf=ao(({alphaT:e,alphaB:t,dotTV:s,dotBV:i,dotTL:r,dotBL:n,dotNV:a,dotNL:o})=>{const l=o.mul(xo(e.mul(s),t.mul(i),a).length()),h=a.mul(xo(e.mul(r),t.mul(n),o).length());return Al(.5,l.add(h).max(Kl))}).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"}]}),Yf=ao(({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"}]}),Kf=co(1/Math.PI),Qf=ao(({alphaT:e,alphaB:t,dotNH:s,dotTH:i,dotBH:r})=>{const n=e.mul(t),a=xo(t.mul(i),e.mul(r),n.mul(s)),o=a.dot(a),l=n.div(o);return Kf.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"}]}),Zf=ao(({lightDirection:e,f0:t,f90:s,roughness:i,f:r,normalView:n=_d,viewDirection:a=ud,USE_IRIDESCENCE:o,USE_ANISOTROPY:l})=>{const h=i.pow2(),u=e.add(a).normalize(),c=n.dot(e).clamp(),d=n.dot(a).clamp(),p=n.dot(u).clamp(),m=a.dot(u).clamp();let f,g,y=Of({f0:t,f90:s,dotVH:m});if(Ya(o)&&(y=$o.mix(y,r)),Ya(l)){const t=Xo.dot(e),s=Xo.dot(a),i=Xo.dot(u),r=Yo.dot(e),n=Yo.dot(a),o=Yo.dot(u);f=Xf({alphaT:Ho,alphaB:h,dotTV:s,dotBV:n,dotTL:t,dotBL:r,dotNV:d,dotNL:c}),g=Qf({alphaT:Ho,alphaB:h,dotNH:p,dotTH:i,dotBH:o})}else f=qf({alpha:h,dotNL:c,dotNV:d}),g=Yf({alpha:h,dotNH:p});return y.mul(f).mul(g)}),Jf=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 eg=null;const tg=ao(({roughness:e,dotNV:t})=>{null===eg&&(eg=new Mr(Jf,16,16,ce,Z),eg.name="DFG_LUT",eg.minFilter=G,eg.magFilter=G,eg.wrapS=I,eg.wrapT=I,eg.generateMipmaps=!1,eg.needsUpdate=!0);const s=go(e,t);return lc(eg,s).rg}),sg=ao(e=>{const{dotNV:t,specularColor:s,specularF90:i,roughness:r}=e,n=tg({dotNV:t,roughness:r});return s.mul(n.x).add(i.mul(n.y))}),ig=ao(({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(xo(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"}]}),rg=ao(({roughness:e,dotNH:t})=>{const s=e.pow2(),i=co(1).div(s),r=t.pow2().oneMinus().max(.0078125);return co(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"}]}),ng=ao(({dotNV:e,dotNL:t})=>co(1).div(co(4).mul(t.add(e).sub(t.mul(e)))).clamp()).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),ag=ao(({lightDirection:e})=>{const t=e.add(ud).normalize(),s=_d.dot(e).clamp(),i=_d.dot(ud).clamp(),r=_d.dot(t).clamp(),n=rg({roughness:Go,dotNH:r}),a=ng({dotNV:i,dotNL:s});return Vo.mul(n).mul(a)}),og=ao(({N:e,V:t,roughness:s})=>{const i=e.dot(t).saturate(),r=go(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"}]}),lg=ao(({f:e})=>{const t=e.length();return kh(t.mul(t).add(e.z).div(t.add(1)),0)}).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),hg=ao(({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(),a=r.div(n),o=s.greaterThan(0).select(a,kh(s.mul(s).oneMinus(),1e-7).inverseSqrt().mul(.5).sub(a));return e.cross(t).mul(o)}).setLayout({name:"LTC_EdgeVectorFormFactor",type:"vec3",inputs:[{name:"v1",type:"vec3"},{name:"v2",type:"vec3"}]}),ug=ao(({N:e,V:t,P:s,mInv:i,p0:r,p1:n,p2:a,p3:o})=>{const l=n.sub(r).toVar(),h=o.sub(r).toVar(),u=l.cross(h),c=xo().toVar();return ho(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(Co(l,h,e).transpose()).toVar(),d=u.mul(r.sub(s)).normalize().toVar(),p=u.mul(n.sub(s)).normalize().toVar(),m=u.mul(a.sub(s)).normalize().toVar(),f=u.mul(o.sub(s)).normalize().toVar(),g=xo(0).toVar();g.addAssign(hg({v1:d,v2:p})),g.addAssign(hg({v1:p,v2:m})),g.addAssign(hg({v1:m,v2:f})),g.addAssign(hg({v1:f,v2:d})),c.assign(xo(lg({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"}]}),cg=1/6,dg=e=>El(cg,El(e,El(e,e.negate().add(3)).sub(3)).add(1)),pg=e=>El(cg,El(e,El(e,El(3,e).sub(6))).add(4)),mg=e=>El(cg,El(e,El(e,El(-3,e).add(3)).add(3)).add(1)),fg=e=>El(cg,Hh(e,3)),gg=e=>dg(e).add(pg(e)),yg=e=>mg(e).add(fg(e)),bg=e=>wl(-1,pg(e).div(dg(e).add(pg(e)))),_g=e=>wl(1,fg(e).div(mg(e).add(fg(e)))),xg=(e,t,s)=>{const i=e.uvNode,r=El(i,t.zw).add(.5),n=lh(r),a=ch(r),o=gg(a.x),l=yg(a.x),h=bg(a.x),u=_g(a.x),c=bg(a.y),d=_g(a.y),p=go(n.x.add(h),n.y.add(c)).sub(.5).mul(t.xy),m=go(n.x.add(u),n.y.add(c)).sub(.5).mul(t.xy),f=go(n.x.add(h),n.y.add(d)).sub(.5).mul(t.xy),g=go(n.x.add(u),n.y.add(d)).sub(.5).mul(t.xy),y=gg(a.y).mul(wl(o.mul(e.sample(p).level(s)),l.mul(e.sample(m).level(s)))),b=yg(a.y).mul(wl(o.mul(e.sample(f).level(s)),l.mul(e.sample(g).level(s))));return y.add(b)},vg=ao(([e,t])=>{const s=go(e.size(po(t))),i=go(e.size(po(t.add(1)))),r=Al(1,s),n=Al(1,i),a=xg(e,wo(r,s),lh(t)),o=xg(e,wo(n,i),hh(t));return ch(t).mix(a,o)}),Tg=ao(([e,t,s,i,r])=>{const n=xo(Jh(t.negate(),uh(e),Al(1,i))),a=xo(Eh(r[0].xyz),Eh(r[1].xyz),Eh(r[2].xyz));return uh(n).mul(s.mul(a))}).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"}]}),Sg=ao(([e,t])=>e.mul(Qh(t.mul(2).sub(2),0,1))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),wg=$m(),Mg=Wm(),Eg=ao(([e,t,s],{material:i})=>{const r=(1===i.side?wg:Mg).sample(e.mul(Hc.zw).add(Hc.xy).div(Tc)),n=nh(Hc.z).mul(Sg(t,s));return vg(r,n)}),Ag=ao(([e,t,s])=>(ho(s.notEqual(0),()=>{const i=rh(t).negate().div(s);return sh(i.negate().mul(e))}),xo(1))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),Ng=ao(([e,t,s,i,r,n,a,o,l,h,u,c,d,p,m])=>{let f,g;if(m){f=wo().toVar(),g=xo().toVar();const r=u.sub(1).mul(m.mul(.025)),n=xo(u.sub(r),u,u.add(r));Rm({start:0,end:3},({i:r})=>{const u=n.element(r),m=Tg(e,t,c,u,o),y=a.add(m),b=h.mul(l.mul(wo(y,1))),_=go(b.xy.div(b.w)).toVar();_.addAssign(1),_.divAssign(2),_.assign(go(_.x,_.y.oneMinus()));const x=Eg(_,s,u);f.element(r).assign(x.element(r)),f.a.addAssign(x.a),g.element(r).assign(i.element(r).mul(Ag(Eh(m),d,p).element(r)))}),f.a.divAssign(3)}else{const r=Tg(e,t,c,u,o),n=a.add(r),m=h.mul(l.mul(wo(n,1))),y=go(m.xy.div(m.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(go(y.x,y.y.oneMinus())),f=Eg(y,s,u),g=i.mul(Ag(Eh(r),d,p))}const y=g.rgb.mul(f.rgb),b=e.dot(t).clamp(),_=xo(sg({dotNV:b,specularColor:r,specularF90:n,roughness:s})),x=g.r.add(g.g,g.b).div(3);return wo(_.oneMinus().mul(y),f.a.oneMinus().mul(x).oneMinus())}),Cg=Co(3.2404542,-1.5371385,-.4985314,-.969266,1.8760108,.041556,.0556434,-.2040259,1.0572252),Rg=(e,t)=>e.sub(t).div(e.add(t)).pow2(),Pg=ao(({outsideIOR:e,eta2:t,cosTheta1:s,thinFilmThickness:i,baseF0:r})=>{const n=Kh(e,t,eu(0,.03,i)),a=e.div(n).pow2().mul(s.pow2().oneMinus()).oneMinus();ho(a.lessThan(0),()=>xo(1));const o=a.sqrt(),l=Rg(n,e),h=Of({f0:l,f90:1,dotVH:s}),u=h.oneMinus(),c=n.lessThan(e).select(Math.PI,0),d=co(Math.PI).sub(c),p=(e=>{const t=e.sqrt();return xo(1).add(t).div(xo(1).sub(t))})(r.clamp(0,.9999)),m=Rg(p,n.toVec3()),f=Of({f0:m,f90:1,dotVH:o}),g=xo(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,o,2),b=xo(d).add(g),_=h.mul(f).clamp(1e-5,.9999),x=_.sqrt(),v=u.pow2().mul(f).div(xo(1).sub(_)),T=h.add(v).toVar(),S=v.sub(u).toVar();return Rm({start:1,end:2,condition:"<=",name:"m"},({m:e})=>{S.mulAssign(x);const t=((e,t)=>{const s=e.mul(2*Math.PI*1e-9),i=xo(54856e-17,44201e-17,52481e-17),r=xo(1681e3,1795300,2208400),n=xo(43278e5,93046e5,66121e5),a=co(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(s.mul(2239900).add(t.x).cos()).mul(s.pow2().mul(-45282e5).exp());let o=i.mul(n.mul(2*Math.PI).sqrt()).mul(r.mul(s).add(t).cos()).mul(s.pow2().negate().mul(n).exp());return o=xo(o.x.add(a),o.y,o.z).div(1.0685e-7),Cg.mul(o)})(co(e).mul(y),co(e).mul(b)).mul(2);T.addAssign(S.mul(t))}),T.max(xo(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"}]}),Bg=ao(({normal:e,viewDir:t,roughness:s})=>{const i=e.dot(t).saturate(),r=s.mul(s),n=s.add(.1).reciprocal(),a=co(-1.9362).add(s.mul(1.0678)).add(r.mul(.4573)).sub(n.mul(.8469)),o=co(-.6014).add(s.mul(.5538)).sub(r.mul(.467)).sub(n.mul(.1255));return a.mul(i).add(o).exp().saturate()}),Fg=xo(.04),Lg=co(1);class Dg extends Bf{constructor(e=!1,t=!1,s=!1,i=!1,r=!1,n=!1,a=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=s,this.anisotropy=i,this.transmission=r,this.dispersion=n,this.retroreflection=a,this.clearcoatRadiance=null,this.clearcoatSpecularDirect=null,this.clearcoatSpecularIndirect=null,this.sheenSpecularDirect=null,this.sheenSpecularIndirect=null,this.iridescenceFresnel=null,this.iridescenceF0Dielectric=null,this.iridescenceF0Metallic=null,this.dfg=null,this.multiScatteringCompensation=null}start(e){if(!0===this.clearcoat&&(this.clearcoatRadiance=xo().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=xo().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=xo().toVar("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=xo().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=xo().toVar("sheenSpecularIndirect")),!0===this.iridescence){const e=_d.dot(ud).clamp(),t=Pg({outsideIOR:co(1),eta2:jo,cosTheta1:e,thinFilmThickness:Wo,baseF0:Ko}),s=Pg({outsideIOR:co(1),eta2:jo,cosTheta1:e,thinFilmThickness:Wo,baseF0:Lo.rgb});this.iridescenceFresnel=Kh(t,s,Uo),this.iridescenceF0Dielectric=ig({f:t,f90:1,dotVH:e}),this.iridescenceF0Metallic=ig({f:s,f90:1,dotVH:e})}if(!0===this.transmission){const t=od,s=Wc.sub(od).normalize(),i=xd,r=e.context;r.backdrop=Ng(i,s,Io,Do,Qo,Zo,t,Qc,$c,Vc,il,nl,ol,al,this.dispersion?ll:null),r.backdropAlpha=rl,Lo.a.mulAssign(Kh(1,r.backdrop.a,rl))}const t=_d.dot(ud).clamp();this.dfg=tg({roughness:Io,dotNV:t}).toConst("dfg");const s=this.dfg.x.add(this.dfg.y);this.multiScatteringCompensation=Qo.mul(s.reciprocal().sub(1)).add(1).toConst("multiScatteringCompensation"),super.start(e)}computeMultiscattering(e,t,s,i,r=null){const n=this.dfg,a=r?$o.mix(i,r):i,o=a.mul(n.x).add(s.mul(n.y)),l=n.x.add(n.y).oneMinus(),h=a.add(a.oneMinus().mul(.047619)),u=o.mul(h).div(l.mul(h).oneMinus());e.addAssign(o),t.addAssign(u.mul(l))}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const i=_d.dot(e).clamp().mul(t).toVar();if(!0===this.sheen){this.sheenSpecularDirect.addAssign(i.mul(ag({lightDirection:e})));const t=Bg({normal:_d,viewDir:ud,roughness:Go}),s=Bg({normal:_d,viewDir:e,roughness:Go}),r=Vo.r.max(Vo.g).max(Vo.b).mul(t.max(s)).oneMinus();i.mulAssign(r)}if(!0===this.clearcoat){const s=vd.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(s.mul(Zf({lightDirection:e,f0:Fg,f90:Lg,roughness:zo,normalView:vd})))}const r=e.add(ud).normalize(),n=ud.dot(r).clamp();let a=Of({f0:Ko,f90:Zo,dotVH:n}),o=Zf({lightDirection:e,f0:Qo,f90:1,roughness:Io,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy});if(!0===this.retroreflection){const t=ud.negate().reflect(_d),s=e.add(t).normalize(),i=t.dot(s).clamp(),r=Of({f0:Ko,f90:Zo,dotVH:i}),n=Zf({lightDirection:e,viewDirection:t,f0:Qo,f90:1,roughness:Io,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy});a=Kh(a,r,hl.clamp()),o=Kh(o,n,hl.clamp())}s.directDiffuse.addAssign(i.mul(If({diffuseColor:Do})).mul(a.oneMinus())),s.directSpecular.addAssign(i.mul(o).mul(this.multiScatteringCompensation))}directRectArea({lightColor:e,lightPosition:t,halfWidth:s,halfHeight:i,reflectedLight:r,ltc_1:n,ltc_2:a}){const o=t.add(s).sub(i),l=t.sub(s).sub(i),h=t.sub(s).add(i),u=t.add(s).add(i),c=_d,d=ud,p=hd.toVar(),m=og({N:c,V:d,roughness:Io}),f=n.sample(m).toVar(),g=a.sample(m).toVar(),y=Co(xo(f.x,0,f.y),xo(0,1,0),xo(f.z,0,f.w)).toVar(),b=Qo.mul(g.x).add(Zo.sub(Qo).mul(g.y)).toVar();if(r.directSpecular.addAssign(e.mul(b).mul(ug({N:c,V:d,P:p,mInv:y,p0:o,p1:l,p2:h,p3:u}))),r.directDiffuse.addAssign(e.mul(Do).mul(ug({N:c,V:d,P:p,mInv:Co(1,0,0,0,1,0,0,0,1),p0:o,p1:l,p2:h,p3:u}))),!0===this.clearcoat){const t=vd,s=og({N:t,V:d,roughness:zo}),i=n.sample(s),r=a.sample(s),c=Co(xo(i.x,0,i.y),xo(0,1,0),xo(i.z,0,i.w)),m=Fg.mul(r.x).add(Lg.sub(Fg).mul(r.y));this.clearcoatSpecularDirect.addAssign(e.mul(m).mul(ug({N:t,V:d,P:p,mInv:c,p0:o,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=xo().toVar(),r=xo().toVar();this.computeMultiscattering(i,r,Zo,Ko,this.iridescenceF0Dielectric);const n=t.mul(If({diffuseColor:Do})).mul(i.add(r).oneMinus()).toVar();if(!0===this.sheen){const e=Bg({normal:_d,viewDir:ud,roughness:Go});this.sheenSpecularIndirect.addAssign(t.mul(Vo,e,1/Math.PI));const s=Vo.r.max(Vo.g).max(Vo.b).mul(e).oneMinus();n.mulAssign(s)}s.indirectDiffuse.addAssign(n)}indirectSpecular(e){const{radiance:t,iblIrradiance:s,reflectedLight:i}=e.context;if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(s.mul(Vo,Bg({normal:_d,viewDir:ud,roughness:Go}),1/Math.PI)),!0===this.clearcoat){const e=vd.dot(ud).clamp(),t=sg({dotNV:e,specularColor:Fg,specularF90:Lg,roughness:zo});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const r=xo().toVar("singleScatteringDielectric"),n=xo().toVar("multiScatteringDielectric"),a=xo().toVar("singleScatteringMetallic"),o=xo().toVar("multiScatteringMetallic");this.computeMultiscattering(r,n,Zo,Ko,this.iridescenceF0Dielectric),this.computeMultiscattering(a,o,Zo,Lo.rgb,this.iridescenceF0Metallic);const l=Kh(r,a,Uo),h=Kh(n,o,Uo),u=r.add(n),c=Do.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=Bg({normal:_d,viewDir:ud,roughness:Go}),t=Vo.r.max(Vo.g).max(Vo.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=_d.dot(ud).clamp().add(t),r=Io.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=vd.dot(ud).clamp(),s=Of({dotVH:e,f0:Fg,f90:Lg}),i=t.mul(ko.mul(s).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(ko));t.assign(i)}if(!0===this.sheen){const e=t.add(this.sheenSpecularDirect,this.sheenSpecularIndirect);t.assign(e)}}}const Og=co(1),Ig=co(-2),Ug=co(.8),kg=co(-1),zg=co(.4),Vg=co(2),Gg=co(.305),$g=co(3),jg=co(.21),Wg=co(4),Hg=co(4),qg=co(16),Xg=ao(([e])=>{const t=xo(wh(e)).toVar(),s=co(-1).toVar();return ho(t.x.greaterThan(t.z),()=>{ho(t.x.greaterThan(t.y),()=>{s.assign(ru(e.x.greaterThan(0),0,3))}).Else(()=>{s.assign(ru(e.y.greaterThan(0),1,4))})}).Else(()=>{ho(t.z.greaterThan(t.y),()=>{s.assign(ru(e.z.greaterThan(0),2,5))}).Else(()=>{s.assign(ru(e.y.greaterThan(0),1,4))})}),s}).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),Yg=ao(([e,t])=>{const s=go().toVar();return ho(t.equal(0),()=>{s.assign(go(e.z,e.y).div(wh(e.x)))}).ElseIf(t.equal(1),()=>{s.assign(go(e.x.negate(),e.z.negate()).div(wh(e.y)))}).ElseIf(t.equal(2),()=>{s.assign(go(e.x.negate(),e.y).div(wh(e.z)))}).ElseIf(t.equal(3),()=>{s.assign(go(e.z.negate(),e.y).div(wh(e.x)))}).ElseIf(t.equal(4),()=>{s.assign(go(e.x.negate(),e.z).div(wh(e.y)))}).Else(()=>{s.assign(go(e.x,e.y).div(wh(e.z)))}),El(.5,s.add(1))}).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),Kg=ao(([e])=>{const t=co(0).toVar();return ho(e.greaterThanEqual(Ug),()=>{t.assign(Og.sub(e).mul(kg.sub(Ig)).div(Og.sub(Ug)).add(Ig))}).ElseIf(e.greaterThanEqual(zg),()=>{t.assign(Ug.sub(e).mul(Vg.sub(kg)).div(Ug.sub(zg)).add(kg))}).ElseIf(e.greaterThanEqual(Gg),()=>{t.assign(zg.sub(e).mul($g.sub(Vg)).div(zg.sub(Gg)).add(Vg))}).ElseIf(e.greaterThanEqual(jg),()=>{t.assign(Gg.sub(e).mul(Wg.sub($g)).div(Gg.sub(jg)).add($g))}).Else(()=>{t.assign(co(-2).mul(nh(El(1.16,e))))}),t}).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),Qg=ao(([e,t,s,i,r,n])=>{const a=co(s),o=xo(t),l=Qh(Kg(a),Ig,n),h=ch(l),u=lh(l),c=xo(Zg(e,o,u,i,r,n)).toVar();return ho(h.notEqual(0),()=>{const t=xo(Zg(e,o,u.add(1),i,r,n)).toVar();c.assign(Kh(c,t,h))}),c}),Zg=ao(([e,t,s,i,r,n])=>{const a=co(s).toVar(),o=xo(t),l=co(Xg(o)).toVar(),h=co(kh(Hg.sub(a),0)).toVar();a.assign(kh(a,Hg));const u=co(ih(a)).toVar(),c=go(Yg(o,l).mul(u.sub(2)).add(1)).toVar();return ho(l.greaterThan(2),()=>{c.y.addAssign(u),l.subAssign(3)}),c.x.addAssign(l.mul(u)),c.x.addAssign(h.mul(El(3,qg))),c.y.addAssign(El(4,ih(n).sub(u))),c.x.mulAssign(i),c.y.mulAssign(r),e.sample(c).grad(go(),go())}),Jg=ao(({SAMPLES:e,sigma:t,outputDirection:s,mipInt:i,envMap:r,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const l=xo(0).toVar();return ho(t.equal(0),()=>{l.assign(Zg(r,s,i,n,a,o))}).Else(()=>{const h=ru(wh(s.z).lessThan(.999),xo(0,0,1),xo(1,0,0)),u=uh(Wh(h,s)).toVar(),c=Wh(s,u).toVar(),d=Uh(t.mul(3),Math.PI),p=sh(d.mul(d).mul(-.5).div(t.mul(t))).oneMinus().toVar(),m=co(0).toVar();Rm({start:po(0),end:e},({i:h})=>{const d=co(h).add(.5).div(co(e)),f=t.mul(ah(rh(d.mul(p).oneMinus()).mul(-2))).toVar(),g=co(h).mul(2.399963229728653).toVar(),y=u.mul(mh(g)).add(c.mul(dh(g))),b=s.mul(mh(f)).add(y.mul(dh(f))),_=dh(f).div(f).toVar();l.addAssign(Zg(r,b,i,n,a,o).mul(_)),m.addAssign(_)}),l.divAssign(m)}),wo(l,1)}),ey=ao(([e])=>{const t=mo(e).toVar();return t.assign(t.shiftLeft(mo(16)).bitOr(t.shiftRight(mo(16)))),t.assign(t.bitAnd(mo(1431655765)).shiftLeft(mo(1)).bitOr(t.bitAnd(mo(2863311530)).shiftRight(mo(1)))),t.assign(t.bitAnd(mo(858993459)).shiftLeft(mo(2)).bitOr(t.bitAnd(mo(3435973836)).shiftRight(mo(2)))),t.assign(t.bitAnd(mo(252645135)).shiftLeft(mo(4)).bitOr(t.bitAnd(mo(4042322160)).shiftRight(mo(4)))),t.assign(t.bitAnd(mo(16711935)).shiftLeft(mo(8)).bitOr(t.bitAnd(mo(4278255360)).shiftRight(mo(8)))),co(t).mul(2.3283064365386963e-10)}),ty=ao(([e,t])=>go(co(e).div(co(t)),ey(e))),sy=ao(([e,t,s])=>{const i=s.mul(s).toConst(),r=xo(1,0,0).toConst(),n=Wh(t,r).toConst(),a=ah(e.x).toConst(),o=El(2,3.14159265359).mul(e.y).toConst(),l=a.mul(mh(o)).toConst(),h=a.mul(dh(o)).toVar(),u=El(.5,t.z.add(1)).toConst();h.assign(u.oneMinus().mul(ah(l.mul(l).oneMinus())).add(u.mul(h)));const c=r.mul(l).add(n.mul(h)).add(t.mul(ah(kh(0,l.mul(l).add(h.mul(h)).oneMinus()))));return uh(xo(i.mul(c.x),i.mul(c.y),kh(0,c.z)))}),iy=ao(({roughness:e,mipInt:t,envMap:s,N_immutable:i,GGX_SAMPLES:r,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const l=xo(i).toVar(),h=xo(0).toVar(),u=co(0).toVar();return ho(e.lessThan(.001),()=>{h.assign(Zg(s,l,t,n,a,o))}).Else(()=>{const i=ru(wh(l.z).lessThan(.999),xo(0,0,1),xo(1,0,0)),c=uh(Wh(i,l)).toVar(),d=Wh(l,c).toVar();Rm({start:mo(0),end:r},({i:i})=>{const p=ty(i,r),m=sy(p,xo(0,0,1),e),f=uh(c.mul(m.x).add(d.mul(m.y)).add(l.mul(m.z))),g=uh(f.mul(jh(l,f).mul(2)).sub(l)),y=kh(jh(l,g),0);ho(y.greaterThan(0),()=>{const e=Zg(s,g,t,n,a,o);h.addAssign(e.mul(y)),u.addAssign(y)})}),ho(u.greaterThan(0),()=>{h.assign(h.div(u))})}),wo(h,1)}),ry=new yn(-1,1,1,-1,0,1),ny=new dn(90,1),ay=new Xs;let oy=null,ly=0,hy=0;const uy=new Wt,cy=new Wt,dy=new WeakMap,py=[3,1,5,0,4,2],my=Zu("outputDirection").normalize();class fy{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],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:a=uy,renderTarget:o=null}=r;if(this._setSize(n),!1===this._hasInitialized)throw new Error('THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Use "await renderer.init();" before using this method.');oy=this._renderer.getRenderTarget(),ly=this._renderer.getActiveCubeFace(),hy=this._renderer.getActiveMipmapLevel();const l=o||this._allocateTarget(!0);return this._init(l),this._sceneToCubeUV(e,s,i,l,a),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 Nt('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)throw new Error('THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Use "await renderer.init();" before using this method.');return this._fromTexture(e,t)}async fromEquirectangularAsync(e,t=null){return Nt('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)throw new Error('THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Use "await renderer.init();" before using this method.');return this._fromTexture(e,t)}async fromCubemapAsync(e,t=null){return Nt('PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=by(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=_y(),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===F||e.mapping===L?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(oy,ly,hy),e.scissorTest=!1,this._setViewport(e,0,0,e.width,e.height)}_fromTexture(e,t){this._setSizeFromTexture(e),oy=this._renderer.getRenderTarget(),ly=this._renderer.getActiveCubeFace(),hy=this._renderer.getActiveMipmapLevel();const s=t||this._allocateTarget(!1);return this._init(s),this._textureToCubeUV(e,s),this._applyPMREM(s),this._cleanup(s),s}_allocateTarget(e){return gy(3*Math.max(this._cubeSize,112),4*this._cubeSize,e)}_init(e){if(null===this._pingPongRenderTarget||this._pingPongRenderTarget.width!==e.width||this._pingPongRenderTarget.height!==e.height){null!==this._pingPongRenderTarget&&this._dispose(),this._pingPongRenderTarget=gy(e.width,e.height);const{_lodMax:t}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods}=function(e){const t=[],s=[];let i=e;const r=e-4+1+6;for(let e=0;e<r;e++){const e=Math.pow(2,i);t.push(e);const r=1/(e-2),n=-r,a=1+r,o=[n,n,a,n,a,a,n,n,a,a,n,a],l=6,h=6,u=3,c=new Float32Array(u*h*l),d=new Float32Array(u*h*l);for(let e=0;e<l;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=py[e];c.set(i,u*h*r);for(let e=0;e<h;e++){const t=2*o[2*e]-1,s=2*o[2*e+1]-1;0===r?cy.set(1,s,t):1===r?cy.set(-t,1,-s):2===r?cy.set(-t,s,1):3===r?cy.set(-1,s,-t):4===r?cy.set(-t,-1,s):cy.set(t,s,-1),cy.toArray(d,(r*h+e)*u)}}const p=new Yi;p.setAttribute("position",new Fi(c,u)),p.setAttribute("outputDirection",new Fi(d,u)),s.push(new Sr(p,null)),i>4&&i--}return{lodMeshes:s,sizeLods:t}}(t)),this._blurMaterial=function(e,t,s){const i=lc(),r=yl(0),n=yl(0),a=co(1/t),o=co(1/s),l=co(e),h={envMap:i,sigma:r,mipInt:n,CUBEUV_TEXEL_WIDTH:a,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:l},u=yy("blur");return u.fragmentNode=Jg({...h,outputDirection:my,SAMPLES:po(20)}),dy.set(u,h),u}(t,e.width,e.height),this._ggxMaterial=function(e,t,s){const i=lc(),r=yl(0),n=yl(0),a=co(1/t),o=co(1/s),l=co(e),h={envMap:i,roughness:r,mipInt:n,CUBEUV_TEXEL_WIDTH:a,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:l},u=yy("ggx");return u.fragmentNode=iy({...h,N_immutable:my,GGX_SAMPLES:mo(256)}),dy.set(u,h),u}(t,e.width,e.height)}}async _compileMaterial(e){const t=new Sr(new Yi,e);await this._renderer.compile(t,ry)}_sceneToCubeUV(e,t,s,i,r){const n=ny;n.near=t,n.far=s;const a=[1,1,1,1,-1,1],o=[1,-1,1,-1,1,-1],l=this._renderer,h=l.autoClear;l.getClearColor(ay),l.autoClear=!1,null===this._backgroundBox&&(this._backgroundBox=new Sr(new kr,new cr({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(ay),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,a[t],0),n.position.set(r.x,r.y,r.z),n.lookAt(r.x+o[t],r.y,r.z)):1===s?(n.up.set(0,0,a[t]),n.position.set(r.x,r.y,r.z),n.lookAt(r.x,r.y+o[t],r.z)):(n.up.set(0,a[t],0),n.position.set(r.x,r.y,r.z),n.lookAt(r.x,r.y,r.z+o[t]));const h=this._cubeSize;this._setViewport(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===F||e.mapping===L;i?null===this._cubemapMaterial&&(this._cubemapMaterial=by(e)):null===this._equirectMaterial&&(this._equirectMaterial=_y(e));const r=i?this._cubemapMaterial:this._equirectMaterial;r.fragmentNode.value=e;const n=this._lodMeshes[0];n.material=r;const a=this._cubeSize;this._setViewport(t,0,0,3*a,2*a),s.setRenderTarget(t),s.render(n,ry)}_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,a=this._lodMeshes[s];a.material=n;const o=dy.get(n),l=s/(this._lodMeshes.length-1),h=t/(this._lodMeshes.length-1),u=Math.sqrt(l*l-h*h)*(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,o.envMap.value=e.texture,o.roughness.value=u,o.mipInt.value=c-t,this._setViewport(r,p,m,3*d,2*d),i.setRenderTarget(r),i.render(a,ry),r.texture.frame=(r.texture.frame||0)+1,o.envMap.value=r.texture,o.roughness.value=0,o.mipInt.value=c-s,this._setViewport(e,p,m,3*d,2*d),i.setRenderTarget(e),i.render(a,ry)}_blur(e,t,s,i){const r=this._pingPongRenderTarget,n=Math.min(i,Math.PI)/Math.SQRT2;this._blurPass(e,r,t,s,n),this._blurPass(r,e,s,s,n)}_blurPass(e,t,s,i,r){const n=this._renderer,a=this._blurMaterial,o=this._lodMeshes[i];o.material=a;const l=dy.get(a);e.texture.frame=(e.texture.frame||0)+1,l.envMap.value=e.texture,l.sigma.value=r,l.mipInt.value=this._lodMax-s;const h=this._sizeLods[i],u=3*h*(i>this._lodMax-4?i-this._lodMax+4:0),c=4*(this._cubeSize-h);this._setViewport(t,u,c,3*h,2*h),n.setRenderTarget(t),n.render(o,ry)}_setViewport(e,t,s,i,r){this._renderer.isWebGLRenderer?(e.viewport.set(t,e.height-r-s,i,r),e.scissor.set(t,e.height-r-s,i,r)):(e.viewport.set(t,s,i,r),e.scissor.set(t,s,i,r))}}function gy(e,t,s){const i=new cs(e,t,{magFilter:G,minFilter:G,generateMipmaps:!1,type:Z,format:ae,colorSpace:Je,depthBuffer:s});return i.texture.mapping=D,i.texture.name="PMREM.cubeUv",i.texture.isPMREMTexture=!0,i.scissorTest=!0,i}function yy(e){const t=new hf;return t.depthTest=!1,t.depthWrite=!1,t.blending=0,t.name=`PMREM_${e}`,t}function by(e){const t=yy("cubemap");return t.fragmentNode=Dd(e,my),t}function _y(e){const t=yy("equirect");return t.fragmentNode=lc(e,Tf(my),0),t}const xy=new WeakMap;function vy(e,t,s){const i=function(e){let t=xy.get(e);void 0===t&&(t=new WeakMap,xy.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)}if(r.pmremVersion=e.pmremVersion,!1===i.has(e)){const t=()=>{e.removeEventListener("dispose",t);const s=i.get(e);void 0!==s&&(s.dispose(),i.delete(e))};e.addEventListener("dispose",t)}i.set(e,r)}return r.texture}class Ty extends da{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 hs;i.isRenderTargetTexture=!0,this._texture=lc(i),this._width=yl(0),this._height=yl(0),this._maxMip=yl(0),this.updateBeforeType=Jn}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.mapping===D?i:vy(i,e.renderer,this._generator),null!==t&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){null===this._generator&&(this._generator=new fy(e.renderer)),this.updateBefore(e);let t=this.uvNode;null===t&&e.context.getUV&&(t=e.context.getUV(this,e)),t=null===this._pmrem||this._pmrem.isRenderTargetTexture?Ad.mul(xo(t.x,t.y.negate(),t.z)):Ad.mul(t);let s=this.levelNode;return null===s&&e.context.getTextureLevel&&(s=e.context.getTextureLevel(this)),Qg(this._texture,t,s,this._width,this._height,this._maxMip)}dispose(){super.dispose(),null!==this._generator&&this._generator.dispose()}}const Sy=to(Ty).setParameterLength(1,3),wy=new WeakMap;class My extends Om{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 i=s.isTextureNode?s.value:t[s.property],r=this._getPMREMNodeCache(e.renderer);let n=r.get(i);void 0===n&&(n=Sy(i),r.set(i,n)),s=n}const i=!0===t.useAnisotropy||t.anisotropy>0?np:_d;let r=ku(s.context(Ey(Io,i)).mul(Ed));if(!0===t.useRetroreflection||t.retroreflectivity>0){const e=ku(s.context(Ay(Io,i)).mul(Ed));r=hl.clamp().mix(r,e)}const n=s.context(Ny(xd)).mul(Math.PI).mul(Ed),a=ku(n);e.context.radiance.addAssign(r),e.context.iblIrradiance.addAssign(a);const o=e.context.lightingModel.clearcoatRadiance;if(o){const e=s.context(Ey(zo,vd)).mul(Ed),t=ku(e);o.addAssign(t)}}_getPMREMNodeCache(e){let t=wy.get(e);return void 0===t&&(t=new WeakMap,wy.set(e,t)),t}}const Ey=(e,t)=>{let s=null;return{getUV:()=>(null===s&&(s=ud.negate().reflect(t),s=Xh(e).mix(s,t).normalize(),s=s.transformDirection(jc)),s),getTextureLevel:()=>e}},Ay=(e,t)=>{let s=null;return{getUV:()=>(null===s&&(s=Xh(e).mix(ud,t).normalize(),s=s.transformDirection(jc)),s),getTextureLevel:()=>e}},Ny=e=>({getUV:()=>e,getTextureLevel:()=>co(1)}),Cy=new jr;class Ry extends hf{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(Cy),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return null===t&&e.environmentNode&&(t=e.environmentNode),t?new My(t):null}setupLightingModel(){return new Dg}setupSpecular(){const e=Kh(xo(.04),Lo.rgb,Uo);Ko.assign(xo(.04)),Qo.assign(e),Zo.assign(1)}setupVariants(){const e=this.metalnessNode?co(this.metalnessNode):Ep;Uo.assign(e);let t=this.roughnessNode?co(this.roughnessNode):Mp;t=Hf({roughness:t}),Io.assign(t),this.setupSpecular(),Do.assign(Lo.rgb.mul(e.oneMinus()))}}const Py=new Wr;class By extends Ry{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.retroreflectivityNode=null,this.anisotropyNode=null,this.setDefaultValues(Py),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}get useRetroreflection(){return this.retroreflectivity>0||null!==this.retroreflectivityNode}setupSpecular(){const e=this.iorNode?co(this.iorNode):zp,t=this.specularColorNode?xo(this.specularColorNode):Tp,s=this.specularIntensityNode?co(this.specularIntensityNode):vp;il.assign(e),Ko.assign(Uh(qh(il.sub(1).div(il.add(1))).mul(t),xo(1)).mul(s)),Qo.assign(Kh(Ko,Lo.rgb,Uo)),Zo.assign(Kh(s,1,Uo))}setupLightingModel(){return new Dg(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion,this.useRetroreflection)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?co(this.clearcoatNode):Np,t=this.clearcoatRoughnessNode?co(this.clearcoatRoughnessNode):Cp;ko.assign(e),zo.assign(Hf({roughness:t}))}if(this.useSheen){const e=this.sheenNode?xo(this.sheenNode):Bp,t=this.sheenRoughnessNode?co(this.sheenRoughnessNode):Fp;Vo.assign(e),Go.assign(t)}if(this.useRetroreflection){const e=this.retroreflectivityNode?co(this.retroreflectivityNode):Kp;hl.assign(e)}if(this.useIridescence){const e=this.iridescenceNode?co(this.iridescenceNode):Dp,t=this.iridescenceIORNode?co(this.iridescenceIORNode):Op,s=this.iridescenceThicknessNode?co(this.iridescenceThicknessNode):Ip;$o.assign(e),jo.assign(t),Wo.assign(s)}if(this.useAnisotropy){const e=(this.anisotropyNode?go(this.anisotropyNode):Lp).toVar();qo.assign(e.length()),ho(qo.equal(0),()=>{e.assign(go(1,0))}).Else(()=>{e.divAssign(go(qo)),qo.assign(qo.saturate())}),Ho.assign(qo.pow2().mix(Io.pow2(),1)),Xo.assign(rp[0].mul(e.x).add(rp[1].mul(e.y))),Yo.assign(rp[1].mul(e.x).sub(rp[0].mul(e.y)))}if(this.useTransmission){const e=this.transmissionNode?co(this.transmissionNode):Up,t=this.thicknessNode?co(this.thicknessNode):kp,s=this.attenuationDistanceNode?co(this.attenuationDistanceNode):Vp,i=this.attenuationColorNode?xo(this.attenuationColorNode):Gp;if(rl.assign(e),nl.assign(t),al.assign(s),ol.assign(i),this.useDispersion){const e=this.dispersionNode?co(this.dispersionNode):Yp;ll.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?xo(this.clearcoatNormalNode):Rp}setup(e){e.context.setupClearcoatNormal=()=>cu(this.setupClearcoatNormal(e),"NORMAL","vec3"),super.setup(e)}}const Fy=ao(({normal:e,lightDirection:t,builder:s})=>{const i=e.dot(t),r=go(i.mul(.5).add(.5),0);if(s.material.gradientMap){const e=kd("gradientMap","texture").context({getUV:()=>r});return xo(e.r)}{const e=r.fwidth().mul(.5);return Kh(xo(.7),xo(1),eu(co(.7).sub(e.x),co(.7).add(e.x),r.x))}});class Ly extends Bf{direct({lightDirection:e,lightColor:t,reflectedLight:s},i){const r=Fy({normal:_d,lightDirection:e,builder:i}).mul(t);s.directDiffuse.addAssign(r.mul(If({diffuseColor:Lo.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:s,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(s.mul(If({diffuseColor:Lo}))),i.indirectDiffuse.mulAssign(t)}}const Dy=new qr;class Oy extends hf{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Dy),this.setValues(e)}setupLightingModel(){return new Ly}}const Iy=ao(()=>{const e=xo(ud.z,0,ud.x.negate()).normalize(),t=ud.cross(e);return go(e.dot(_d),t.dot(_d)).mul(.495).add(.5)}).once(["NORMAL","VERTEX"])().toVar("matcapUV"),Uy=new Kr;class ky extends hf{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(Uy),this.setValues(e)}setupVariants(e){const t=Iy;let s;s=e.material.matcap?kd("matcap","texture").context({getUV:()=>t}):xo(Kh(.2,.8,t.y)),Lo.rgb.mulAssign(s.rgb)}}class zy extends da{static get type(){return"RotateNode"}constructor(e,t,s="XYZ"){super(),this.positionNode=e,this.rotationNode=t,this._order=s}customCacheKey(){return kn(this._order)}setOrder(e){return this._order=e,this}getOrder(){return this._order}generateNodeType(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 No(e,i,i.negate(),e).mul(s)}{const e=t,i=this._order,r={X:Ro(wo(1,0,0,0),wo(0,mh(e.x),dh(e.x),0),wo(0,dh(e.x).negate(),mh(e.x),0),wo(0,0,0,1)),Y:Ro(wo(mh(e.y),0,dh(e.y).negate(),0),wo(0,1,0,0),wo(dh(e.y),0,mh(e.y),0),wo(0,0,0,1)),Z:Ro(wo(mh(e.z),dh(e.z),0,0),wo(dh(e.z).negate(),mh(e.z),0,0),wo(0,0,1,0),wo(0,0,0,1))};return r[i.charAt(0)].mul(r[i.charAt(1)]).mul(r[i.charAt(2)]).mul(wo(s,1)).xyz}}serialize(e){super.serialize(e),e.order=this._order}deserialize(e){super.deserialize(e),this._order=e.order}}const Vy=to(zy).setParameterLength(2,3),Gy=new nr;class $y extends hf{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(Gy),this.setValues(e)}setupPositionView(e){const{object:t,camera:s}=e,{positionNode:i,rotationNode:r,scaleNode:n,sizeAttenuation:a}=this,o=Jc.mul(xo(i||0));let l=go(Qc[0].xyz.length(),Qc[1].xyz.length());null!==n&&(l=l.mul(go(n))),s.isPerspectiveCamera&&!1===a&&(l=l.mul(o.z.negate()));let h=rd.xy;if(t.center&&!0===t.center.isVector2){const e=((e,t,s)=>new xu(e,t,s))("center","vec2",t);h=h.sub(e.sub(.5))}h=h.mul(l);const u=co(r||Pp),c=Vy(h,u);return wo(o.xy.add(c),o.zw)}get sizeAttenuation(){return this._useSizeAttenuation}set sizeAttenuation(e){this._useSizeAttenuation!==e&&(this._useSizeAttenuation=e,this.needsUpdate=!0)}}const jy=new Lr,Wy=new $t;class Hy extends $y{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(jy),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return Jc.mul(xo(e||nd)).xyz}setupVertexSprite(e){const{material:t,camera:s}=e,{rotationNode:i,scaleNode:r,sizeNode:n,sizeAttenuation:a}=this;let o=super.setupVertex(e);if(!0!==t.isNodeMaterial)return o;let l=null!==n?go(n):Xp;l=l.mul(xc),s.isPerspectiveCamera&&!0===a&&(l=l.mul(qy.div(hd.z.negate()))),r&&r.isNode&&(l=l.mul(go(r)));let h=rd.xy;if(i&&i.isNode){const e=co(i);h=Vy(h,e)}return h=h.mul(l),h=h.div(Mc.div(2)),h=h.mul(o.w),o=o.add(wo(h,0,0)),o}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 qy=yl(1).setGroup(ml).onRenderUpdate(function({renderer:e}){const t=e.getSize(Wy);this.value=.5*t.y});class Xy extends Bf{constructor(){super(),this.shadowNode=co(1).toVar("shadowMask")}direct({lightNode:e}){null!==e.shadowNode&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){Lo.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(Lo.rgb)}}const Yy=new $r;class Ky extends hf{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(Yy),this.setValues(e)}setupLightingModel(){return new Xy}}Bo("vec3"),Bo("vec3"),Bo("vec3");class Qy{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),this.renderer._inspector.isRunning&&this.renderer._inspector.finish(),!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)};e()}stop(){this.renderer._inspector.isRunning&&this.renderer._inspector.finish(),null!==this._context&&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 Zy{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 Jy=0;const eb=new WeakMap;class tb{constructor(e,t,s,i,r,n,a,o,l,h){this.id=Jy++,this._nodes=e,this._geometries=t,this.renderer=s,this.object=i,this.material=r,this.scene=n,this.camera=a,this.lightsNode=o,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._sourceMaterial=s._currentSourceMaterial,this.onDispose=null,this.isRenderObject=!0,this.onMaterialDispose=()=>{this.dispose()},this.onGeometryDispose=()=>{this.attributes=null,this.attributesId=null},this.onObjectDispose=()=>{this.dispose()},this.object.addEventListener("dispose",this.onObjectDispose),this.material.addEventListener("dispose",this.onMaterialDispose),this.geometry.addEventListener("dispose",this.onGeometryDispose),null!==this._sourceMaterial&&this._sourceMaterial.addEventListener("dispose",this.onMaterialDispose)}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.getNodeBuilderState().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),void 0!==e&&(e.isInterleavedBufferAttribute?r[n.name]=e.data.uuid:r[n.name]=e.id)),void 0===e)continue;s.push(e);const a=e.isInterleavedBufferAttribute?e.data:e;i.add(a)}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}),a=this.getIndex(),o=null!==a;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;o?p=a.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=eb.get(e.constructor);if(void 0===s){s=[];let t=Object.getPrototypeOf(e);for(;t;){const e=Object.getOwnPropertyDescriptors(t);for(const t in e){const i=e[t];i&&"function"==typeof i.get&&s.push(t)}t=Object.getPrototypeOf(t)}eb.set(e.constructor,s)}for(let e=0;e<s.length;e++)t.push(s[e]);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 t=typeof r;"number"===t?n="side"===e?String(r):0!==r?"1":"0":"object"===t?(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)&&(i+=e.uuid+","),i+=this.context.id+",",i+=e.receiveShadow+",",kn(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)return!0;const i=s.isInterleavedBufferAttribute?s.data.uuid:s.id;if(e[t]!==i)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=Vn(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=Vn(e,1)),e=Vn(e,this.renderer.contextNode.id,this.renderer.contextNode.version),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.object.removeEventListener("dispose",this.onObjectDispose),this.material.removeEventListener("dispose",this.onMaterialDispose),this.geometry.removeEventListener("dispose",this.onGeometryDispose),null!==this._sourceMaterial&&this._sourceMaterial.removeEventListener("dispose",this.onMaterialDispose),this.onDispose()}}const sb=[];class ib{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={},this._renderObjects=new Set}get(e,t,s,i,r,n,a,o){const l=this.getChainMap(o);sb[0]=e,sb[1]=t,sb[2]=n,sb[3]=r;let h=l.get(sb);return void 0===h?(h=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,s,i,r,n,a,o),l.set(sb,h)):(h.camera=i,h.updateClipping(a),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,a,o)):h.version=t.version)),sb[0]=null,sb[1]=null,sb[2]=null,sb[3]=null,h}getChainMap(e="default"){return this._chainMaps[e]||(this._chainMaps[e]=new Zy)}dispose(){for(const e of this._renderObjects)e.dispose();this._renderObjects.clear(),this._chainMaps={}}createRenderObject(e,t,s,i,r,n,a,o,l,h,u){const c=this.getChainMap(u),d=new tb(e,t,s,i,r,n,a,o,l,h);return d.onDispose=()=>{this.pipelines.delete(d),this.bindings.deleteForRender(d),this.nodes.delete(d),c.delete(d.getChainArray()),this._renderObjects.delete(d)},this._renderObjects.add(d),d}}class rb{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 nb=1,ab=2,ob=3,lb=4,hb=16;class ub extends rb{constructor(e,t){super(),this.backend=e,this.info=t}delete(e){const t=super.delete(e);return null!==t&&(this.backend.destroyAttribute(e),this.info.destroyAttribute(e)),t}update(e,t){const s=this.get(e);if(void 0===s.version)t===nb?(this.backend.createAttribute(e),this.info.createAttribute(e)):t===ab?(this.backend.createIndexAttribute(e),this.info.createIndexAttribute(e)):t===ob?(this.backend.createStorageAttribute(e),this.info.createStorageAttribute(e)):t===lb&&(this.backend.createIndirectStorageAttribute(e),this.info.createIndirectStorageAttribute(e)),s.version=this._getBufferAttribute(e).version;else{const t=this._getBufferAttribute(e);(s.version<t.version||t.usage===dt)&&(this.backend.updateAttribute(e),s.version=t.version)}}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}function cb(e){return null!==e.index?e.index.version:e.attributes.position.version}function db(e){return null!==e.index?e.index.id:e.attributes.position.id}function pb(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(i.count>=65535?Di:Li)(t,1);return r.version=cb(e),r.__id=db(e),r}class mb extends rb{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;null!==i&&this.attributes.delete(i);for(const e of Object.values(t.attributes))this.attributes.delete(e);const r=this.wireframes.get(t);void 0!==r&&this.attributes.delete(r);const n=new Set(Object.values(e.geometry.attributes));for(const t of e.getAttributes())!1===n.has(t)&&this.attributes.delete(t);t.removeEventListener("dispose",s),this._geometryDisposeListeners.delete(t),this.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,ob):this.updateAttribute(e,nb);const s=this.getIndex(e);null!==s&&this.updateAttribute(s,ab);const i=e.geometry.indirect;null!==i&&this.updateAttribute(i,lb)}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=pb(t),e.set(t,s)):s.version===cb(t)&&s.__id===db(t)||(this.attributes.delete(s),s=pb(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 fb{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={attributes:0,attributesSize:0,geometries:0,indexAttributes:0,indexAttributesSize:0,indirectStorageAttributes:0,indirectStorageAttributesSize:0,programs:0,programsSize:0,readbackBuffers:0,readbackBuffersSize:0,renderTargets:0,storageAttributes:0,storageAttributesSize:0,textures:0,texturesSize:0,uniformBuffers:0,uniformBuffersSize:0,total:0},this.memoryMap=new WeakMap}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):At("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;for(const e in this.memory)this.memory[e]=0;this.memoryMap=new WeakMap}createTexture(e){const t=this._getTextureMemorySize(e);this.memoryMap.set(e,t),this.memory.textures++,this.memory.total+=t,this.memory.texturesSize+=t}destroyTexture(e){const t=this.memoryMap.get(e)||0;this.memoryMap.delete(e),this.memory.textures--,this.memory.total-=t,this.memory.texturesSize-=t}_createAttribute(e,t){const s=this._getAttributeMemorySize(e);this.memoryMap.set(e,{size:s,type:t}),this.memory[t]++,this.memory.total+=s,this.memory[t+"Size"]+=s}createAttribute(e){this._createAttribute(e,"attributes")}createIndexAttribute(e){this._createAttribute(e,"indexAttributes")}createStorageAttribute(e){this._createAttribute(e,"storageAttributes")}createIndirectStorageAttribute(e){this._createAttribute(e,"indirectStorageAttributes")}destroyAttribute(e){const t=this.memoryMap.get(e);t&&(this.memoryMap.delete(e),this.memory[t.type]--,this.memory.total-=t.size,this.memory[t.type+"Size"]-=t.size)}createReadbackBuffer(e){const t=e.maxByteLength;this.memoryMap.set(e,{size:t,type:"readbackBuffers"}),this.memory.readbackBuffers++,this.memory.total+=t,this.memory.readbackBuffersSize+=t}destroyReadbackBuffer(e){const{size:t}=this.memoryMap.get(e);this.memoryMap.delete(e),this.memory.readbackBuffers--,this.memory.total-=t,this.memory.readbackBuffersSize-=t}createUniformBuffer(e){const t=e.byteLength;this.memoryMap.set(e,{size:t,type:"uniformBuffers"}),this.memory.uniformBuffers++,this.memory.total+=t,this.memory.uniformBuffersSize+=t}destroyUniformBuffer(e){const t=this.memoryMap.get(e);t&&(this.memoryMap.delete(e),this.memory.uniformBuffers--,this.memory.total-=t.size,this.memory.uniformBuffersSize-=t.size)}createProgram(e){const t=e.code.length;this.memoryMap.set(e,t),this.memory.programs++,this.memory.total+=t,this.memory.programsSize+=t}destroyProgram(e){const t=this.memoryMap.get(e)||0;this.memoryMap.delete(e),this.memory.programs--,this.memory.total-=t,this.memory.programsSize-=t}_getTextureMemorySize(e){if(e.isCompressedTexture)return 1;let t=1;e.type===H||e.type===W?t=1:e.type===q||e.type===X||e.type===Z?t=2:e.type!==Y&&e.type!==K&&e.type!==Q||(t=4);let s=4;e.format===re||e.format===he||e.format===ue||e.format===oe||e.format===le?s=1:e.format===ce||e.format===de?s=2:e.format!==ne&&e.format!==pe||(s=3);let i=t*s;e.type===J||e.type===ee?i=2:e.type!==te&&e.type!==se&&e.type!==ie||(i=4);const r=e.width||1,n=e.height||1,a=e.isCubeTexture?6:e.depth||1;let o=r*n*a*i;const l=e.mipmaps;if(l&&l.length>0){let e=0;for(let t=0;t<l.length;t++){const s=l[t];if(s.data)e+=s.data.byteLength;else{e+=(s.width||Math.max(1,r>>t))*(s.height||Math.max(1,n>>t))*a*i}}o+=e}else e.generateMipmaps&&(o*=1.333);return Math.round(o)}_getAttributeMemorySize(e){return e.isInterleavedBufferAttribute&&(e=e.data),e.array?e.array.byteLength:e.count&&e.itemSize?e.count*e.itemSize*4:0}}class gb{constructor(e){this.cacheKey=e,this.usedTimes=0}}class yb extends gb{constructor(e,t,s){super(e),this.vertexProgram=t,this.fragmentProgram=s}}class bb extends gb{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let _b=0;class xb{constructor(e,t,s,i=null,r=null){this.id=_b++,this.code=e,this.stage=t,this.name=s,this.transforms=i,this.attributes=r,this.usedTimes=0}}class vb extends rb{constructor(e,t,s){super(),this.backend=e,this.nodes=t,this.info=s,this.bindings=null,this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}getForCompute(e,t,s=null){const{backend:i}=this,r=this.get(e);if(this._needsComputeUpdate(e)){const n=r.pipeline;n&&(n.usedTimes--,n.computeProgram.usedTimes--);const a=this.nodes.getForCompute(e);let o=this.programs.compute.get(a.computeShader);void 0===o&&(n&&0===n.computeProgram.usedTimes&&this._releaseProgram(n.computeProgram),o=new xb(a.computeShader,"compute",e.name,a.transforms,a.nodeAttributes),this.programs.compute.set(a.computeShader,o),i.createProgram(o),this.info.createProgram(o));const l=this._getComputeCacheKey(e,o);let h=this.caches.get(l);void 0===h&&(n&&0===n.usedTimes&&this._releasePipeline(n),h=this._getComputePipeline(e,o,l,t,s)),h.usedTimes++,o.usedTimes++,r.version=e.version,r.pipeline=h}return r.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(),a=e.material?e.material.name:"";let o=this.programs.vertex.get(n.vertexShader);void 0===o&&(r&&0===r.vertexProgram.usedTimes&&this._releaseProgram(r.vertexProgram),o=new xb(n.vertexShader,"vertex",a),this.programs.vertex.set(n.vertexShader,o),s.createProgram(o),this.info.createProgram(o));let l=this.programs.fragment.get(n.fragmentShader);void 0===l&&(r&&0===r.fragmentProgram.usedTimes&&this._releaseProgram(r.fragmentProgram),l=new xb(n.fragmentShader,"fragment",a),this.programs.fragment.set(n.fragmentShader,l),s.createProgram(l),this.info.createProgram(l));const h=this._getRenderCacheKey(e,o,l);let u=this.caches.get(h);void 0===u?(r&&0===r.usedTimes&&this._releasePipeline(r),u=this._getRenderPipeline(e,o,l,h,t)):e.pipeline=u,u.usedTimes++,o.usedTimes++,l.usedTimes++,i.pipeline=u}return i.pipeline}isReady(e){const t=this.get(e).pipeline;if(void 0===t)return!1;const s=this.backend.get(t);return void 0!==s.pipeline&&null!==s.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,r){s=s||this._getComputeCacheKey(e,t);let n=this.caches.get(s);return void 0===n&&(n=new bb(s,t),this.caches.set(s,n),this.backend.createComputePipeline(n,i,r)),n}_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 yb(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),this.info.destroyProgram(e)}_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 Tb extends rb{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(),s=this.get(e);return!0!==s.initialized&&(this._createBindings(t),s.initialized=!0),t}getForCompute(e){const t=this.nodes.getForCompute(e).bindings,s=this.get(e);return!0===s.initialized&&s.bindings===t||(void 0!==s.bindings&&this._destroyBindings(s.bindings),this._createBindings(t),s.initialized=!0,s.bindings=t),t}updateForCompute(e){this._updateBindings(this.getForCompute(e))}updateForRender(e){this._updateBindings(this.getForRender(e))}updateSharedForRender(e){const t=this.getForRender(e);for(const e of t)for(const t of e.bindings)if((!0===t.isNodeUniformsGroup||!0===t.isNodeUniformBuffer)&&!0===t.groupNode.shared){if(!1===this.nodes.updateGroup(t))continue;t.update()&&this.backend.updateBinding(t),t.updateRanges.length>0&&t.clearUpdateRanges()}}deleteForCompute(e){const t=this.get(e).bindings||this.nodes.getForCompute(e).bindings;this._destroyBindings(t),this.delete(e)}deleteForRender(e){const t=e.getBindings();this._destroyBindings(t),this.delete(e)}_createBindings(e){for(const t of e){const s=this.get(t);if(void 0===s.bindGroup){for(const e of t.bindings)if(e.isUniformBuffer)this.backend.createUniformBuffer(e),this.info.createUniformBuffer(e);else if(e.isSampledTexture)this.textures.updateTexture(e.texture);else if(e.isSampler)this.textures.updateSampler(e);else if(e.isStorageBuffer){const t=e.attribute,s=t.isIndirectStorageBufferAttribute?lb:ob;this.attributes.update(t,s)}this.backend.createBindings(t,e,""),s.bindGroup=t,s.usedTimes=1}else s.usedTimes++}}_destroyBindings(e){for(const t of e){const e=this.get(t);if(e.usedTimes--,0===e.usedTimes){for(const e of t.bindings)if(e.isUniformBuffer)this.backend.destroyUniformBuffer(e),this.info.destroyUniformBuffer(e),e.release();else if(e.isSampler){if(!0!==e.isSampledTexture)this.backend.destroySampler(e);else if(null!==e.texture){const s=this.textures.get(e.texture);void 0!==s.bindGroups&&s.bindGroups.delete(t)}e.release()}this.backend.deleteBindGroupData(t),this.delete(t)}}}_updateBindings(e){for(const t of e)this._update(t,e)}_update(e,t){const{backend:s}=this;let i=!1,r=!0,n="",a=0;for(const t of e.bindings){if(!1!==this.nodes.updateGroup(t)){if(t.isStorageBuffer){const e=t.attribute,r=e.isIndirectStorageBufferAttribute?lb:ob,a=s.get(t);this.attributes.update(e,r),a.attribute!==e&&(a.attribute=e,i=!0),n+=e.id+","}if(t.isUniformBuffer){t.update()&&s.updateBinding(t)}else if(t.isSampledTexture){const o=t.update(),l=t.texture,h=this.textures.get(l);o&&(this.textures.updateTexture(l),t.generation!==h.generation&&(t.generation=h.generation,i=!0),h.bindGroups.add(e));if(void 0!==s.get(l).externalTexture||h.isDefaultTexture?r=!1:(n+=l.id+",",a+=l.version),!0===l.isStorageTexture&&!0===l.mipmapsAutoUpdate){const e=this.get(l);!0===t.store?e.needsMipmap=!0:this.textures.needsMipmaps(l)&&!0===e.needsMipmap&&(this.backend.generateMipmaps(l),e.needsMipmap=!1)}}else if(t.isSampler){if(t.update()){const e=this.textures.updateSampler(t);t.samplerKey!==e&&(t.samplerKey=e,i=!0)}}t.isBuffer&&t.updateRanges.length>0&&t.clearUpdateRanges()}}!0===i&&this.backend.updateBindings(e,t,r?n:"",a)}}const Sb=Object.freeze([]);function wb(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 Mb(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 Eb(e){return(e.transmission>0||e.transmissionNode&&e.transmissionNode.isNode)&&2===e.side&&!1===e.forceSinglePass}class Ab{constructor(e,t,s){this.renderItems=[],this.renderItemsIndex=0,this.opaque=[],this.transparentDoublePass=[],this.transparent=[],this.bundles=[],this.lighting=e,this.lightsNode=e.getNode(t),this.lightsArray=[],this.scene=t,this.camera=s,this.occlusionQueryCount=0,this.frameId=-1,this._lastOcclusionObject=null}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,a){let o=this.renderItems[this.renderItemsIndex];return void 0===o?(o={id:e.id,object:e,geometry:t,material:s,groupOrder:i,renderOrder:e.renderOrder,z:r,group:n,clippingContext:a},this.renderItems[this.renderItemsIndex]=o):(o.id=e.id,o.object=e,o.geometry=t,o.material=s,o.groupOrder=i,o.renderOrder=e.renderOrder,o.z=r,o.group=n,o.clippingContext=a),this.renderItemsIndex++,o}push(e,t,s,i,r,n,a){!0===this.camera.reversedDepth&&(r=-r);const o=this.getNextRenderItem(e,t,s,i,r,n,a);!0===e.occlusionTest&&this._lastOcclusionObject!==e&&(this.occlusionQueryCount++,this._lastOcclusionObject=e),!0===s.transparent||s.transmission>0||s.transmissionNode&&s.transmissionNode.isNode||s.backdropNode&&s.backdropNode.isNode?(Eb(s)&&this.transparentDoublePass.push(o),this.transparent.push(o)):this.opaque.push(o)}unshift(e,t,s,i,r,n,a){const o=this.getNextRenderItem(e,t,s,i,r,n,a);!0===s.transparent||s.transmission>0||s.transmissionNode&&s.transmissionNode.isNode||s.backdropNode&&s.backdropNode.isNode?(Eb(s)&&this.transparentDoublePass.unshift(o),this.transparent.unshift(o)):this.opaque.unshift(o)}pushBundle(e){this.bundles.push(e)}pushLight(e){this.lightsArray.push(e)}sort(e,t){this.opaque.length>1&&this.opaque.sort(e||wb),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||Mb),this.transparent.length>1&&this.transparent.sort(t||Mb)}finish(){this.lightsNode.setLights(this.lighting.enabled?this.lightsArray:Sb);for(let e=this.renderItemsIndex,t=this.renderItems.length;e<t;e++){const t=this.renderItems[e];if(null===t.id)break;Nb(t)}this._lastOcclusionObject=null}clear(){for(let e=0,t=this.renderItems.length;e<t;e++){const t=this.renderItems[e];if(null===t.id)break;Nb(t)}this.opaque.length=0,this.transparentDoublePass.length=0,this.transparent.length=0,this.bundles.length=0}}function Nb(e){e.id=null,e.object=null,e.geometry=null,e.material=null,e.groupOrder=null,e.renderOrder=null,e.z=null,e.group=null,e.clippingContext=null}const Cb=[];class Rb{constructor(){this.lists=new Zy,this._activeLists=new Set,this._frameId=-1}get(e,t,s){const i=this.lists;Cb[0]=e,Cb[1]=t,Cb[2]=s;let r=i.get(Cb);return void 0===r&&(r=new Ab(s,e,t),i.set(Cb,r)),Cb[0]=null,Cb[1]=null,Cb[2]=null,r.frameId=this._frameId,this._activeLists.add(r),r}update(e){if(e!==this._frameId){this._frameId=e;for(const t of this._activeLists)e-t.frameId>10&&(t.clear(),this._activeLists.delete(t))}}dispose(){this.lists=new Zy,this._activeLists.clear(),this._frameId=-1}}let Pb=0;class Bb{constructor(){this.id=Pb++,this.mrt=null,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 us,this.scissor=!1,this.scissorValue=new us,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.camera=null,this.fullscreenPass=!1,this.isRenderContext=!0}getCacheKey(){return Fb(this)}}function Fb(e){const{textures:t,activeCubeFace:s,activeMipmapLevel:i}=e,r=[s,i];for(const e of t)r.push(e.id);return zn(r)}class Lb{constructor(e){this.renderer=e,this._renderContexts={}}get(e=null,t=null,s=0){let i;if(null===e)i="default";else{const t=e.texture.format,s=e.texture.type;i=`${e.textures.length}:${t}:${s}:${e.samples}:${e.depthBuffer}:${e.stencilBuffer}`}const r=i+"-"+(null!==t?t.id:"default")+"-"+s;let n=this._renderContexts[r];return void 0===n&&(n=new Bb,n.mrt=t,this._renderContexts[r]=n),null!==e&&(n.sampleCount=0===e.samples?1:e.samples),n.clearDepthValue=this.renderer.getClearDepth(),n.clearStencilValue=this.renderer.getClearStencil(),n}dispose(){this._renderContexts={}}}const Db=new Wt;class Ob extends rb{constructor(e,t,s){super(),this.renderer=e,this.backend=t,this.info=s,this._htmlTextures=new Set}updateRenderTarget(e,t=0){const s=this.get(e),i=0===e.samples?1:e.samples,r=s.depthTextureMips||(s.depthTextureMips={}),n=e.textures,a=this.getSize(n[0]),o=a.width>>t,l=a.height>>t;let h=e.depthTexture||r[t];const u=!0===e.depthBuffer||!0===e.stencilBuffer;let c=!1;const d=void 0!==h&&void 0!==h.image&&h.image.depth>1,p=a.depth>1&&(e.useArrayDepthTexture||e.multiview||d);void 0===h&&u&&(h=new Ir,h.format=e.stencilBuffer?le:oe,h.type=e.stencilBuffer?te:K,h.image.width=o,h.image.height=l,h.image.depth=a.depth,h.renderTarget=e,r[t]=h),h&&(h.isArrayTexture=p),s.width===a.width&&a.height===s.height||(c=!0,h&&h.renderTarget===e&&(h.needsUpdate=!0,h.image.width=o,h.image.height=l,h.image.depth=p?a.depth:1)),s.width=a.width,s.height=a.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.renderTarget===e&&(h.needsUpdate=!0),s.sampleCount=i);const m={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,m)}h&&this.updateTexture(h,m)}!0!==s.initialized&&(s.initialized=!0,this.info.memory.renderTargets++,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:W}if(e.isHTMLTexture&&e.image){const t=this.renderer.domElement;if("requestPaint"in t){if(t.hasAttribute("layoutsubtree")||t.setAttribute("layoutsubtree","true"),e.image.parentNode!==t&&t.appendChild(e.image),0===this._htmlTextures.size){const e=this._htmlTextures;t.onpaint=t=>{const s=t&&t.changedElements;for(const t of e)s&&!s.includes(t.image)||(t.needsUpdate=!0)}}this._htmlTextures.add(e)}}const{width:n,height:a,depth:o}=this.getSize(e);if(t.width=n,t.height=a,t.depth=o,t.needsMipmaps=this.needsMipmaps(e),t.levels=t.needsMipmaps?this.getMipLevels(e,n,a):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)Et("Renderer: Texture marked for update but image is undefined.");else if(!1===i.complete)Et("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,s.bindGroups=new Set,this.info.createTexture(e),e.isVideoTexture&&!0===Jt.enabled&&Jt.getTransfer(e.colorSpace)!==tt&&Et("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=Db){let s=e.images?e.images[0]:e.image;return s?(void 0!==s.image&&(s=s.image),e.isHTMLTexture?(t.width=s.offsetWidth||1,t.height=s.offsetHeight||1,t.depth=1):"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&&i.renderTarget===e&&this._destroyTexture(i),this.delete(e),this.backend.delete(e),this.info.memory.renderTargets--}}_destroyTexture(e){if(!0===this.has(e)){const t=this.get(e);e.removeEventListener("dispose",t.onDispose);const s=t.isDefaultTexture;if(this.backend.destroyTexture(e,s),t.bindGroups)for(const s of t.bindGroups){const t=this.backend.get(s);t.groups=void 0,t.versions=void 0;for(const t of s.bindings)t.isSampler&&t.texture===e&&(!0!==t.isSampledTexture&&this.backend.destroySampler(t),t.reset(),t.release())}this._htmlTextures.delete(e),this.delete(e),this.info.destroyTexture(e)}}}class Ib extends Xs{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)}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b,yield this.a}}class Ub extends nu{static get type(){return"OverrideContextNode"}constructor(e,t=null){super(t,{overrideNodes:e}),this.isOverrideContextNode=!0}getFlowContextData(){const e=[];this.traverse(t=>{!0===t.isOverrideContextNode&&e.push(t.value.overrideNodes)});const t=new Map(e.flatMap(e=>Array.from(e.entries()))),s=super.getFlowContextData();return s.overrideNodes=t,s}}wa("overrideNode",(e,t,s)=>function(e,t=null,s=null){if(t&&t.isNode){const e=t;t=()=>e}return new Ub(new Map([[e,t]]),s)}(t,s,e)),wa("overrideNodes",(e,t)=>function(e,t=null){const s=new Map;for(const[t,i]of e){const e=null!==i?"function"==typeof i?i:()=>i:null;s.set(t,e)}return new Ub(s,t)}(t,e));class kb extends Po{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):(At(`TSL: Member "${t}" not found in struct "${s}".`,new In),r="float"),r}getHash(){return String(this.id)}generate(){return this.name}}class zb extends ha{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._nodeDataLibrary=new Map,this.isStackNode=!0}getElementType(e){return this.outputNode?this.outputNode.getElementType(e):"void"}generateNodeType(e){return this.outputNode?this.outputNode.getNodeType(e):"void"}getMemberType(e,t){return this.outputNode?this.outputNode.getMemberType(e,t):"void"}addToStack(e,t=-1){if(!0!==e.isNode)return At("TSL: Invalid node added to stack.",new In),this;if(-1===t)if(this._currentNode){let e=this._nodeDataLibrary.get(this._currentNode);void 0===e&&(e={delta:0},this._nodeDataLibrary.set(this._currentNode,e)),e.delta++,t=this.nodes.indexOf(this._currentNode)+e.delta}else t=this.nodes.length;return 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 Ka(t);return this._currentCond=ru(e,s),this.addToStack(this._currentCond)}ElseIf(e,t){const s=new Ka(t),i=ru(e,s);return this._currentCond.elseNode=i,this._currentCond=i,this}Else(e){return this._currentCond.elseNode=new Ka(e),this}Switch(e){return this._expressionNode=Qa(e),this}Case(...e){const t=[];if(e.length>=2)for(let s=0;s<e.length-1;s++)t.push(this._expressionNode.equal(Qa(e[s])));else At("TSL: Invalid parameter length. Case() requires at least two parameters.",new In);const s=new Ka(e[e.length-1]);let i=t[0];for(let e=1;e<t.length;e++)i=i.or(t[e]);const r=ru(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}build(e,...t){const s=lo(),i=e.buildStage;oo(this),e.setActiveStack(this);for(let t=0;t<this.nodes.length;t++){const s=this.nodes[t],r=this._currentNode;if(this._currentNode=s,!s.isVarNode||!s.isIntent(e)||!0===s.isAssign(e)){if("setup"===i)s.build(e);else if("analyze"===i)s.build(e,this);else if("generate"===i){const t=e.getDataFromNode(s,"any").stages,i=t&&t[e.shaderStage];if(s.isVarNode&&i&&1===i.length&&i[0]&&i[0].isStackNode)continue;s.build(e,"void")}this._currentNode=r}}let r;if(this.outputNode){const s=this.outputNode.build(e,...t);"generate"===e.buildStage&&"void"===this.outputNode.getNodeType(e)||(r=s)}else r=super.build(e,...t);return oo(s),e.removeActiveStack(this),r}}const Vb=to(zb).setParameterLength(0,1);new ps;const Gb=new cs;vc.flipX(),Gb.depthTexture=new Ir(1,1);const $b=new yn(-1,1,1,-1,0,1);class jb extends Yi{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new Ii([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new Ii(t,2))}}const Wb=new jb,Hb=wo(_l([-1,-1,3]).element(Fu),_l([3,-1,-1]).element(Fu),0,1);class qb extends Sr{constructor(e){super(Wb,e),this.camera=$b,this.isQuadMesh=!0}async renderAsync(e){Nt('QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await e.init(),e.render(this,$b)}render(e){const t=this.material.vertexNode;this.material.vertexNode=Hb,e.render(this,$b),this.material.vertexNode=t}}function Xb(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 Xs),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 Yb=ao(([e])=>ch(co(52.9829189).mul(ch(jh(e,go(.06711056,.00583715)))))).setLayout({name:"interleavedGradientNoise",type:"float",inputs:[{name:"position",type:"vec2"}]}),Kb=ao(([e,t,s])=>{const i=co(2.399963229728653),r=ah(co(e).add(.5).div(co(t))),n=co(e).mul(i).add(s);return go(mh(n),dh(n)).mul(r)}).setLayout({name:"vogelDiskSample",type:"vec2",inputs:[{name:"sampleIndex",type:"int"},{name:"samplesCount",type:"int"},{name:"phi",type:"float"}]}),Qb=new ps,Zb=yl(0).setGroup(ml).onRenderUpdate(({scene:e})=>e.backgroundBlurriness),Jb=yl(1).setGroup(ml).onRenderUpdate(({scene:e})=>e.backgroundIntensity),e_=yl(new ps).setGroup(ml).onRenderUpdate(({scene:e})=>{const t=e.background;return null!==t&&t.isTexture&&300!==t.mapping||e.backgroundNode&&e.backgroundNode.isNode?Qb.makeRotationFromEuler(e.backgroundRotation).transpose():Qb.identity(),Qb}),t_=ao(([e,t])=>e.mul(t).clamp()).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),s_=ao(([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"}]}),i_=ao(([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"}]}),r_=ao(([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)}),n_=ao(([e,t])=>{const s=Co(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),i=Co(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=s.mul(e),e=r_(e),(e=i.mul(e)).clamp()}).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),a_=Co(xo(1.6605,-.1246,-.0182),xo(-.5876,1.1329,-.1006),xo(-.0728,-.0083,1.1187)),o_=Co(xo(.6274,.0691,.0164),xo(.3293,.9195,.088),xo(.0433,.0113,.8956)),l_=ao(([e])=>{const t=xo(e).toVar(),s=xo(t.mul(t)).toVar(),i=xo(s.mul(s)).toVar();return co(15.5).mul(i.mul(s)).sub(El(40.14,i.mul(t))).add(El(31.96,i).sub(El(6.868,s.mul(t))).add(El(.4298,s).add(El(.1191,t).sub(.00232))))}),h_=ao(([e,t])=>{const s=xo(e).toVar(),i=Co(xo(.856627153315983,.137318972929847,.11189821299995),xo(.0951212405381588,.761241990602591,.0767994186031903),xo(.0482516061458583,.101439036467562,.811302368396859)),r=Co(xo(1.1271005818144368,-.1413297634984383,-.14132976349843826),xo(-.11060664309660323,1.157823702216272,-.11060664309660294),xo(-.016493938717834573,-.016493938717834257,1.2519364065950405)),n=co(-12.47393),a=co(4.026069);return s.mulAssign(t),s.assign(o_.mul(s)),s.assign(i.mul(s)),s.assign(kh(s,1e-10)),s.assign(nh(s)),s.assign(s.sub(n).div(a.sub(n))),s.assign(Qh(s,0,1)),s.assign(l_(s)),s.assign(r.mul(s)),s.assign(Hh(kh(xo(0),s),xo(2.2))),s.assign(a_.mul(s)),s.assign(Qh(s,0,1)),s}).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),u_=ao(([e,t])=>{const s=co(.76),i=co(.15);e=e.mul(t);const r=Uh(e.r,Uh(e.g,e.b)),n=ru(r.lessThan(.08),r.sub(El(6.25,r.mul(r))),.04);e.subAssign(n);const a=kh(e.r,kh(e.g,e.b));ho(a.lessThan(s),()=>e);const o=Ml(1,s),l=Ml(1,o.mul(o).div(a.add(o.sub(s))));e.mulAssign(l.div(a));const h=Ml(1,Al(1,i.mul(a.sub(l)).add(1)));return Kh(e,xo(l),h)}).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class c_ extends ha{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,"void");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}}class d_ extends c_{static get type(){return"FunctionNode"}constructor(e="",t=[],s=""){super(e,t,s)}generateNodeType(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);if(""!==i){const t=e.getDataFromNode(this);!0!==t.declarationRegistered&&(n.name=i,e.registerDeclaration(n),t.declarationRegistered=!0)}const a=e.getPropertyName(n),o=this.getNodeFunction(e).getCode(a);return n.code=o+"\n","property"===t?a:e.format(`${a}()`,r,t)}}function p_(e){let t;const s=e.context.getViewZ;return void 0!==s&&(t=s(this)),(t||hd.z).negate()}const m_=ao(([e,t],s)=>{const i=p_(s);return eu(e,t,i)}),f_=ao(([e],t)=>{const s=p_(t);return e.mul(e,s,s).negate().exp().oneMinus()}),g_=ao(([e,t])=>wo(t.toFloat().mix(el.rgb,e.toVec3()),el.a));let y_;function b_(e){y_=y_||new WeakMap;let t=y_.get(e);return void 0===t&&y_.set(e,t={}),t}function __(e){const t=b_(e);return t.shadowMatrix||(t.shadowMatrix=yl("mat4").setGroup(ml).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 x_(e){const t=b_(e);return t.position||(t.position=yl(new Wt).setGroup(ml).onRenderUpdate((t,s)=>s.value.setFromMatrixPosition(e.matrixWorld)))}function v_(e){const t=b_(e);return t.viewPosition||(t.viewPosition=yl(new Wt).setGroup(ml).onRenderUpdate(({camera:t},s)=>{s.value=s.value||new Wt,s.value.setFromMatrixPosition(e.matrixWorld),s.value.applyMatrix4(t.matrixWorldInverse)}))}const T_=e=>$c.transformDirection(x_(e).sub(function(e){const t=b_(e);return t.targetPosition||(t.targetPosition=yl(new Wt).setGroup(ml).onRenderUpdate((t,s)=>s.value.setFromMatrixPosition(e.target.matrixWorld)))}(e))),S_=Bo("vec3","totalDiffuse"),w_=Bo("vec3","totalSpecular"),M_=Bo("vec3","outgoingLight"),E_=(e,t)=>{for(const s of t)if(s.isAnalyticLightNode&&s.light.id===e)return s;return null},A_=new WeakMap,N_=[];class C_ extends ha{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=S_,this.totalSpecularNode=w_,this.outgoingLightNode=M_,this._lights=[],this.global=!0}customCacheKey(){const e=this.getBuiltinLights();for(let t=0;t<e.length;t++){const s=e[t];if(N_.push(s.id),N_.push(s.castShadow?1:0),!0===s.isSpotLight){const e=null!==s.map?s.map.id:-1,t=s.colorNode?s.colorNode.getCacheKey():-1;N_.push(e,t)}}const t=zn(N_);return N_.length=0,t}getHash(e){const t=e.getDataFromNode(this);if(void 0===t.lightNodesHash){const s=this.setupLightsNode(e);t.lightNodes=s;const i=[];for(const e of s)i.push(e.getHash());t.lightNodesHash="lights-"+i.join(",")}return t.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=e.getDataFromNode(this).lightNodes||null,i=(e=>e.sort((e,t)=>e.id-t.id))([...e.context.materialLightings,...this.getBuiltinLights()]),r=e.renderer.library;for(const e of i)if(e.isNode)t.push(e);else{let i=null;if(null!==s&&(i=E_(e.id,s)),null===i){const t=r.getLightNodeClass(e.constructor);if(null===t){Et(`LightsNode.setupNodeLights: Light node not found for ${e.constructor.name}`);continue}!1===A_.has(e)&&A_.set(e,new t(e)),i=A_.get(e)}t.push(i)}return 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){const t=e.getDataFromNode(this);return void 0===t.lightNodes&&(t.lightNodes=this.setupLightsNode(e)),t.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:a}=this;i.outgoingLight=s;const o=e.addStack();n.nodes=o.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=xo(null!==h?h.mix(m,l):l)),t.assign(m),a.assign(c.add(p)),s.assign(t.add(a)),r.finish(e),s=s.bypass(e.removeStack())}else n.nodes=[];return e.lightsNode=t,s}setLights(e){return this._lights=e,this}getLights(){return this._lights}getBuiltinLights(){return this._lights}get hasLights(){return this._lights.length>0}}const R_=new WeakMap,P_=new Zy,B_=[];class F_ extends ha{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=Jn,this.isShadowBaseNode=!0}getShadowMaterial(){return(e=>{let t=R_.get(e);return void 0===t&&(t=new hf,t.colorNode=wo(0,0,0,1),t.isShadowPassMaterial=!0,t.name="ShadowMaterial",t.blending=0,t.fog=!1,R_.set(e,t)),t})(this.light)}disposeShadowMaterial(){(e=>{const t=R_.get(e);void 0!==t&&(t.dispose(),R_.delete(e))})(this.light)}getShadowRenderObjectFunction(e,t=this.light.shadow){const s=e.shadowMap.type,i=e.getMRT();return((e,t,s,i)=>{B_[0]=e,B_[1]=t;let r=P_.get(B_);return void 0!==r&&r.shadowType===s&&r.useVelocity===i||(r=(r,n,a,o,l,h,u,c,d)=>{(!0===r.castShadow||r.receiveShadow&&3===s)&&(i&&(Xn(r).useVelocity=!0),r.onBeforeShadow(e,r,a,t.camera,o,n.overrideMaterial,h),e.renderObject(r,n,a,o,l,h,u,c,d),r.onAfterShadow(e,r,a,t.camera,o,n.overrideMaterial,h))},r.shadowType=s,r.useVelocity=i,P_.set(B_,r)),B_[0]=null,B_[1]=null,r})(e,t,s,!!i&&i.has("velocity"))}setupShadowPosition({context:e,material:t}){L_.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||od)}}const L_=Bo("vec3","shadowPositionWorld"),D_=ao(({depthTexture:e,shadowCoord:t,depthLayer:s})=>{let i=lc(e,t.xy).setName("t_basic");return e.isArrayTexture&&(i=i.depth(s)),i.compare(t.z)}),O_=ao(({depthTexture:e,shadowCoord:t,shadow:s,depthLayer:i})=>{const r=(t,s)=>{let r=lc(e,t);return e.isArrayTexture&&(r=r.depth(i)),r.compare(s)},n=Id("mapSize","vec2",s).setGroup(ml),a=Id("radius","float",s).setGroup(ml),o=go(1).div(n),l=a.mul(o.x),h=Yb(Sc.xy).mul(6.28318530718);return wl(r(t.xy.add(Kb(0,5,h).mul(l)),t.z),r(t.xy.add(Kb(1,5,h).mul(l)),t.z),r(t.xy.add(Kb(2,5,h).mul(l)),t.z),r(t.xy.add(Kb(3,5,h).mul(l)),t.z),r(t.xy.add(Kb(4,5,h).mul(l)),t.z)).mul(.2)}),I_=ao(({depthTexture:e,shadowCoord:t,depthLayer:s},i)=>{let r=lc(e).sample(t.xy);e.isArrayTexture&&(r=r.depth(s)),r=r.rg;const n=r.x,a=kh(1e-7,r.y.mul(r.y)),o=i.renderer.reversedDepthBuffer?zh(n,t.z):zh(t.z,n),l=co(1).toVar();return ho(o.notEqual(1),()=>{const e=t.z.sub(n);let s=a.div(a.add(e.mul(e)));s=Qh(Ml(s,.3).div(.65)),l.assign(kh(o,s))}),l}),U_=ao(({samples:e,radius:t,size:s,shadowPass:i,depthLayer:r})=>{const n=co(0).toVar("meanVertical"),a=co(0).toVar("squareMeanVertical"),o=e.lessThanEqual(co(1)).select(co(0),co(2).div(e.sub(1))),l=e.lessThanEqual(co(1)).select(co(0),co(-1));Rm({start:po(0),end:po(e),type:"int",condition:"<"},({i:e})=>{const h=l.add(co(e).mul(o));let u=i.sample(wl(Sc.xy,go(0,h).mul(t)).div(s));i.value.isArrayTexture&&(u=u.depth(r)),u=u.x,n.addAssign(u),a.addAssign(u.mul(u))}),n.divAssign(e),a.divAssign(e);const h=ah(a.sub(n.mul(n)).max(0));return go(n,h)}),k_=ao(({samples:e,radius:t,size:s,shadowPass:i,depthLayer:r})=>{const n=co(0).toVar("meanHorizontal"),a=co(0).toVar("squareMeanHorizontal"),o=e.lessThanEqual(co(1)).select(co(0),co(2).div(e.sub(1))),l=e.lessThanEqual(co(1)).select(co(0),co(-1));Rm({start:po(0),end:po(e),type:"int",condition:"<"},({i:e})=>{const h=l.add(co(e).mul(o));let u=i.sample(wl(Sc.xy,go(h,0).mul(t)).div(s));i.value.isArrayTexture&&(u=u.depth(r)),n.addAssign(u.x),a.addAssign(wl(u.y.mul(u.y),u.x.mul(u.x)))}),n.divAssign(e),a.divAssign(e);const h=ah(a.sub(n.mul(n)).max(0));return go(n,h)}),z_=[D_,O_,null,I_];let V_;const G_=new qb;class $_ extends F_{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 a=i.x.greaterThanEqual(0).and(i.x.lessThanEqual(1)).and(i.y.greaterThanEqual(0)).and(i.y.lessThanEqual(1)).and(i.z.lessThanEqual(1)),o=t({depthTexture:s,shadowCoord:i,shadow:r,depthLayer:n});return a.select(o,co(1))}setupShadowCoord(e,t){const{shadow:s}=this,{renderer:i}=e,r=s.biasNode||Id("bias","float",s).setGroup(ml);let n,a=t;if(s.camera.isOrthographicCamera||!0!==i.logarithmicDepthBuffer)a=a.xyz.div(a.w),n=a.z;else{const e=a.w;a=a.xy.div(e);const t=Id("near","float",s.camera).setGroup(ml),i=Id("far","float",s.camera).setGroup(ml);n=ef(e.negate(),t,i)}return a=xo(a.x,a.y.oneMinus(),i.reversedDepthBuffer?n.sub(r):n.add(r)),a}getShadowFilterFn(e){return z_[e]}setupRenderTarget(e,t){const s=new Ir(e.mapSize.width,e.mapSize.height);s.name="ShadowDepthTexture",s.compareFunction=t.renderer.reversedDepthBuffer?ht:at;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,{depthTexture:n,shadowMap:a}=this.setupRenderTarget(r,e),o=t.shadowMap.type,l=t.hasCompatibility(yt);if(1===o&&l?(n.minFilter=G,n.magFilter=G):(n.minFilter=k,n.magFilter=k),r.camera.coordinateSystem=s.coordinateSystem,r.camera.updateProjectionMatrix(),3===o&&!0!==r.isPointLightShadow){n.compareFunction=null,a.depth>1?(a._vsmShadowMapVertical||(a._vsmShadowMapVertical=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:ce,type:Z,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:ce,type:Z,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:ce,type:Z,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:ce,type:Z,depthBuffer:!1}));let t=lc(n);n.isArrayTexture&&(t=t.depth(this.depthLayer));let s=lc(this.vsmShadowMapVertical.texture);n.isArrayTexture&&(s=s.depth(this.depthLayer));const i=Id("blurSamples","float",r).setGroup(ml),o=Id("radius","float",r).setGroup(ml),l=Id("mapSize","vec2",r).setGroup(ml),h=au(e.getSharedContext());let u=this.vsmMaterialVertical||(this.vsmMaterialVertical=new hf);u.contextNode=h,u.fragmentNode=U_({samples:i,radius:o,size:l,shadowPass:t,depthLayer:this.depthLayer}),u.name="VSMVertical",u=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new hf),u.contextNode=h,u.fragmentNode=k_({samples:i,radius:o,size:l,shadowPass:s,depthLayer:this.depthLayer}),u.name="VSMHorizontal"}const h=Id("intensity","float",r).setGroup(ml),u=Id("normalBias","float",r).setGroup(ml),c=__(i),d=xd.mul(u);let p;if(!t.highPrecision||e.material.receivedShadowPositionNode||e.context.shadowPositionWorld)p=c.mul(L_.add(d));else{p=yl("mat4").onObjectUpdate(({object:e},t)=>t.value.multiplyMatrices(c.value,e.matrixWorld)).mul(nd).add(c.mul(wo(d,0)))}const m=this.setupShadowCoord(e,p),f=r.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(null===f)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const g=3===o&&!0!==r.isPointLightShadow?this.vsmShadowMapHorizontal.texture:n,y=this.setupShadowFilter(e,{filterFn:f,shadowTexture:a.texture,depthTexture:g,shadowCoord:m,shadow:r,depthLayer:this.depthLayer});let b,_;!0===t.shadowMap.transmitted&&(a.texture.isCubeTexture?b=Dd(a.texture,m.xyz):(b=lc(a.texture,m),n.isArrayTexture&&(b=b.depth(this.depthLayer)))),_=b?Kh(1,y.rgb.mix(b,1),h.mul(b.a)).toVar():Kh(1,y,h).toVar(),this.shadowMap=a,this.shadow.map=a;const x=`${this.light.type} Shadow [ ${this.light.name||"ID: "+this.light.id} ]`;return b&&_.toInspector(`${x} / Color`,()=>this.shadowMap.texture.isCubeTexture?Dd(this.shadowMap.texture,Sf()):lc(this.shadowMap.texture)),_.toInspector(`${x} / Depth`,()=>{const e=Id("near","float",this.shadow.camera),t=Id("far","float",this.shadow.camera);let s,i;return s=this.shadowMap.texture.isCubeTexture?Dd(this.shadowMap.depthTexture,Sf()).r:lc(this.shadowMap.depthTexture).r,i=this.shadow.camera.isPerspectiveCamera?Jm(s,e,t):Qm(s,e,t),i=Km(i,e,t),i.oneMinus()})}setup(e){if(!1!==e.renderer.shadowMap.enabled)return ao(()=>{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.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 a=n.name;n.name=`Shadow Map [ ${i.name||"ID: "+i.id} ]`,r.render(n,t.camera),n.name=a}updateShadow(e){const{shadowMap:t,shadow:s}=this,{renderer:i,scene:r,camera:n}=e,a=i.shadowMap.type,o=t.depthTexture.version;this._depthVersionCached=o;const l=s.camera.layers.mask;4294967294&s.camera.layers.mask||(s.camera.layers.mask=n.layers.mask);const h=i.getRenderObjectFunction();V_=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=Xb(e,s)),s}(i,r,V_),r.overrideMaterial=this.getShadowMaterial(),i.setRenderObjectFunction(this.getShadowRenderObjectFunction(i,this.shadow||this.light.shadow)),i.setClearColor(0,0),i.setRenderTarget(t),this.renderShadow(e),i.setRenderObjectFunction(h),3===a&&!0!==s.isPointLightShadow&&this.vsmPass(i),s.camera.layers.mask=l,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)}(i,r,V_)}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),G_.material=this.vsmMaterialVertical,G_.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),G_.material=this.vsmMaterialHorizontal,G_.render(e)}dispose(){this._reset(),super.dispose()}_reset(){this._currentShadowType=null,this.disposeShadowMaterial(),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){if(!0===e.renderer._isPreCompiling)return;const{shadow:t}=this;let s=t.needsUpdate||t.autoUpdate;s&&(this._cameraFrameId.get(e.camera)===e.frameId&&(s=!1),this._cameraFrameId.set(e.camera,e.frameId)),s&&(this.updateShadow(e),this.shadowMap.depthTexture.version===this._depthVersionCached&&(t.needsUpdate=!1))}}const j_=new Xs,W_=new ps,H_=new Wt,q_=new Wt,X_=[new Wt(1,0,0),new Wt(-1,0,0),new Wt(0,-1,0),new Wt(0,1,0),new Wt(0,0,1),new Wt(0,0,-1)],Y_=[new Wt(0,-1,0),new Wt(0,-1,0),new Wt(0,0,-1),new Wt(0,0,1),new Wt(0,-1,0),new Wt(0,-1,0)],K_=[new Wt(1,0,0),new Wt(-1,0,0),new Wt(0,1,0),new Wt(0,-1,0),new Wt(0,0,1),new Wt(0,0,-1)],Q_=[new Wt(0,-1,0),new Wt(0,-1,0),new Wt(0,0,1),new Wt(0,0,-1),new Wt(0,-1,0),new Wt(0,-1,0)],Z_=ao(({depthTexture:e,bd3D:t,dp:s})=>Dd(e,t).compare(s)),J_=ao(({depthTexture:e,bd3D:t,dp:s,shadow:i})=>{const r=Id("radius","float",i).setGroup(ml),n=Id("mapSize","vec2",i).setGroup(ml),a=r.div(n.x),o=wh(t),l=uh(Wh(t,o.x.greaterThan(o.z).select(xo(0,1,0),xo(1,0,0)))),h=Wh(t,l),u=Yb(Sc.xy).mul(6.28318530718),c=Kb(0,5,u),d=Kb(1,5,u),p=Kb(2,5,u),m=Kb(3,5,u),f=Kb(4,5,u);return Dd(e,t.add(l.mul(c.x).add(h.mul(c.y)).mul(a))).compare(s).add(Dd(e,t.add(l.mul(d.x).add(h.mul(d.y)).mul(a))).compare(s)).add(Dd(e,t.add(l.mul(p.x).add(h.mul(p.y)).mul(a))).compare(s)).add(Dd(e,t.add(l.mul(m.x).add(h.mul(m.y)).mul(a))).compare(s)).add(Dd(e,t.add(l.mul(f.x).add(h.mul(f.y)).mul(a))).compare(s)).mul(.2)}),ex=ao(({filterFn:e,depthTexture:t,shadowCoord:s,shadow:i},r)=>{const n=s.xyz.toConst(),a=n.abs().toConst(),o=a.x.max(a.y).max(a.z),l=yl("float").setGroup(ml).onRenderUpdate(()=>i.camera.near),h=yl("float").setGroup(ml).onRenderUpdate(()=>i.camera.far),u=Id("bias","float",i).setGroup(ml),c=co(1).toVar();return ho(o.sub(h).lessThanEqual(0).and(o.sub(l).greaterThanEqual(0)),()=>{let s;r.renderer.reversedDepthBuffer?(s=((e,t,s)=>t.mul(e.add(s)).div(e.mul(t.sub(s))))(o.negate(),l,h),s.subAssign(u)):r.renderer.logarithmicDepthBuffer?(s=ef(o.negate(),l,h),s.addAssign(u)):(s=Zm(o.negate(),l,h),s.addAssign(u));const a=n.normalize();c.assign(e({depthTexture:t,bd3D:a,dp:s,shadow:i}))}),c});class tx extends $_{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return 0===e?Z_:J_}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,depthTexture:s,shadowCoord:i,shadow:r}){return ex({filterFn:t,depthTexture:s,shadowCoord:i,shadow:r})}setupRenderTarget(e,t){const s=new Ur(e.mapSize.width);s.name="PointShadowDepthTexture",s.compareFunction=t.renderer.reversedDepthBuffer?ht:at;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,a=t.camera,o=t.matrix,l=r.coordinateSystem===mt,h=l?X_:K_,u=l?Y_:Q_;s.setSize(t.mapSize.width,t.mapSize.width);const c=r.autoClear,d=r.getClearColor(j_),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||a.far;l!==a.far&&(a.far=l,a.updateProjectionMatrix()),H_.setFromMatrixPosition(i.matrixWorld),a.position.copy(H_),q_.copy(a.position),q_.add(h[e]),a.up.copy(u[e]),a.lookAt(q_),a.updateMatrixWorld(),o.makeTranslation(-H_.x,-H_.y,-H_.z),W_.multiplyMatrices(a.projectionMatrix,a.matrixWorldInverse),t._frustum.setFromProjectionMatrix(W_,a.coordinateSystem,a.reversedDepth);const c=n.name;n.name=`Point Light Shadow [ ${i.name||"ID: "+i.id} ] - Face ${e+1}`,r.render(n,a),n.name=c}r.autoClear=c,r.setClearColor(d,p)}}class sx extends Om{static get type(){return"AnalyticLightNode"}constructor(e=null){super(),this.light=e,this.color=new Xs,this.colorNode=e&&e.colorNode||yl(this.color).setGroup(ml),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=Zn,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 v_(this.light).sub(e.context.positionView||hd)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return((e,t)=>new $_(e,t))(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?Qa(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 ix=ao(({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)});class rx extends sx{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=yl(0).setGroup(ml),this.decayExponentNode=yl(2).setGroup(ml)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return((e,t)=>new tx(e,t))(this.light)}setupDirect(e){return(({color:e,lightVector:t,cutoffDistance:s,decayExponent:i})=>{const r=t.normalize(),n=t.length(),a=ix({lightDistance:n,cutoffDistance:s,decayExponent:i});return{lightDirection:r,lightColor:e.mul(a)}})({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}}const nx=ao(([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(El(s,s).sub(El(i,i)))),n}),ax=new Ib;class ox extends rb{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(ax),ax.a=i._clearColor.a;else if(!0===r.isColor)r.getRGB(ax),ax.a=1,n=!0;else if(!0===r.isNode){const o=this.get(e),l=r;ax.copy(i._clearColor);let h=o.backgroundMesh;if(void 0===h){const c=wo(l).mul(Jb).context({getUV:()=>e_.mul(bd),getTextureLevel:()=>Zb}),d=Vc.element(3).element(3).equal(1),p=Al(1,Vc.element(1).element(1)).mul(3),m=d.select(nd.mul(p),nd),f=Jc.mul(wo(m,0));let g=Vc.mul(wo(f.xyz,1));g=g.setZ(g.w);const y=new hf;function b(){r.removeEventListener("dispose",b),h.material.dispose(),h.geometry.dispose()}y.name="Background.material",y.side=1,y.depthTest=!1,y.depthWrite=!1,y.allowOverride=!1,y.fog=!1,y.lights=!1,y.vertexNode=g,y.colorNode=c,o.backgroundMeshNode=c,o.backgroundMesh=h=new Sr(new Gr(1,32,32),y),h.frustumCulled=!1,h.name="Background.mesh",r.addEventListener("dispose",b)}const u=l.getCacheKey();o.backgroundCacheKey!==u&&(o.backgroundMeshNode.node=wo(l).mul(Jb),o.backgroundMeshNode.needsUpdate=!0,h.material.needsUpdate=!0,o.backgroundCacheKey=u),t.unshift(h,h.geometry,h.material,0,0,null,null)}else At("Renderer: Unsupported background configuration.",r);const a=i.xr.getEnvironmentBlendMode();if("additive"===a?ax.set(0,0,0,1):"alpha-blend"===a&&ax.set(0,0,0,0),!0===i.autoClear||!0===n){const _=s.clearColorValue;_.r=ax.r,_.g=ax.g,_.b=ax.b,_.a=ax.a,!0!==i.backend.isWebGLBackend&&!0!==i.alpha||(_.r*=_.a,_.g*=_.a,_.b*=_.a),s.depthClearValue=i.getClearDepth(),s.stencilClearValue=i.getClearStencil(),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 lx=0;class hx{constructor(e="",t=[]){this.name=e,this.bindings=t,this.id=lx++}}class ux{constructor(e,t,s,i,r,n,a,o,l,h,u=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=s,this.transforms=u,this.nodeAttributes=i,this.bindings=r,this.updateNodes=n,this.updateBeforeNodes=a,this.updateAfterNodes=o,this.observer=l,this.hardwareClipping=h,this.usedTimes=0}createBindings(){const e=[];for(const t of this.bindings){if(!0!==t.bindings[0].groupNode.shared){const s=new hx(t.name,[]);e.push(s);for(const e of t.bindings)s.bindings.push(e.clone())}else e.push(t)}return e}}class cx{constructor(e,t,s=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=s}}class dx{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 px{constructor(e,t,s=!1,i=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=s,this.count=i}}class mx extends px{constructor(e,t,s=null,i=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=s,this.interpolationSampling=i}}class fx{constructor(e,t,s=""){this.name=e,this.type=t,this.code=s,Object.defineProperty(this,"isNodeCode",{value:!0})}}let gx=0;class yx{constructor(e=null){this.id=gx++,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 bx{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class _x{constructor(e,t){this.name=e,this.value=t,this.boundary=0,this.itemSize=0,this.offset=0,this.index=-1}setValue(e){this.value=e}getValue(){return this.value}}class xx extends _x{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class vx extends _x{constructor(e,t=new $t){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class Tx extends _x{constructor(e,t=new Wt){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class Sx extends _x{constructor(e,t=new us){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class wx extends _x{constructor(e,t=new Xs){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class Mx extends _x{constructor(e,t=new Nn){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}}class Ex extends _x{constructor(e,t=new Xt){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class Ax extends _x{constructor(e,t=new ps){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class Nx extends xx{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Cx extends vx{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Rx extends Tx{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Px extends Sx{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Bx extends wx{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Fx extends Mx{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Lx extends Ex{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class Dx extends Ax{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}let Ox=0;const Ix=new WeakMap,Ux=new WeakMap,kx=new WeakMap,zx=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),Vx=e=>/e/g.test(e)?String(e).replace(/\+/g,""):(e=Number(e))+(e%1?"":".0"),Gx=e=>{if(e.writeUsageCount>0)return!0;if(void 0!==e.subBuildsCache)for(const t in e.subBuildsCache)if(Gx(e.subBuildsCache[t]))return!0;return!1};class $x{constructor(e,t,s){this.object=e,this.material=e&&e.material||null,this.geometry=e&&e.geometry||null,this.compute=null,this.renderer=t,this.parser=s,this.scene=null,this.camera=null,this.nodes=new Set,this.sequentialNodes=new Set,this.updateNodes=[],this.updateBeforeNodes=[],this.updateAfterNodes=[],this.hashNodes={},this.observer=null,this.lightsNode=null,this.environmentNode=null,this.fogNode=null,this.clippingContext=null,this.hardwareClipping=!1,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=Vb(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new yx,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:Ox++})}isFlatShading(){return!0===this.material.flatShading||!1===this.geometry.hasAttribute("normal")}isOpaque(){const e=this.material;return!1===e.transparent&&1===e.blending&&!1===e.alphaToCoverage}createRenderTarget(e,t,s){return new cs(e,t,s)}createCubeRenderTarget(e,t){return new wf(e,t)}includes(e){return this.nodes.has(e)}getOutputType(e=0){const t=this.renderer.getRenderTarget();return null!==t?Hn(t.textures[e]):"vec4"}getOutputStructName(){}_getBindGroup(e,t){const s=t[0].groupNode;let i,r=s.shared;if(r)for(let e=1;e<t.length;e++)s!==t[e].groupNode&&(r=!1);if(r){let s="";for(const e of t)if(e.isNodeUniformsGroup){e.uniforms.sort((e,t)=>e.nodeUniform.node.id-t.nodeUniform.node.id);for(const t of e.uniforms)s+=t.nodeUniform.node.id}else s+=e.nodeUniform.id;const r=this.renderer._currentRenderContext||this.renderer;let n=Ix.get(r);void 0===n&&(n=new Map,Ix.set(r,n));const a=kn(s);i=n.get(a),void 0===i&&(i=new hx(e,t),n.set(a,i))}else i=new hx(e,t);return i}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 na)for(const i in s[e]){const r=s[e][i],n=t[i]||(t[i]=[]);for(const e of r)!1===n.includes(e)&&n.push(e)}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}}setHashNode(e,t){this.hashNodes[t]=e}addNode(e){!1===this.nodes.has(e)&&(this.nodes.add(e),this.setHashNode(e,e.getHash(this)))}addSequentialNode(e){const t=e.updateBeforeType,s=e.updateAfterType;t===Qn&&s===Qn||this.sequentialNodes.add(e)}buildUpdateNodes(){for(const e of this.nodes){e.updateType!==Qn&&this.updateNodes.push(e)}for(const e of this.sequentialNodes){const t=e.updateBeforeType,s=e.updateAfterType;t!==Qn&&this.updateBeforeNodes.push(e),s!==Qn&&this.updateAfterNodes.push(e)}}get currentNode(){return this.chaining[this.chaining.length-1]}get renderPipeline(){return this.context.renderPipeline}isFilteredTexture(e){return e.magFilter===G||e.magFilter===$||e.magFilter===V||e.magFilter===j||e.minFilter===G||e.minFilter===$||e.minFilter===V||e.minFilter===j}getUniformBufferLimit(){return this.renderer.backend.capabilities.getUniformBufferLimit()}addChain(e){this.chaining.push(e)}removeChain(e){if(this.chaining.pop()!==e)throw new Error("THREE.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.getGI,delete e.getShadow,delete e.nodeLoop,delete e.nodeBlock,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 yx(t?this.getCache():null)),s.cache}isAvailable(){return!1}getVertexIndex(){Et("Abstract function.")}getInstanceIndex(){Et("Abstract function.")}getDrawIndex(){Et("Abstract function.")}getFrontFacing(){Et("Abstract function.")}getFragCoord(){Et("Abstract function.")}isFlipY(){return!1}isContextAssign(){return!0===this.context.assign}increaseUsage(e){const t=this.getDataFromNode(e);return t.usageCount=void 0===t.usageCount?1:t.usageCount+1,this.isContextAssign()?t.writeUsageCount=void 0===t.writeUsageCount?1:t.writeUsageCount+1:t.readUsageCount=void 0===t.readUsageCount?1:t.readUsageCount+1,t.usageCount}hasWriteUsage(e){const t=e.getShared(this),s=(t.isGlobal(this)?this.globalCache:this.cache).getData(t);if(void 0!==s)for(const e in s)if(Gx(s[e]))return!0;return!1}generateTexture(){Et("Abstract function.")}generateTextureLod(){Et("Abstract function.")}generateTextureSize(){Et("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 Xs:"vec2"===e||"uvec2"===e||"ivec2"===e?t=new $t:"vec3"===e||"uvec3"===e||"ivec3"===e?t=new Wt:"vec4"!==e&&"uvec4"!==e&&"ivec4"!==e||(t=new us)),"float"===e)return Vx(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")}( ${Vx(t.r)}, ${Vx(t.g)}, ${Vx(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(`THREE.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 cx(e,t);return this.registerDeclaration(i),s.push(i),i}getPropertyName(e){return e.name}isReservedKeyword(){return!1}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;return!0===e.isDepthTexture?"float":t===Y?"int":t===K?"uint":"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=jn(e);const i="float"===t?"":t[0];return!0===/mat2/.test(t)&&(s=s.replace("vec","mat")),i+s}getTypeFromArray(e){return zx.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 Oi||!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("THREE.NodeBuilder: Invalid active stack removal.");this.activeStacks.pop()}getActiveStack(){return this.activeStacks[this.activeStacks.length-1]}getBaseStack(){return this.activeStacks[0]}addStack(){this.stack=Vb(this.stack);const e=lo();return this.stacks.push(e),oo(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,oo(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];if(0===this.subBuildLayers.length)return r;const n=i.any?i.any.subBuilds:null,a=this.getClosestSubBuild(n);return a&&(void 0===r.subBuildsCache&&(r.subBuildsCache={}),r=r.subBuildsCache[a]||(r.subBuildsCache[a]={}),r.subBuilds=n),r}getNodeProperties(e,t="any"){const s=this.getDataFromNode(e,t);return s.properties||(s.properties={outputNode:null})}getBufferAttributeFromNode(e,t,s=null){const i=this.getDataFromNode(e,"vertex");let r=i.bufferAttribute;if(void 0===r){const n=this.uniforms.index++;null===s&&(s="nodeAttribute"+n),r=new cx(s,t,e),this.bufferAttributes.push(r),i.bufferAttribute=r}return r}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 a=this.structs.index++;null===s&&(s="StructType"+a),n=new bx(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 a=this.uniforms.index++;n=new dx(i||"nodeUniform"+a,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),a=this.getSubBuildProperty("variable",n.subBuilds);let o=n[a];if(void 0===o){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"!==a&&(t=this.getSubBuildProperty(t,n.subBuilds));const c=e.getArrayCount(this);o=new px(t,s,r,c),r||h.push(o),this.registerDeclaration(o),n[a]=o}return o}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"),a=this.getSubBuildProperty("varying",n.subBuilds);let o=n[a];if(void 0===o){const e=this.varyings,l=e.length;null===t&&(t="nodeVarying"+l),"varying"!==a&&(t=this.getSubBuildProperty(t,n.subBuilds)),o=new mx(t,s,i,r),e.push(o),this.registerDeclaration(o),n[a]=o}return o}registerDeclaration(e){const t=this.shaderStage,s=this.declarations[t]||(this.declarations[t]={}),i=this.renderer.debug.diagnostics.keywords,r=e.name;let n=r,a=this.getPropertyName(e),o=1;for(;i&&this.isReservedKeyword(n)||void 0!==s[a];)n=r+"_"+o++,e.name=n,a=this.getPropertyName(e);n!==r&&Et(`TSL: Declaration name '${r}' of '${e.type}' is a reserved keyword or already in use. Renamed to '${n}'.`),s[a]=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 fx("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=this.renderer.backend;let s=Ux.get(t);void 0===s&&(s=new WeakMap,Ux.set(t,s));let i=s.get(e);if(void 0===i){i=new d_;const t=this.currentFunctionNode;this.currentFunctionNode=i,i.code=this.buildFunctionCode(e),this.currentFunctionNode=t,s.set(e,i)}return i}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 kb(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,a=this.buildStage,o=this.stack,l={code:""};this.flow=l,this.vars={},this.declarations={},this.cache=new yx,this.stack=Vb();for(const s of ra)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=o,this.setBuildStage(a),l}getFunctionOperator(){return null}buildFunctionCode(){Et("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,a=this.shaderStage,o=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(a),this.cache=n,this.tab=r,this.context=o,h}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){Et("Abstract function.")}getVaryings(){Et("Abstract function.")}getVar(e,t,s=null){return`${null!==s?this.generateArrayDeclaration(e,s):this.getType(e)} ${t}`}getVars(e,t=!1){const s=[],i=this.vars[e];if(void 0!==i)for(const e of i)s.push(`${this.getVar(e.type,e.name,e.count)};`);return s.join(t?"\n":"\n\t")}getUniforms(){Et("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(){Et("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}prebuild(){const{renderer:e,material:t}=this;if(!0===e.contextNode.isContextNode?this.context={...this.context,...e.contextNode.getFlowContextData()}:At('NodeBuilder: "renderer.contextNode" must be an instance of `context()`.'),t&&t.contextNode&&(!0===t.contextNode.isContextNode?this.context={...this.context,...t.contextNode.getFlowContextData()}:At('NodeBuilder: "material.contextNode" must be an instance of `context()`.')),null!==t){let s=e.library.fromMaterial(t);null===s&&(At(`NodeBuilder: Material "${t.type}" is not compatible.`),s=new hf),s.build(this)}else this.addFlow("compute",this.compute)}build(){this.prebuild();for(const e of ra){this.setBuildStage(e),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage("vertex",this.context.position);for(const t of na){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}async buildAsync(){this.prebuild();for(const e of ra){this.setBuildStage(e),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage("vertex",this.context.position);for(const t of na){this.setShaderStage(t);const s=this.flowNodes[t];for(const t of s)"generate"===e?this.flowNode(t):t.build(this);await Ct()}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}getSharedDataFromNode(e){let t=kx.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 Nx(e);else if("vec2"===t||"ivec2"===t||"uvec2"===t)i=new Cx(e);else if("vec3"===t||"ivec3"===t||"uvec3"===t)i=new Rx(e);else if("vec4"===t||"ivec4"===t||"uvec4"===t)i=new Px(e);else if("color"===t)i=new Bx(e);else if("mat2"===t)i=new Fx(e);else if("mat3"===t)i=new Lx(e);else{if("mat4"!==t)throw new Error(`THREE.NodeBuilder: Uniform "${t}" not implemented.`);i=new Dx(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${t} - Node System\n`}needsPreviousData(){const e=this.renderer.getMRT();return e&&e.has("velocity")||null!==this.object&&!0===Xn(this.object).useVelocity}}class jx{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,this.compute=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(this),s=e.updateReference(this);if(t===Zn){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===Jn){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===ea&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(this),s=e.updateReference(this);if(t===Zn){const t=this._getMaps(this.updateAfterMap,s);t.frameId!==this.frameId&&!1!==e.updateAfter(this)&&(t.frameId=this.frameId)}else if(t===Jn){const t=this._getMaps(this.updateAfterMap,s);t.renderId!==this.renderId&&!1!==e.updateAfter(this)&&(t.renderId=this.renderId)}else t===ea&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(this),s=e.updateReference(this);if(t===Zn){const t=this._getMaps(this.updateMap,s);t.frameId!==this.frameId&&!1!==e.update(this)&&(t.frameId=this.frameId)}else if(t===Jn){const t=this._getMaps(this.updateMap,s);t.renderId!==this.renderId&&!1!==e.update(this)&&(t.renderId=this.renderId)}else t===ea&&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 Wx{constructor(e,t,s=null,i="",r=!1){this.type=e,this.name=t,this.count=s,this.qualifier=i,this.isConst=r}}Wx.isNodeFunctionInput=!0;class Hx extends sx{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class qx extends sx{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:T_(this.light),lightColor:e}}}class Xx extends sx{static get type(){return"HemisphereLightNode"}constructor(e=null){super(e),this.lightPositionNode=x_(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=yl(new Xs).setGroup(ml)}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=xd.dot(i).mul(.5).add(.5),n=Kh(s,t,r);e.context.irradiance.addAssign(n)}}class Yx extends sx{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=yl(0).setGroup(ml),this.penumbraCosNode=yl(0).setGroup(ml),this.cutoffDistanceNode=yl(0).setGroup(ml),this.decayExponentNode=yl(0).setGroup(ml),this.colorNode=yl(this.color).setGroup(ml)}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 eu(s,i,t)}getLightCoord(e){const t=e.getNodeProperties(this);let s=t.projectionUV;return void 0===s&&(s=function(e,t=od){const s=__(e).mul(t);return s.xyz.div(s.w)}(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),a=n.normalize(),o=a.dot(T_(r)),l=this.getSpotAttenuation(e,o),h=n.length(),u=ix({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=lc(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:a}}}class Kx extends Yx{static get type(){return"IESSpotLightNode"}constructor(e=null){super(e),this._iesTextureNode=null}getSpotAttenuation(e,t){const s=this.light.iesMap;let i=null;if(s&&!0===s.isTexture){const e=t.acos().mul(1/Math.PI);this._iesTextureNode=lc(s,go(e,0),0),i=this._iesTextureNode.r}else i=super.getSpotAttenuation(e,t);return i}update(e){super.update(e),null!==this._iesTextureNode&&this.light.iesMap&&(this._iesTextureNode.value=this.light.iesMap)}}class Qx extends sx{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let e=0;e<9;e++)t.push(new Wt);this.lightProbe=mc(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=nx(xd,this.lightProbe);e.context.irradiance.addAssign(t)}}const Zx=ao(([e,t])=>{const s=e.abs().sub(t);return Eh(kh(s,0)).add(Uh(kh(s.x,s.y),0))});class Jx extends Yx{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=co(0),s=this.penumbraCosNode,i=__(this.light).mul(e.context.positionWorld||od);return ho(i.w.greaterThan(0),()=>{const e=i.xyz.div(i.w),r=Zx(e.xy.sub(go(.5)),go(.5)),n=Al(-1,Ml(1,xh(s)).sub(1));t.assign(Zh(r.mul(-2).mul(n)))}),t}}const ev=new ps,tv=new ps;let sv=null;class iv extends sx{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=yl(new Wt).setGroup(ml),this.halfWidth=yl(new Wt).setGroup(ml),this.updateType=Jn}update(e){super.update(e);const{light:t}=this,s=e.camera.matrixWorldInverse;tv.identity(),ev.copy(t.matrixWorld),ev.premultiply(s),tv.extractRotation(ev),this.halfWidth.value.set(.5*t.width,0,0),this.halfHeight.value.set(0,.5*t.height,0),this.halfWidth.value.applyMatrix4(tv),this.halfHeight.value.applyMatrix4(tv)}setupDirectRectArea(e){let t,s;e.isAvailable("float32Filterable")?(t=lc(sv.LTC_FLOAT_1),s=lc(sv.LTC_FLOAT_2)):(t=lc(sv.LTC_HALF_1),s=lc(sv.LTC_HALF_2));const{colorNode:i,light:r}=this;return{lightColor:i,lightPosition:v_(r),halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:s}}static setLTC(e){sv=e}}class rv{parseFunction(){Et("Abstract function.")}}class nv{constructor(e,t,s="",i=""){this.type=e,this.inputs=t,this.name=s,this.precision=i}getCode(){Et("Abstract function.")}}nv.isNodeFunction=!0;const av=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,ov=/[a-z_0-9]+/gi,lv="#pragma main";class hv extends nv{constructor(e){const{type:t,inputs:s,name:i,precision:r,inputsCode:n,blockCode:a,headerCode:o}=(e=>{const t=(e=e.trim()).indexOf(lv),s=(-1!==t?e.slice(t+12):e).replace(/^(?:\s*\/\/[^\r\n]*|\s*\/\*[\s\S]*?\*\/|\s*)+/,""),i=s.match(av);if(null!==i&&5===i.length){const r=i[4],n=[];let a=null;for(;null!==(a=ov.exec(r));)n.push(a);const o=[];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];o.push(new Wx(s,r,i,t,e))}const h=s.substring(i[0].length),u=void 0!==i[3]?i[3]:"";return{type:i[2],inputs:o,name:u,precision:void 0!==i[1]?i[1]:"",inputsCode:r,blockCode:h,headerCode:-1!==t?e.slice(0,t):""}}throw new Error("THREE.FunctionNode: Function is not a GLSL code.")})(e);super(t,s,i,r),this.inputsCode=n,this.blockCode=a,this.headerCode=o}getCode(e=this.name){let t;const s=this.blockCode;if(""!==s){const{type:i,inputsCode:r,headerCode:n,precision:a}=this;let o=`${i} ${e} ( ${r.trim()} )`;""!==a&&(o=`${a} ${o}`),t=n+o+s}else t="";return t}}class uv extends rv{parseFunction(e){return new hv(e)}}const cv=[],dv=[],pv=yl(0,"int").setGroup(ml);class mv extends rb{constructor(e,t){super(),this.renderer=e,this.backend=t,this.nodeFrame=new jx,this.nodeBuilderCache=new Map,this.callHashCache=new Zy,this.groupsData=new Zy,this._buildQueue=[],this._buildInProgress=!1,this.cacheLib={}}updateGroup(e){const t=e.groupNode;if(t.updateType===ea)return!0;cv[0]=t,cv[1]=e;let s=this.groupsData.get(cv);return void 0===s&&this.groupsData.set(cv,s={}),cv[0]=null,cv[1]=null,s.version!==t.version&&(s.version=t.version,!0)}getForRenderCacheKey(e){return e.initialCacheKey}_createNodeBuilder(e,t){const s=this.backend.createNodeBuilder(e.object,this.renderer),i=this.renderer.debug.onNodeBuilderCreated;return null!==i&&i(s,e),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}getForRender(e,t=!1){const s=this.get(e);let i=s.nodeBuilderState;if(void 0===i){const{nodeBuilderCache:r}=this,n=this.getForRenderCacheKey(e);if(i=r.get(n),void 0===i){const a=async()=>{let s=this._createNodeBuilder(e,e.material);try{t?await s.buildAsync():s.build()}catch(i){s=this._createNodeBuilder(e,new hf),t?await s.buildAsync():s.build(),At("TSL: "+i)}return s};if(t)return a().then(e=>(i=this._createNodeBuilderState(e),r.set(n,i),i.usedTimes++,s.nodeBuilderState=i,i));{let t=this._createNodeBuilder(e,e.material);try{t.build()}catch(s){t=this._createNodeBuilder(e,new hf),t.build();let i=s.stackTrace;!i&&s.stack&&(i=new In(s.stack)),At("TSL: "+s,i)}i=this._createNodeBuilderState(t),r.set(n,i)}}i.usedTimes++,s.nodeBuilderState=i}return i}getForRenderAsync(e){const t=this.getForRender(e,!0);return t.then?t:Promise.resolve(t)}getForRenderDeferred(e){const t=this.get(e);if(void 0!==t.nodeBuilderState)return t.nodeBuilderState;const s=this.getForRenderCacheKey(e),i=this.nodeBuilderCache.get(s);return void 0!==i?(i.usedTimes++,t.nodeBuilderState=i,i):(!0!==t.pendingBuild&&(t.pendingBuild=!0,this._buildQueue.push(()=>this.getForRenderAsync(e).then(()=>{t.pendingBuild=!1})),this._processBuildQueue()),null)}_processBuildQueue(){if(this._buildInProgress||0===this._buildQueue.length)return;this._buildInProgress=!0;this._buildQueue.shift()().then(()=>{this._buildInProgress=!1,this._processBuildQueue()})}delete(e){if(e.isRenderObject){const t=this.get(e).nodeBuilderState;void 0!==t&&(t.usedTimes--,0===t.usedTimes&&this.nodeBuilderCache.delete(this.getForRenderCacheKey(e)))}return super.delete(e)}getForCompute(e,t=!1){const s=this.get(e);let i=s.nodeBuilderState;if(void 0===i||s.version!==e.version){const r=this.backend.createNodeBuilder(null,this.renderer);r.compute=e;const n=this.renderer.debug.onNodeBuilderCreated;if(null!==n&&n(r,e),t)return r.buildAsync().then(()=>(i=this._createNodeBuilderState(r),s.nodeBuilderState=i,s.version=e.version,i));r.build(),i=this._createNodeBuilderState(r),s.nodeBuilderState=i,s.version=e.version}return i}getForComputeAsync(e){const t=this.getForCompute(e,!0);return t.then?t:Promise.resolve(t)}_createNodeBuilderState(e){return new ux(e.vertexShader,e.fragmentShader,e.computeShader,e.getAttributesArray(),e.getBindings(),e.updateNodes,e.updateBeforeNodes,e.updateAfterNodes,e.observer,e.hardwareClipping,e.transforms)}getEnvironmentNode(e){if(!1===this.renderer.lighting.enabled)return null;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){cv[0]=e,cv[1]=t;const s=this.renderer.info.calls,i=this.callHashCache.get(cv)||{};if(i.callId!==s){if(dv.push(this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview?1:0),dv.push(this.renderer.lighting.enabled?1:0),this.renderer.lighting.enabled){dv.push(t.getCacheKey(!0)),dv.push(this.renderer.shadowMap.enabled?1:0),dv.push(this.renderer.shadowMap.type);const s=this.getEnvironmentNode(e);s&&dv.push(s.getCacheKey())}const r=this.getFogNode(e);r&&dv.push(r.getCacheKey()),i.callId=s,i.cacheKey=zn(dv),this.callHashCache.set(cv,i),dv.length=0}return cv[0]=null,cv[1]=null,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||s.mapping===D){if(e.backgroundBlurriness>0||s.mapping===D)return Sy(s);{let e;return e=!0===s.isCubeTexture?Dd(s):lc(s),Cf(e)}}if(!0===s.isTexture)return lc(s,vc.flipY()).setUpdateMatrix(!0);!0!==s.isColor&&At("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);if(void 0===n||i){if(void 0===n&&!0===t.isTexture){const e=()=>{t.removeEventListener("dispose",e);const s=r.get(t);void 0!==s&&(r.delete(t),s.dispose())};t.addEventListener("dispose",e)}n=s(),r.set(t,n)}return 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=Id("color","color",s).setGroup(ml),t=Id("density","float",s).setGroup(ml);return g_(e,f_(t))}if(s.isFog){const e=Id("color","color",s).setGroup(ml),t=Id("near","float",s).setGroup(ml),i=Id("far","float",s).setGroup(ml);return g_(e,m_(t,i))}At("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?Dd(s):!0===s.isTexture?lc(s):void At("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,n=null){const a=this.nodeFrame;return a.renderer=e,a.scene=t,a.object=s,a.camera=i,a.material=r,a.compute=n,a}getNodeFrameForRender(e){return this.getNodeFrame(e.renderer,e.scene,e.object,e.camera,e.material)}getNodeFrameForCompute(e){return this.getNodeFrame(this.renderer,null,null,null,null,e)}getOutputCacheKey(){const e=this.renderer;return e.toneMapping+","+e.currentColorSpace+","+e.xr.isPresenting}getOutputNode(e){const t=this.renderer;let s;return s=e.isArrayTexture?this.backend.isWebGLBackend?lc(e,vc).depth(gc("gl_ViewID_OVR")).renderOutput(t.toneMapping,t.currentColorSpace):lc(e,vc).depth(pv).renderOutput(t.toneMapping,t.currentColorSpace):lc(e,vc).renderOutput(t.toneMapping,t.currentColorSpace),s}setOutputLayerIndex(e){pv.value=e}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)}updateBeforeForCompute(e){const t=this.getForCompute(e);for(const s of t.updateBeforeNodes)this.getNodeFrameForCompute(e).updateBeforeNode(s)}updateAfterForCompute(e){const t=this.getForCompute(e);for(const s of t.updateAfterNodes)this.getNodeFrameForCompute(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 jx,this.nodeBuilderCache=new Map,this.cacheLib={}}}const fv=new sr;let gv=0;class yv{constructor(e=null){this.id=gv++,this.version=0,this.clipIntersection=null,this.cacheKey="",this.shadowPass=!1,this.viewMatrix=new ps,this.viewNormalMatrix=new Xt,this.clippingGroupContexts=new WeakMap,this.intersectionPlanes=[],this.unionPlanes=[],this.parentVersion=null,null!==e&&(this.viewMatrix=e.viewMatrix,this.viewNormalMatrix=e.viewNormalMatrix,this.clippingGroupContexts=e.clippingGroupContexts,this.shadowPass=e.shadowPass)}projectPlanes(e,t,s){const i=e.length;for(let r=0;r<i;r++){fv.copy(e[r]).applyMatrix4(this.viewMatrix,this.viewNormalMatrix);const i=t[s+r],n=fv.normal;i.x=-n.x,i.y=-n.y,i.z=-n.z,i.w=fv.constant}}updateGlobal(e,t){this.shadowPass=null!==e.overrideMaterial&&e.overrideMaterial.isShadowPassMaterial,this.viewMatrix.copy(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,a;if(this.clipIntersection?(n=this.intersectionPlanes,a=e.intersectionPlanes.length):(n=this.unionPlanes,a=e.unionPlanes.length),n.length!==a+r){n.length=a+r;for(let e=0;e<r;e++)n[a+e]=new us;s=!0}this.projectPlanes(i,n,a),s&&(this.version++,this.cacheKey=`${this.id}:${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 yv(this),this.clippingGroupContexts.set(e,t)),t.update(this,e),t}get unionClippingCount(){return this.unionPlanes.length}}class bv{constructor(e,t,s){this.bundleGroup=e,this.camera=t,this.renderContext=s}}const _v=[];class xv{constructor(){this.bundles=new Zy}get(e,t,s){const i=this.bundles;_v[0]=e,_v[1]=t,_v[2]=s;let r=i.get(_v);return void 0===r&&(r=new bv(e,t,s),i.set(_v,r)),_v[0]=null,_v[1]=null,_v[2]=null,r}dispose(){this.bundles=new Zy}}class vv{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))Et(`Redefinition of node ${t}`);else{if("function"!=typeof e)throw new Error(`THREE.NodeLibrary: Node class ${e.name} is not a class.`);if("function"==typeof t||"object"==typeof t)throw new Error(`THREE.NodeLibrary: Base class ${t} is not a class.`);s.set(t,e)}}addClass(e,t,s){if(s.has(t))Et(`Redefinition of node ${t.name}`);else{if("function"!=typeof e)throw new Error(`THREE.NodeLibrary: Node class ${e.name} is not a class.`);if("function"!=typeof t)throw new Error(`THREE.NodeLibrary: Base class ${t.name} is not a class.`);s.set(t,e)}}}const Tv=new C_;class Sv{constructor(){this.enabled=!0,this._cache=[],this._lightsNodeMap=new WeakMap}createNode(e=[]){return(new C_).setLights(e)}getNode(e){if(!0!==e.isScene&&!0!==e.isGroup)return Tv;let t=this._lightsNodeMap.get(e);return void 0===t&&(t=this.createNode(),this._lightsNodeMap.set(e,t)),t}beginRender(e){this._cache.push(this.getNode(e).getLights())}finishRender(e){this.getNode(e).setLights(this._cache.pop())}}class wv extends cs{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 Mv=new Wt,Ev=new Wt,Av=new WeakMap;class Nv extends Pt{constructor(e,t=!1){super(),this.enabled=!1,this.isPresenting=!1,this.cameraAutoUpdate=!0,this._renderer=e,this._cameraL=new dn,this._cameraL.viewport=new us,this._cameraL.matrixWorldAutoUpdate=!1,this._cameraR=new dn,this._cameraR.viewport=new us,this._cameraR.matrixWorldAutoUpdate=!1,this._cameras=[this._cameraL,this._cameraR],this._cameraXR=new En,this._currentDepthNear=null,this._currentDepthFar=null,this._controllers=[],this._controllerInputSources=[],this._xrRenderTarget=null,this._layers=[],this._sessionUsesLayers=!1,this._supportsGlBinding="undefined"!=typeof XRWebGLBinding,this._supportsWebGPUBinding=void 0!==globalThis.XRGPUBinding,this._createXRLayer=Fv.bind(this),this._gl=null,this._currentAnimationContext=null,this._currentAnimationLoop=null,this._currentPixelRatio=null,this._currentSize=new $t,this._currentCameraSettings=null,this._onSessionEvent=Rv.bind(this),this._onSessionEnd=Pv.bind(this),this._onInputSourcesChange=Bv.bind(this),this._onAnimationFrame=Lv.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._webgpuBinding=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(){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&&Et("XRManager: Cannot change framebuffer scale while presenting.")}getReferenceSpaceType(){return this._referenceSpaceType}setReferenceSpaceType(e){this._referenceSpaceType=e,!0===this.isPresenting&&Et("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}getBaseLayer(){return null!==this._glProjLayer?this._glProjLayer:this._glBaseLayer}getBinding(){return null===this._glBinding&&this._supportsGlBinding&&(this._glBinding=new XRWebGLBinding(this._session,this._gl)),this._glBinding}foveateBoundTexture(e){if(null===e||!0!==e.isPostProcessingRenderTarget)return;if(!0!==this.isPresenting)return;if(null===this._glProjLayer)return;const t=this._renderer.backend;if(void 0===t||!0!==t.isWebGLBackend)return;if(null===t.state)return;const s=this._renderer.getOutputRenderTarget();if(null===s||!0!==s.isXRRenderTarget)return;const i=this.getBinding();if(null===i||"function"!=typeof i.foveateBoundTexture)return;this._renderer._textures.updateRenderTarget(e);const{textureGPU:r,glTextureType:n}=t.get(e.texture);if(void 0!==r&&void 0!==n&&e._xrFoveationTextureGPU!==r){e._xrFoveationTextureGPU=r,t.state.bindTexture(n,r);try{i.foveateBoundTexture(n,this.getFoveation())}catch(e){Nt(`XRManager: Unable to foveate bound XR post-processing texture. ${e.name}: ${e.message}`)}finally{t.state.unbindTexture()}}}getWebGPUBinding(){return null===this._webgpuBinding&&this._supportsWebGPUBinding&&(this._webgpuBinding=new globalThis.XRGPUBinding(this._session,this._renderer.backend.device)),this._webgpuBinding}_isWebGPUSession(){return!0===this._renderer.backend.isWebGPUBackend&&null!==this._session&&this._session.enabledFeatures.includes("webgpu")}_validateWebGPUSession(){if(!0===this._renderer.backend.isWebGPUBackend&&!1===this._session.enabledFeatures.includes("webgpu"))throw new Error('THREE.XRManager: WebGPU XR sessions require the "webgpu" session feature. Use VRButtonGPU/XRButton with "webgpu" enabled or use a WebGL backend.')}async _initWebGPUSession(e){const t=this.getWebGPUBinding(),s=t.createProjectionLayer({colorFormat:t.getPreferredColorFormat()});this._glProjLayer=s,e.updateRenderState({layers:[s]}),this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType()),this._xrRenderTarget=new cs(s.textureWidth,s.textureHeight,{depth:2,minFilter:G,magFilter:G,depthBuffer:!0,multiview:!1,useArrayDepthTexture:!0,storeMultisampledColorBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1,samples:this._renderer.samples}),this._xrRenderTarget.texture.isArrayTexture=!0,!0===this._useMultiviewIfPossible&&Nt("THREE.XRManager: WebGPU XR does not support multiview yet. Disabling multiview for this XR session."),this._useMultiview=!1}_disposeWebGPUSession(){const e=this._renderer,t=e.backend,s=this._xrRenderTarget;if(null!==s&&!0===t.isWebGPUBackend){e._renderContexts&&e._renderContexts.dispose&&e._renderContexts.dispose(),s.dispose();for(const e of s.textures)t.has(e)&&t.destroyTexture(e);t.delete(s)}}_getWebGPUViewData(e){const t=this.getWebGPUBinding(),s={colorTexture:null,viewDescriptors:[],viewports:[]};for(let i=0;i<e.length;i++){const r=t.getViewSubImage(this._glProjLayer,e[i]);null===s.colorTexture&&(s.colorTexture=r.colorTexture),s.viewports.push(r.viewport),r.getViewDescriptor&&s.viewDescriptors.push(r.getViewDescriptor())}return s}getFrame(){return this._xrFrame}useMultiview(){return this._useMultiview}createQuadLayer(e,t,s,i,r,a,o,l={}){const h=new Vr(e,t),c=new wv(r,a,{format:ae,type:W,depthTexture:new Ir(r,a,l.stencil?te:K,void 0,void 0,void 0,void 0,void 0,void 0,l.stencil?le:oe),stencilBuffer:l.stencil,samples:l.samples??this._renderer.samples,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledColorBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1}),d=new cr({color:16777215,side:0});d.map=c.texture,d.map.offset.y=1,d.map.repeat.y=-1;const p=new Sr(h,d);p.position.copy(s),p.quaternion.copy(i);const m={type:"quad",width:e,height:t,translation:s,quaternion:i,pixelwidth:r,pixelheight:a,samples:c.samples,plane:p,material:d,rendercall:o,renderTarget:c};if(this._layers.push(m),null!==this._session){m.plane.material=new cr({color:16777215,side:0}),m.plane.material.blending=5,m.plane.material.blendEquation=n,m.plane.material.blendSrc=u,m.plane.material.blendDst=u,m.xrlayer=this._createXRLayer(m);const e=this._session.renderState.layers;e.unshift(m.xrlayer),this._session.updateRenderState({layers:e})}else c.isXRRenderTarget=!1;return p}createCylinderLayer(e,t,s,i,r,a,o,l,h={}){const c=new zr(e,e,e*t/s,64,64,!0,Math.PI-t/2,t),d=new wv(a,o,{format:ae,type:W,depthTexture:new Ir(a,o,h.stencil?te:K,void 0,void 0,void 0,void 0,void 0,void 0,h.stencil?le:oe),stencilBuffer:h.stencil,samples:h.samples??this._renderer.samples,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledColorBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1}),p=new cr({color:16777215,side:1});p.map=d.texture,p.map.offset.y=1,p.map.repeat.y=-1;const m=new Sr(c,p);m.position.copy(i),m.quaternion.copy(r);const f={type:"cylinder",radius:e,centralAngle:t,aspectratio:s,translation:i,quaternion:r,pixelwidth:a,pixelheight:o,samples:d.samples,plane:m,material:p,rendercall:l,renderTarget:d};if(this._layers.push(f),null!==this._session){f.plane.material=new cr({color:16777215,side:1}),f.plane.material.blending=5,f.plane.material.blendEquation=n,f.plane.material.blendSrc=u,f.plane.material.blendDst=u,f.xrlayer=this._createXRLayer(f);const e=this._session.renderState.layers;e.unshift(f.xrlayer),this._session.updateRenderState({layers:e})}else d.isXRRenderTarget=!1;return m}renderLayers(){const e=new Wt,t=new jt,s=this._renderer,i=this.isPresenting;this.isPresenting=!1;const r=new $t;s.getSize(r);const n=s.getRenderTarget();for(const i of this._layers){i.renderTarget.isXRRenderTarget=null!==this._session,i.renderTarget._hasExternalTextures=i.renderTarget.isXRRenderTarget;const r=s.contextNode;let n;if(i.renderTarget.isXRRenderTarget&&this._sessionUsesLayers){i.xrlayer.transform=new XRRigidTransform(i.plane.getWorldPosition(e),i.plane.getWorldQuaternion(t));const a=this._glBinding.getSubImage(i.xrlayer,this._xrFrame);s.backend.setXRRenderTargetTextures(i.renderTarget,a.colorTexture,void 0),s._setXRLayerSize(i.renderTarget.width,i.renderTarget.height),n=Av.get(r),void 0===n&&(n=au({getOutput:e=>qu(e,s.toneMapping,s.outputColorSpace),...r.getFlowContextData()}),Av.set(r,n))}else n=r;s.contextNode=n,s.setRenderTarget(i.renderTarget),i.rendercall(),s.contextNode=r}s.setRenderTarget(n),s._setXRLayerSize(r.x,r.y),this.isPresenting=i}getSession(){return this._session}async setSession(e){const t=this._renderer;!1===t.initialized&&await t.init(),this._gl=t.getContext();const s=this._gl;if(this._session=e,null!==e){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),this._validateWebGPUSession(),this._currentPixelRatio=t.getPixelRatio(),t.getSize(this._currentSize),this._currentAnimationContext=t._animation.getContext(),this._currentAnimationLoop=t._animation.getAnimationLoop(),t._animation.stop(),this._isWebGPUSession())await this._initWebGPUSession(e);else if(!0===this._supportsLayers){let i=null,r=null,a=null;const o=s.getContextAttributes();await t.backend.makeXRCompatible(),this.setFoveation(this.getFoveation()),t.depth&&(a=t.stencil?s.DEPTH24_STENCIL8:s.DEPTH_COMPONENT24,i=t.stencil?le:oe,r=t.stencil?te:K);const l={colorFormat:s.RGBA8,depthFormat:a,scaleFactor:this._framebufferScaleFactor,clearOnAccess:!1};this._useMultiviewIfPossible&&t.hasFeature("OVR_multiview2")&&(l.textureType="texture-array",this._useMultiview=!0),this._glBinding=this.getBinding();const h=this._glBinding.createProjectionLayer(l),c=[h];this._glProjLayer=h,t.setPixelRatio(1),t._setXRLayerSize(h.textureWidth,h.textureHeight);const d=this._useMultiview?2:1,p=new Ir(h.textureWidth,h.textureHeight,r,void 0,void 0,void 0,void 0,void 0,void 0,i,d);if(this._xrRenderTarget=new wv(h.textureWidth,h.textureHeight,{format:ae,type:W,colorSpace:t.outputColorSpace,depthTexture:p,stencilBuffer:t.stencil,samples:o.antialias?4:0,resolveDepthBuffer:!1===h.ignoreDepthValues,resolveStencilBuffer:!1===h.ignoreDepthValues,storeMultisampledColorBuffer:!1,storeMultisampledDepthBuffer:!1===h.ignoreDepthValues,storeMultisampledStencilBuffer:!1===h.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 cr({color:16777215,side:"cylinder"===e.type?1:0}),e.plane.material.blending=5,e.plane.material.blendEquation=n,e.plane.material.blendSrc=u,e.plane.material.blendDst=u,e.xrlayer=this._createXRLayer(e),c.unshift(e.xrlayer);e.updateRenderState({layers:c})}else{await t.backend.makeXRCompatible(),this.setFoveation(this.getFoveation());const i={antialias:t.currentSamples>0,alpha:!0,depth:t.depth,stencil:t.stencil,framebufferScaleFactor:this.getFramebufferScaleFactor()},r=new XRWebGLLayer(e,s,i);this._glBaseLayer=r,e.updateRenderState({baseLayer:r}),t.setPixelRatio(1),t._setXRLayerSize(r.framebufferWidth,r.framebufferHeight),this._xrRenderTarget=new wv(r.framebufferWidth,r.framebufferHeight,{format:ae,type:W,colorSpace:t.outputColorSpace,stencilBuffer:t.stencil}),this._xrRenderTarget._isOpaqueFramebuffer=!0,this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType())}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,a=this._cameraR;r.near=a.near=n.near=s,r.far=a.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=-5&r.layers.mask,a.layers.mask=-3&r.layers.mask;const o=e.parent,l=r.cameras;Cv(r,o);for(let e=0;e<l.length;e++)Cv(l[e],o);2===l.length?function(e,t,s){Mv.setFromMatrixPosition(t.matrixWorld),Ev.setFromMatrixPosition(s.matrixWorld);const i=Mv.distanceTo(Ev),r=t.projectionMatrix.elements,n=s.projectionMatrix.elements,a=r[14]/(r[10]-1),o=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=a*u,p=a*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=a+m,s=o+m,r=d-f,n=p+(i-f),u=l*o/s*t,c=h*o/s*t;e.projectionMatrix.makePerspective(r,n,u,c,t,s),e.projectionMatrixInverse.copy(e.projectionMatrix).invert()}}(r,n,a):r.projectionMatrix.copy(n.projectionMatrix),null===this._currentCameraSettings&&e.isPerspectiveCamera&&(this._currentCameraSettings={camera:e,fov:e.fov,zoom:e.zoom}),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*Dt*Math.atan(1/e.projectionMatrix.elements[5]),e.zoom=1)}(e,r,o)}_getController(e){let t=this._controllers[e];return void 0===t&&(t=new $s,this._controllers[e]=t),t}}function Cv(e,t){null===t?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}function Rv(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 Pv(){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._disposeWebGPUSession(),this._session=null,this._xrRenderTarget=null,this._glBinding=null,this._webgpuBinding=null,this._glBaseLayer=null,this._glProjLayer=null,!0===this._sessionUsesLayers)for(const e of this._layers)e.renderTarget=new wv(e.pixelwidth,e.pixelheight,{format:ae,type:W,depthTexture:new Ir(e.pixelwidth,e.pixelheight,e.stencilBuffer?te:K,void 0,void 0,void 0,void 0,void 0,void 0,e.stencilBuffer?le:oe),stencilBuffer:e.stencilBuffer,samples:e.samples,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledColorBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!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;if(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),null!==this._currentCameraSettings){const e=this._currentCameraSettings.camera;e.fov=this._currentCameraSettings.fov,e.zoom=this._currentCameraSettings.zoom,e.updateProjectionMatrix(),this._currentCameraSettings=null}this.dispatchEvent({type:"sessionend"})}function Bv(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 a=t[n];a&&a.connect(r)}}function Fv(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 Lv(e,t){if(void 0===t)return;const s=this._cameraXR,i=this._renderer,r=i.backend,n=this._glBaseLayer,a=this.getReferenceSpace(),o=t.getViewerPose(a);if(this._xrFrame=t,null!==o){const e=o.views,t=this._isWebGPUSession()?this._getWebGPUViewData(e):null;null!==this._glBaseLayer&&null===t&&r.setXRTarget(n.framebuffer);let a=!1;e.length!==s.cameras.length&&(s.cameras.length=0,a=!0);for(let i=0;i<e.length;i++){const o=e[i];let l;if(null!==t)l=t.viewports[i];else if(!0===this._supportsLayers){const e=this._glBinding.getViewSubImage(this._glProjLayer,o);l=e.viewport,0===i&&r.setXRRenderTargetTextures(this._xrRenderTarget,e.colorTexture,this._glProjLayer.ignoreDepthValues&&!this._useMultiview?void 0:e.depthStencilTexture)}else l=n.getViewport(o);let h=this._cameras[i];void 0===h&&(h=new dn,h.layers.enable(i),h.viewport=new us,h.matrixWorldAutoUpdate=!1,this._cameras[i]=h),h.matrix.fromArray(o.transform.matrix),h.matrix.decompose(h.position,h.quaternion,h.scale),h.projectionMatrix.fromArray(o.projectionMatrix),h.projectionMatrixInverse.copy(h.projectionMatrix).invert(),h.viewport.set(l.x,l.y,l.width,l.height),0===i&&(s.matrix.copy(h.matrix),s.matrix.decompose(s.position,s.quaternion,s.scale)),!0===a&&s.cameras.push(h)}null!==t&&null!==t.colorTexture&&r.setXRRenderTargetTextures(this._xrRenderTarget,t.colorTexture,t.viewDescriptors),i.setOutputRenderTarget(this._xrRenderTarget);const l=i._getFrameBufferTarget();null!==t&&(this._xrRenderTarget.samples=null===l?i.samples:0,this._xrRenderTarget.depthBuffer=null===l),i.xr.foveateBoundTexture(l)}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,a)}this._currentAnimationLoop&&this._currentAnimationLoop(e,t),t.detectedPlanes&&this.dispatchEvent({type:"planesdetected",data:t}),this._xrFrame=null}class Dv extends Pt{constructor(e){super(),this.domElement=e,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new us(0,0,this._width,this._height),this._scissor=new us(0,0,this._width,this._height),this._scissorTest=!1,this.colorTexture=new Dr,this.depthTexture=new Ir}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 a=this._viewport;e.isVector4?a.copy(e):a.set(e,t,s,i),a.minDepth=r,a.maxDepth=n}_dispatchResize(){this.dispatchEvent({type:"resize"})}dispose(){this.dispatchEvent({type:"dispose"})}}const Ov=new Ks,Iv=new $t,Uv=new us,kv=new Rr,zv=new Br,Vv=new ps,Gv=new us,$v={[s]:1,[i]:0,[r]:2};class jv{constructor(e,t={}){this.isRenderer=!0;const{logarithmicDepthBuffer:s=!1,reversedDepthBuffer:i=!1,alpha:r=!0,depth:n=!0,stencil:a=!1,antialias:o=!1,samples:l=0,getFallback:h=null,outputBufferType:u=Z,multiview:c=!1}=t;this.backend=e,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.alpha=r,this.logarithmicDepthBuffer=s,this.reversedDepthBuffer=i,this.outputColorSpace=Ze,this.toneMapping=0,this.toneMappingExposure=1,this.sortObjects=!0,this.depth=n,this.stencil=a,this.info=new fb,this.contextNode=au(),this.library=new vv,this.lighting=new Sv,this._samples=l||(!0===o?4:0),this._onCanvasTargetResize=this._onCanvasTargetResize.bind(this),this._canvasTarget=new Dv(e.getDomElement()),this._canvasTarget.addEventListener("resize",this._onCanvasTargetResize),this._canvasTarget.isDefaultCanvasTarget=!0,this._inspector=new Yu,this._inspector.setRenderer(this),this._getFallback=h,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._quadCache=new Map,this._currentRenderContext=null,this._opaqueSort=null,this._transparentSort=null,this._frameBufferTargets=new Map;const d=!0===this.alpha?0:1;this._clearColor=new Ib(0,0,0,d),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.onError=this._onError,this._outputBufferType=u,this._cacheShadowNodes=new WeakMap,this._initialized=!1,this._callDepth=-1,this._initPromise=null,this._compilationPromises=null,this._isPreCompiling=!1,this._currentSourceMaterial=null,this.transparent=!0,this.opaque=!0,this.shadowMap={enabled:!1,transmitted:!1,type:1},this.xr=new Nv(this,c),this.debug={checkShaderErrors:!0,diagnostics:{keywords:!1},onNodeBuilderCreated:null,onShaderError:null,getShaderAsync:async(e,t,s)=>{await this.compileAsync(s,t,e);const i=this.needsFrameBufferTarget&&null===this._renderTarget?this._getFrameBufferTarget():this._renderTarget||this._outputRenderTarget,r=this._renderLists.get(e,t,this.lighting),n=this._renderContexts.get(i,this._mrt),a=e.overrideMaterial||s.material,o=this._objects.get(s,a,e,t,r.lightsNode,n,n.clippingContext),{fragmentShader:l,vertexShader:h}=o.getNodeBuilderState();return{fragmentShader:l,vertexShader:h}}}}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 mv(this,s),this._animation=new Qy(this,this._nodes,this.info),this._attributes=new ub(s,this.info),this._background=new ox(this,this._nodes),this._geometries=new mb(this._attributes,this.info),this._textures=new Ob(this,s,this.info),this._pipelines=new vb(s,this._nodes,this.info),this._bindings=new Tb(s,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new ib(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new Rb,this._bundles=new xv,this._renderContexts=new Lb(this),this._animation.start(),this._initialized=!0,e(this)})),this._initPromise}get domElement(){return this._canvasTarget.domElement}get coordinateSystem(){return this.backend.coordinateSystem}async compileAsync(e,t,s=null,i=null){if(!0===this._isDeviceLost)return;!1===this._initialized&&await this.init(),2===this.shadowMap.type&&(Et("WebGPURenderer: PCFSoftShadowMap has been removed. Using PCFShadowMap instead."),this.shadowMap.type=1);const r=this._nodes.nodeFrame,n=r.renderId,a=this._currentRenderContext,o=this._currentRenderObjectFunction,l=this._handleObjectFunction,h=this._compilationPromises;null===s&&(s=e);const u=!0===e.isScene?e:!0===s.isScene?s:Ov,c=this.needsFrameBufferTarget&&null===this._renderTarget,d=this._renderTarget||this._outputRenderTarget,p=!0===this.xr.isPresenting&&this.isOutputTarget,m=c?this._getFrameBufferTarget():d,f=this._renderContexts.get(m,this._mrt),g=this._activeMipmapLevel,y=[];this._currentRenderContext=f,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=y,r.renderId++,r.update(),f.depth=this.depth,f.stencil=this.stencil,f.clippingContext||(f.clippingContext=new yv),f.clippingContext.updateGlobal(u,t),!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),t=this._updateCamera(t,p),u.onBeforeRender(this,e,t,m),Vv.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),t.isArrayCamera?zv.setFromArrayCamera(t):kv.setFromProjectionMatrix(Vv,t.coordinateSystem,t.reversedDepth);const b=this._renderLists.get(u,t,this.lighting);if(b.begin(),this._projectObject(e,t,0,b,f.clippingContext),s!==e&&s.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&b.pushLight(e)}),b.finish(),null!==m){this._textures.updateRenderTarget(m,g);const e=this._textures.get(m);f.textures=e.textures,f.depthTexture=e.depthTexture}else f.textures=null,f.depthTexture=null;s!==e?this._background.update(s,b,f):this._background.update(u,b,f);const _=b.opaque,x=b.transparent,v=b.transparentDoublePass,T=b.lightsNode;!0===this.opaque&&_.length>0&&this._renderObjects(_,t,u,T),!0===this.transparent&&x.length>0&&this._renderTransparents(x,v,t,u,T),r.renderId=n,this._currentRenderContext=a,this._currentRenderObjectFunction=o,this._handleObjectFunction=l,this._compilationPromises=h;const S=y.length;let w=0;for(const e of y){const t=this._objects.get(e.object,e.material,e.scene,e.camera,e.lightsNode,e.renderContext,e.clippingContext,e.passId);t.drawRange=e.object.geometry.drawRange,t.group=e.group,await this._nodes.getForRenderAsync(t),this._isPreCompiling=!0,this._nodes.updateBefore(t),this._geometries.updateForRender(t),this._nodes.updateForRender(t),this._bindings.updateForRender(t),this._isPreCompiling=!1;const s=[];this._pipelines.getForRender(t,s),s.length>0&&await Promise.all(s),this._isPreCompiling=!0,this._nodes.updateAfter(t),this._isPreCompiling=!1,w++,null!==i&&i(new ProgressEvent("progress",{lengthComputable:!0,loaded:w,total:S})),await Ct()}}async compileComputeAsync(e,t=null){if(!0===this._isDeviceLost)return;!1===this._initialized&&await this.init();const s=Array.isArray(e)?e:[e];if(0===s.length||s.some(e=>null==e||!0!==e.isComputeNode))throw new Error("THREE.Renderer: .compileComputeAsync() expects a ComputeNode.");const i=s.length;let r=0;const n=this._pipelines,a=this._bindings,o=this._nodes;for(const e of s){if(!1===n.has(e)){const t=()=>{e.removeEventListener("dispose",t),n.delete(e),a.deleteForCompute(e),o.delete(e)};e.addEventListener("dispose",t);const s=e.onInitFunction;null!==s&&s.call(e,{renderer:this})}await o.getForComputeAsync(e),o.updateBeforeForCompute(e),o.updateForCompute(e),a.updateForCompute(e);const s=a.getForCompute(e),l=[];n.getForCompute(e,s,l),await Promise.all(l),o.updateAfterForCompute(e),r++,null!==t&&t(new ProgressEvent("progress",{lengthComputable:!0,loaded:r,total:i})),r<i&&await Ct()}}async renderAsync(e,t){Nt('Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.render(e,t)}async waitForGPU(){At("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=td,t.modelNormalViewMatrix=sd):this.highPrecision&&(delete t.modelViewMatrix,delete t.modelNormalViewMatrix)}get highPrecision(){const e=this.contextNode.value;return e.modelViewMatrix===td&&e.modelNormalViewMatrix===sd}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getOutputBufferType(){return this._outputBufferType}getColorBufferType(){return Nt('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}`),At(t),this._isDeviceLost=!0}_onError(e){let t=`WebGPURenderer: Uncaptured ${e.api} ${e.type}`;e.message&&(t+=`: ${e.message}`),At(t)}_bundleNeedsUpdate(e,t){return void 0===t.bundleGPU||e.version!==t.version}_renderBundle(e,t,s){const{bundleGroup:i,camera:r,renderList:n}=e,a=this._currentRenderContext,o=this._bundles.get(i,r,a),l=this.backend.get(o);if(this._bundleNeedsUpdate(i,l)){this.backend.beginBundle(a),this._currentRenderBundle=o;const{transparentDoublePass:e,transparent:h,opaque:u}=n;!0===this.opaque&&u.length>0&&this._renderObjects(u,r,t,s),!0===this.transparent&&h.length>0&&this._renderTransparents(h,e,r,t,s),this._currentRenderBundle=null,this.backend.finishBundle(a,o),l.version=i.version}else{const{renderObjects:e}=l;for(let t=0,s=e.length;t<s;t++){const s=e[t],i=this._nodes.needsRefresh(s);i===xt?(this._nodes.updateBefore(s),this._geometries.updateForRender(s),this._nodes.updateForRender(s),this._bindings.updateForRender(s),this._nodes.updateAfter(s)):i===_t&&(this._nodes.updateBefore(s),this._nodes.updateForRender(s),this._bindings.updateSharedForRender(s),this._nodes.updateAfter(s))}}this.backend.addBundle(a,o)}render(e,t){if(!1===this._initialized)throw new Error('THREE.Renderer: .render() called before the backend is initialized. Use "await renderer.init();" before rendering.');this._renderScene(e,t)}get initialized(){return this._initialized}_renderOutputLayers(e,t){if(!0===this.backend.isWebGLBackend&&!0===t.multiview||!0!==t.texture.isArrayTexture||t.texture.image.depth<=1)return void this._renderScene(e,e.camera,!1);const s=this._activeCubeFace;try{for(let s=0;s<t.texture.image.depth;s++)this._nodes.setOutputLayerIndex(s),this._activeCubeFace=s,this._renderScene(e,e.camera,!1)}finally{this._nodes.setOutputLayerIndex(0),this._activeCubeFace=s}}_getFrameBufferTarget(){if(!1===this.needsFrameBufferTarget)return null;const{width:e,height:t}=this.getDrawingBufferSize(Iv),{depth:s,stencil:i}=this,r=this._outputRenderTarget||this._canvasTarget;let n=this._frameBufferTargets.get(r);if(void 0===n){n=new cs(e,t,{depthBuffer:s,stencilBuffer:i,type:this._outputBufferType,format:ae,colorSpace:Jt.workingColorSpace,generateMipmaps:!1,minFilter:G,magFilter:G,samples:this.samples}),n.isPostProcessingRenderTarget=!0;const a=()=>{r.removeEventListener("dispose",a),n.dispose(),this._frameBufferTargets.delete(r)};r.addEventListener("dispose",a),this._frameBufferTargets.set(r,n)}const a=this.getOutputRenderTarget();n.depthBuffer=s,n.stencilBuffer=i,null!==a?n.setSize(a.width,a.height,a.depth):n.setSize(e,t,1);const o=this._outputRenderTarget?this._outputRenderTarget.viewport:r._viewport,l=this._outputRenderTarget?this._outputRenderTarget.scissor:r._scissor,h=this._outputRenderTarget?1:r._pixelRatio,u=this._outputRenderTarget?this._outputRenderTarget.scissorTest:r._scissorTest;return n.viewport.copy(o),n.scissor.copy(l),n.viewport.multiplyScalar(h),n.scissor.multiplyScalar(h),n.scissorTest=u,n.multiview=null!==a&&a.multiview,n.useArrayDepthTexture=null!==a&&a.useArrayDepthTexture,n.resolveDepthBuffer=null===a||a.resolveDepthBuffer,n.resolveStencilBuffer=null===a||a.resolveStencilBuffer,n.storeMultisampledColorBuffer=null===a||a.storeMultisampledColorBuffer,n.storeMultisampledDepthBuffer=null===a||a.storeMultisampledDepthBuffer,n.storeMultisampledStencilBuffer=null===a||a.storeMultisampledStencilBuffer,n._autoAllocateDepthBuffer=null!==a&&a._autoAllocateDepthBuffer,n}_renderScene(e,t,s=!0){if(!0===this._isDeviceLost)return;2===this.shadowMap.type&&(Et("WebGPURenderer: PCFSoftShadowMap has been removed. Using PCFShadowMap instead."),this.shadowMap.type=1);const i=s?this._getFrameBufferTarget():null,r=this._nodes.nodeFrame,n=r.renderId,a=this._currentRenderContext,o=this._currentRenderObjectFunction,l=this._handleObjectFunction;this.lighting.beginRender(e),this._callDepth++;const h=!0===e.isScene?e:Ov,u=this._renderTarget||this._outputRenderTarget,c=!0===this.xr.isPresenting&&this.isOutputTarget,d=this._activeCubeFace,p=this._activeMipmapLevel;let m;if(null!==i?(m=i,this.setRenderTarget(m)):m=u,null!==m&&!0===m.depthBuffer){const e=this._textures.get(m);!0!==e.depthInitialized&&((!1===this.autoClear||!0===this.autoClear&&!1===this.autoClearDepth)&&this.clearDepth(),e.depthInitialized=!0)}const f=this._renderContexts.get(m,this._mrt,this._callDepth);this._currentRenderContext=f,this._currentRenderObjectFunction=this._renderObjectFunction||this.renderObject,this._handleObjectFunction=this._renderObjectDirect,this.info.calls++,this.info.render.calls++,this.info.render.frameCalls++,r.renderId=this.info.calls,this.backend.updateTimeStampUID(f),this.inspector.beginRender(this.backend.getTimestampUID(f),e,t,m),!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),t=this._updateCamera(t,c);const g=this._canvasTarget;let y=g._viewport,b=g._scissor,_=g._pixelRatio;null!==m&&(y=m.viewport,b=m.scissor,_=1),this.getDrawingBufferSize(Iv),Uv.set(0,0,Iv.width,Iv.height);const x=void 0===y.minDepth?0:y.minDepth,v=void 0===y.maxDepth?1:y.maxDepth;f.viewportValue.copy(y).multiplyScalar(_).floor(),f.viewportValue.width>>=p,f.viewportValue.height>>=p,f.viewportValue.minDepth=x,f.viewportValue.maxDepth=v,f.viewport=!1===f.viewportValue.equals(Uv),f.scissorValue.copy(b).multiplyScalar(_).floor(),f.scissor=g._scissorTest&&!1===f.scissorValue.equals(Uv),f.scissorValue.width>>=p,f.scissorValue.height>>=p,f.clippingContext||(f.clippingContext=new yv),f.clippingContext.updateGlobal(h,t),h.onBeforeRender(this,e,t,m),Vv.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),t.isArrayCamera?zv.setFromArrayCamera(t):kv.setFromProjectionMatrix(Vv,t.coordinateSystem,t.reversedDepth),this._renderLists.update(r.frameId);const T=this._renderLists.get(e,t,this.lighting);if(T.begin(),this._projectObject(e,t,0,T,f.clippingContext),T.finish(),!0===this.sortObjects&&T.sort(this._opaqueSort,this._transparentSort),null!==m){this._textures.updateRenderTarget(m,p);const e=this._textures.get(m);f.textures=e.textures,f.depthTexture=e.depthTexture,f.width=e.width,f.height=e.height,f.renderTarget=m,f.depth=m.depthBuffer,f.stencil=m.stencilBuffer}else f.textures=null,f.depthTexture=null,f.width=Iv.width,f.height=Iv.height,f.depth=this.depth,f.stencil=this.stencil;f.width>>=p,f.height>>=p,f.activeCubeFace=d,f.activeMipmapLevel=p,f.occlusionQueryCount=T.occlusionQueryCount,f.fullscreenPass=!0===e.isQuadMesh,f.scissorValue.max(Gv.set(0,0,0,0)),f.scissorValue.x+f.scissorValue.width>f.width&&(f.scissorValue.width=Math.max(f.width-f.scissorValue.x,0)),f.scissorValue.y+f.scissorValue.height>f.height&&(f.scissorValue.height=Math.max(f.height-f.scissorValue.y,0)),this._background.update(h,T,f),f.camera=t,this.backend.beginRender(f);const{bundles:S,lightsNode:w,transparentDoublePass:M,transparent:E,opaque:A}=T;return S.length>0&&this._renderBundles(S,h,w),!0===this.opaque&&A.length>0&&this._renderObjects(A,t,h,w),!0===this.transparent&&E.length>0&&this._renderTransparents(E,M,t,h,w),this.backend.finishRender(f),r.renderId=n,this._currentRenderContext=a,this._currentRenderObjectFunction=o,this._handleObjectFunction=l,this.lighting.finishRender(e),this._callDepth--,null!==i&&(this.setRenderTarget(u,d,p),this._renderOutput(m)),h.onAfterRender(this,e,t,m),this.inspector.finishRender(this.backend.getTimestampUID(f)),f}_setXRLayerSize(e,t){this._canvasTarget._width=e,this._canvasTarget._height=t,this.setViewport(0,0,e,t)}_renderOutput(e){const t=this._nodes.getOutputCacheKey();let s,i=this._quadCache.get(e.texture);if(void 0===i){s=new qb(new hf),s.name="Output Color Transform",s.material.name="outputColorTransform",s.material.fragmentNode=this._nodes.getOutputNode(e.texture),i={quad:s,cacheKey:t},this._quadCache.set(e.texture,i);const r=()=>{s.material.dispose(),this._quadCache.delete(e.texture),e.texture.removeEventListener("dispose",r)};e.texture.addEventListener("dispose",r)}else s=i.quad,i.cacheKey!==t&&(s.material.fragmentNode=this._nodes.getOutputNode(e.texture),s.material.needsUpdate=!0,i.cacheKey=t);const r=this.autoClear,n=this.xr.enabled;this.autoClear=!1,this.xr.enabled=!1,this._renderOutputLayers(s,e),this.autoClear=r,this.xr.enabled=n}getMaxAnisotropy(){return this.backend.capabilities.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,t=null,s=0,i=-1){if(null!==t&&t.isReadbackBuffer&&!1===this.info.memoryMap.has(t)){this.info.createReadbackBuffer(t);const e=()=>{t.removeEventListener("dispose",e),this.info.destroyReadbackBuffer(t)};t.addEventListener("dispose",e)}if(s%4!=0||i>0&&i%4!=0)throw new Error('THREE.Renderer: "getArrayBufferAsync()" offset and count must be a multiple of 4.');return await this.backend.getArrayBufferAsync(e,t,s,i)}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)}resetState(){if(!1===this._initialized)throw new Error('THREE.Renderer: .resetState() called before the backend is initialized. Use "await renderer.init();" before using this method.');this.backend.resetState()}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!0===this.reversedDepthBuffer?1-this._clearDepth: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('THREE.Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" 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.get(i,null,-1),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;const t=this.backend.getClearColor();r.clearColorValue.r=t.r,r.clearColorValue.g=t.g,r.clearColorValue.b=t.b,r.clearColorValue.a=t.a,r.clearDepthValue=this.getClearDepth(),r.clearStencilValue=this.getClearStencil(),r.activeCubeFace=this.getActiveCubeFace(),r.activeMipmapLevel=this.getActiveMipmapLevel(),!0===i.depthBuffer&&(e.depthInitialized=!0)}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){Nt('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(){Nt('Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.'),this.clear(!0,!1,!1)}async clearDepthAsync(){Nt('Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!0,!1)}async clearStencilAsync(){Nt('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!==Jt.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||!0===this._currentRenderContext?.fullscreenPass)&&(e=0),e}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:0}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:Jt.workingColorSpace}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||null===this._renderTarget}async dispose(){if(!0===this._initialized){this.info.dispose(),this._inspector.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();for(const e of this._frameBufferTargets.keys())e.dispose();await this.backend.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);for(const e of this._frameBufferTargets.keys())e.dispose()}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}compute(e,t=null){if(!0===this._isDeviceLost)return;if(!1===this._initialized)return Et('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,a=this._bindings,o=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),a.deleteForCompute(s),o.delete(s)};s.addEventListener("dispose",e);const t=s.onInitFunction;null!==t&&t.call(s,{renderer:this})}o.updateBeforeForCompute(s),o.updateForCompute(s),a.updateForCompute(s);const i=a.getForCompute(s),l=n.getForCompute(s,i);r.compute(e,s,i,l,t),o.updateAfterForCompute(s)}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 Nt('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('THREE.Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before using this method.');return this.backend.hasFeature(e)}hasInitialized(){return this._initialized}async initTextureAsync(e){Nt('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('THREE.Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before using this method.');this._textures.updateTexture(e)}initRenderTarget(e){if(!1===this._initialized)throw new Error('THREE.Renderer: .initRenderTarget() called before the backend is initialized. Use "await renderer.init();" before using this method.');this._textures.updateRenderTarget(e);const t=this._textures.get(e),s=this._renderContexts.get(e);s.textures=t.textures,s.depthTexture=t.depthTexture,s.width=t.width,s.height=t.height,s.renderTarget=e,s.depth=e.depthBuffer,s.stencil=e.stencilBuffer,this.backend.initRenderTarget(s)}copyFramebufferToTexture(e,t=null){if(null!==t)if(t.isVector2)t=Gv.set(t.x,t.y,e.image.width,e.image.height).floor();else{if(!t.isVector4)return void At("Renderer.copyFramebufferToTexture: Invalid rectangle.");t=Gv.copy(t).floor()}else t=Gv.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,a=0){return this.backend.copyTextureToBuffer(e.textures[n],t,s,i,r,a)}_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?zv:kv;if(!e.frustumCulled||e.intersectsFrustum(n)){!0===this.sortObjects&&Gv.setFromMatrixPosition(e.matrixWorld).applyMatrix4(Vv);const{geometry:t,material:n}=e;n.visible&&i.push(e,t,n,s,Gv.z,null,r)}}else if(e.isLineLoop)At("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?zv:kv;if(!e.frustumCulled||e.intersectsFrustum(n)){const{geometry:t,material:n}=e;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),Gv.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(Vv)),Array.isArray(n)){const a=t.groups;for(let o=0,l=a.length;o<l;o++){const l=a[o],h=n[l.materialIndex];h&&h.visible&&i.push(e,t,h,s,Gv.z,l,r)}}else n.visible&&i.push(e,t,n,s,Gv.z,null,r)}}if(!0===e.isBundleGroup&&void 0!==this.backend.beginBundle){const n=i;i=this._renderLists.get(e,t,this.lighting);const a=this._bundles.get(e,t,this._currentRenderContext),o=this.backend.get(a);if(this._bundleNeedsUpdate(e,o)){i.begin(),void 0===o.renderObjects?o.renderObjects=[]:o.renderObjects.length=0;const n=e.children;for(let e=0,a=n.length;e<a;e++)this._projectObject(n[e],t,s,i,r);i.finish()}return void n.pushBundle({bundleGroup:e,camera:t,renderList:i})}const n=e.children;for(let e=0,a=n.length;e<a;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,a=e.length;n<a;n++){const{object:a,geometry:o,material:l,group:h,clippingContext:u}=e[n];this._currentRenderObjectFunction(a,s,t,o,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=e.map&&e.map.isTexture,r=e.colorNode&&e.colorNode.isNode,n=e.castShadowNode&&e.castShadowNode.isNode,a=e.maskShadowNode&&e.maskShadowNode.isNode||e.maskNode&&e.maskNode.isNode;let o=null,l=null,h=null;if(i||r||n||a){let t,s;if(n?(t=e.castShadowNode.rgb,s=e.castShadowNode.a,!0!==this.shadowMap.transmitted&&Nt("Renderer: `shadowMap.transmitted` needs to be set to `true` when using `material.castShadowNode`.")):(t=xo(0),s=co(1)),i&&(s=s.mul(Id("map","texture",e).a)),r&&(s=s.mul(e.colorNode.a)),l=wo(t,s),a){const t=e.maskShadowNode||e.maskNode;l=ao(([e])=>(t.not().discard(),e))(l)}}e.depthNode&&e.depthNode.isNode&&(h=e.depthNode),e.castShadowPositionNode&&e.castShadowPositionNode.isNode?o=e.castShadowPositionNode:e.positionNode&&e.positionNode.isNode&&(o=e.positionNode),s={version:t,colorNode:l,depthNode:h,positionNode:o},this._cacheShadowNodes.set(e,s)}return s}_updateCamera(e,t){const s=this.xr;if(!1===s.isPresenting||!1===t){let t=!1;if(!0===this.reversedDepthBuffer&&!0!==e.reversedDepth){if(e._reversedDepth=!0,e.isArrayCamera)for(const t of e.cameras)t._reversedDepth=!0;t=!0}const s=this.coordinateSystem;if(e.coordinateSystem!==s){if(e.coordinateSystem=s,e.isArrayCamera)for(const t of e.cameras)t.coordinateSystem=s;t=!0}if(!0===t&&(e.updateProjectionMatrix(),e.isArrayCamera))for(const t of e.cameras)t.updateProjectionMatrix()}return null===e.parent&&!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),!0===t&&!0===s.enabled&&!0===s.isPresenting&&(!0===s.cameraAutoUpdate&&s.updateCamera(e),e=s.getCamera()),e}renderObject(e,t,s,i,r,n,a,o=null,l=null){let h,u,c,d,p,m,f,g=!1;const y=this._currentSourceMaterial;if(e.onBeforeRender(this,t,s,i,r,n),!0===r.allowOverride&&null!==t.overrideMaterial){this._currentSourceMaterial=r;const e=t.overrideMaterial;if(g=!0,h=e.isNodeMaterial?e.colorNode:null,u=e.isNodeMaterial?e.depthNode:null,c=e.isNodeMaterial?e.positionNode:null,d=t.overrideMaterial.side,p=e.displacementMap,m=e.displacementScale,f=e.displacementBias,r.positionNode&&r.positionNode.isNode&&(e.positionNode=r.positionNode),e.alphaTest=r.alphaTest,e.alphaMap=r.alphaMap,e.displacementMap=r.displacementMap,e.displacementScale=r.displacementScale,e.displacementBias=r.displacementBias,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);3===this.shadowMap.type?e.side=null!==r.shadowSide?r.shadowSide:r.side:e.side=null!==r.shadowSide?r.shadowSide:$v[r.side],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,a,n,o,"backSide"),r.side=0,this._handleObjectFunction(e,r,t,s,a,n,o,l),r.side=2):this._handleObjectFunction(e,r,t,s,a,n,o,l),g&&(t.overrideMaterial.colorNode=h,t.overrideMaterial.depthNode=u,t.overrideMaterial.positionNode=c,t.overrideMaterial.side=d,t.overrideMaterial.displacementMap=p,t.overrideMaterial.displacementScale=m,t.overrideMaterial.displacementBias=f),this._currentSourceMaterial=y,e.onAfterRender(this,t,s,i,r,n)}hasCompatibility(e){if(!1===this._initialized)throw new Error('THREE.Renderer: .hasCompatibility() called before the backend is initialized. Use "await renderer.init();" before using this method.');return this.backend.hasCompatibility(e)}_renderObjectDirect(e,t,s,i,r,n,a,o){const l=this._objects.get(e,t,s,i,r,this._currentRenderContext,a,o);if(l.drawRange=e.geometry.drawRange,l.group=n,null!==this._currentRenderBundle){this.backend.get(this._currentRenderBundle).renderObjects.push(l),l.bundle=this._currentRenderBundle.bundleGroup}const h=this._nodes.needsRefresh(l);h===xt?(this._nodes.updateBefore(l),this._geometries.updateForRender(l),this._nodes.updateForRender(l),this._bindings.updateForRender(l)):h===_t&&(this._nodes.updateBefore(l),this._nodes.updateForRender(l),this._bindings.updateSharedForRender(l)),this._pipelines.updateForRender(l),this._pipelines.isReady(l)&&(this.backend.draw(l,this.info),h!==bt&&this._nodes.updateAfter(l))}_createObjectPipeline(e,t,s,i,r,n,a,o){if(null!==this._compilationPromises)return void this._compilationPromises.push({object:e,material:t,scene:s,camera:i,lightsNode:r,group:n,clippingContext:a,passId:o,renderContext:this._currentRenderContext});const l=this._objects.get(e,t,s,i,r,this._currentRenderContext,a,o);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 Wv{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)}}function Hv(e){return e+(hb-e%hb)%hb}class qv extends Wv{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 Hv(this._buffer.byteLength)}get buffer(){return this._buffer}update(){return!0}release(){this._buffer=null}}class Xv extends qv{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let Yv=0;class Kv extends Xv{constructor(e,t){super("UniformBuffer_"+(e&&e.name?e.name:Yv++),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 byteLength(){return Hv(this.buffer.byteLength)}get buffer(){return this.nodeUniform.value}}class Qv extends Xv{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[],this._updateRangeCache=new Map,this._addedIndices=new Set}addUniformUpdateRange(e){const t=e.index;if(this._addedIndices.has(t))return;let s=this._updateRangeCache.get(t);void 0===s&&(s={start:0,count:0},this._updateRangeCache.set(t,s)),s.start=e.offset,s.count=e.itemSize,this._addedIndices.add(t),this.updateRanges.push(s)}clearUpdateRanges(){this._addedIndices.clear(),super.clearUpdateRanges()}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,a=t%hb,o=a%r,l=a+o;t+=o,0!==l&&hb-l<n&&(t+=hb-l),i.offset=t/e,i.index=s,t+=n}return Math.ceil(t/hb)*hb}update(){let e=!1;for(const t of this.uniforms)!0===this.updateByType(t)&&(e=!0);return e}release(){super.release(),this._values=null}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 At("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,this.addUniformUpdateRange(e)}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 a=this._getBufferForType(n);a[r+0]=s[r+0]=i.x,a[r+1]=s[r+1]=i.y,t=!0,this.addUniformUpdateRange(e)}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 a=this._getBufferForType(n);a[r+0]=s[r+0]=i.x,a[r+1]=s[r+1]=i.y,a[r+2]=s[r+2]=i.z,t=!0,this.addUniformUpdateRange(e)}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+3]!==i.w){const a=this._getBufferForType(n);a[r+0]=s[r+0]=i.x,a[r+1]=s[r+1]=i.y,a[r+2]=s[r+2]=i.z,a[r+3]=s[r+3]=i.w,t=!0,this.addUniformUpdateRange(e)}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 n=this.buffer;n[r+0]=s[r+0]=i.r,n[r+1]=s[r+1]=i.g,n[r+2]=s[r+2]=i.b,t=!0,this.addUniformUpdateRange(e)}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 n=this.buffer;n[r+0]=s[r+0]=i[0],n[r+1]=s[r+1]=i[1],n[r+2]=s[r+2]=i[2],n[r+4]=s[r+4]=i[3],n[r+5]=s[r+5]=i[4],n[r+6]=s[r+6]=i[5],n[r+8]=s[r+8]=i[6],n[r+9]=s[r+9]=i[7],n[r+10]=s[r+10]=i[8],t=!0,this.addUniformUpdateRange(e)}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,this.addUniformUpdateRange(e)}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 Zv=0;class Jv extends Qv{constructor(e,t){super(e),this.id=Zv++,this.groupNode=t,this.isNodeUniformsGroup=!0}}class eT extends Wv{constructor(e,t){super(e),this._texture=t,this.version=-1,this.generation=null,this.samplerKey="",this.isSampler=!0}set texture(e){this._texture!==e&&(this._texture=e,this.reset())}get texture(){return this._texture}update(){const{texture:e,version:t}=this;return t!==e.version&&(this.version=e.version,!0)}reset(){this.generation=null,this.version=-1}release(){this._texture=null}}let tT=0;class sT extends eT{constructor(e,t){super(e,t),this.id=tT++,this.store=!1,this.mipLevel=0,this.isSampledTexture=!0}}class iT extends sT{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 rT extends iT{constructor(e,t,s,i=null){super(e,t,s,i),this.isSampledCubeTexture=!0}}class nT extends iT{constructor(e,t,s,i=null){super(e,t,s,i),this.isSampledTexture3D=!0}}const aT={textureGather:new c_("\nvec4 tsl_textureGather( const int comp, sampler2D map, vec2 coord, ivec2 offset, bool flipY ) {\n\tif ( flipY ) offset.y = - offset.y;\n\tvec2 size = vec2( textureSize( map, 0 ) );\n\tvec2 st = floor( coord * size + vec2( offset ) - 0.5 );\n\tvec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;\n\tvec4 ret = vec4(\n\t\ttextureLod( map, ij.xw, 0.0 )[ comp ],\n\t\ttextureLod( map, ij.zw, 0.0 )[ comp ],\n\t\ttextureLod( map, ij.zy, 0.0 )[ comp ],\n\t\ttextureLod( map, ij.xy, 0.0 )[ comp ]\n\t);\n\treturn flipY ? ret.wzyx : ret;\n}\n"),textureGatherArray:new c_("\nvec4 tsl_textureGather_array( const int comp, sampler2DArray map, vec3 coord, ivec2 offset, bool flipY ) {\n\tif ( flipY ) offset.y = - offset.y;\n\tvec2 size = vec2( textureSize( map, 0 ).xy );\n\tvec2 st = floor( coord.xy * size + vec2( offset ) - 0.5 );\n\tvec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;\n\tvec4 ret = vec4(\n\t\ttextureLod( map, vec3( ij.xw, coord.z ), 0.0 )[ comp ],\n\t\ttextureLod( map, vec3( ij.zw, coord.z ), 0.0 )[ comp ],\n\t\ttextureLod( map, vec3( ij.zy, coord.z ), 0.0 )[ comp ],\n\t\ttextureLod( map, vec3( ij.xy, coord.z ), 0.0 )[ comp ]\n\t);\n\treturn flipY ? ret.wzyx : ret;\n}\n"),textureGatherCompare:new c_("\nvec4 tsl_textureGatherCompare( sampler2DShadow map, vec2 coord, ivec2 offset, float ref, bool flipY ) {\n\tif ( flipY ) offset.y = - offset.y;\n\tvec2 size = vec2( textureSize( map, 0 ) );\n\tvec2 st = floor( coord * size + vec2( offset ) - 0.5 );\n\tvec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;\n\tvec4 ret = vec4(\n\t\ttextureLod( map, vec3( ij.xw, ref ), 0.0 ),\n\t\ttextureLod( map, vec3( ij.zw, ref ), 0.0 ),\n\t\ttextureLod( map, vec3( ij.zy, ref ), 0.0 ),\n\t\ttextureLod( map, vec3( ij.xy, ref ), 0.0 )\n\t);\n\treturn flipY ? ret.wzyx : ret;\n}\n"),textureGatherCompareArray:new c_("\nvec4 tsl_textureGatherCompare_array( sampler2DArrayShadow map, vec3 coord, ivec2 offset, float ref, bool flipY ) {\n\tif ( flipY ) offset.y = - offset.y;\n\tvec2 size = vec2( textureSize( map, 0 ).xy );\n\tvec2 st = floor( coord.xy * size + vec2( offset ) - 0.5 );\n\tvec4 ij = vec4( st + 0.5, st + 1.5 ) / size.xyxy;\n\tvec4 ret = vec4(\n\t\ttexture( map, vec4( ij.xw, coord.z, ref ) ),\n\t\ttexture( map, vec4( ij.zw, coord.z, ref ) ),\n\t\ttexture( map, vec4( ij.zy, coord.z, ref ) ),\n\t\ttexture( map, vec4( ij.xy, coord.z, ref ) )\n\t);\n\treturn flipY ? ret.wzyx : ret;\n}\n"),floatpack_snorm_4x8:new c_("uint tsl_packSnorm4x8( vec4 v ) { uvec4 u = uvec4( ivec4( round( clamp( v, -1.0, 1.0 ) * 127.0 ) ) & 0xff ); return u.x | u.y << 8 | u.z << 16 | u.w << 24; }"),floatpack_unorm_4x8:new c_("uint tsl_packUnorm4x8( vec4 v ) { uvec4 u = uvec4( round( clamp( v, 0.0, 1.0 ) * 255.0 ) ); return u.x | u.y << 8 | u.z << 16 | u.w << 24; }"),floatunpack_snorm_4x8:new c_("vec4 tsl_unpackSnorm4x8( uint x ) { return max( vec4( ivec4( x << 24, x << 16, x << 8, x ) >> 24 ) / 127.0, -1.0 ); }"),floatunpack_unorm_4x8:new c_("vec4 tsl_unpackUnorm4x8( uint x ) { return vec4( uvec4( x, x >> 8, x >> 16, x >> 24 ) & 0xffu ) / 255.0; }")},oT={equals:"equal",bitcast_float_int:"floatBitsToInt",bitcast_int_float:"intBitsToFloat",bitcast_uint_float:"uintBitsToFloat",bitcast_float_uint:"floatBitsToUint",floatpack_snorm_2x16:"packSnorm2x16",floatpack_unorm_2x16:"packUnorm2x16",floatpack_float16_2x16:"packHalf2x16",floatpack_snorm_4x8:"tsl_packSnorm4x8",floatpack_unorm_4x8:"tsl_packUnorm4x8",floatunpack_snorm_2x16:"unpackSnorm2x16",floatunpack_unorm_2x16:"unpackUnorm2x16",floatunpack_float16_2x16:"unpackHalf2x16",floatunpack_snorm_4x8:"tsl_unpackSnorm4x8",floatunpack_unorm_4x8:"tsl_unpackUnorm4x8"},lT={low:"lowp",medium:"mediump",high:"highp"},hT={swizzleAssign:!0,storageBuffer:!1},uT={perspective:"smooth",linear:"noperspective"},cT={centroid:"centroid"},dT="\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 highp sampler2DShadow;\nprecision highp sampler2DArrayShadow;\nprecision highp samplerCubeShadow;\n",pT=new Set(["const","uniform","buffer","shared","attribute","varying","coherent","volatile","restrict","readonly","writeonly","atomic_uint","layout","centroid","flat","smooth","noperspective","patch","sample","invariant","precise","break","continue","do","for","while","switch","case","default","if","else","subroutine","in","out","inout","int","void","bool","true","false","float","double","discard","return","vec2","vec3","vec4","ivec2","ivec3","ivec4","bvec2","bvec3","bvec4","uint","uvec2","uvec3","uvec4","dvec2","dvec3","dvec4","mat2","mat3","mat4","mat2x2","mat2x3","mat2x4","mat3x2","mat3x3","mat3x4","mat4x2","mat4x3","mat4x4","dmat2","dmat3","dmat4","dmat2x2","dmat2x3","dmat2x4","dmat3x2","dmat3x3","dmat3x4","dmat4x2","dmat4x3","dmat4x4","lowp","mediump","highp","precision","sampler2D","sampler3D","samplerCube","sampler2DShadow","samplerCubeShadow","sampler2DArray","sampler2DArrayShadow","isampler2D","isampler3D","isamplerCube","isampler2DArray","usampler2D","usampler3D","usamplerCube","usampler2DArray","struct","common","partition","active","asm","class","union","enum","typedef","template","this","resource","goto","inline","noinline","public","static","extern","external","interface","long","short","half","fixed","unsigned","superp","input","output","hvec2","hvec3","hvec4","fvec2","fvec3","fvec4","sampler3DRect","filter","sizeof","cast","namespace","using","main"]);class mT extends $x{constructor(e,t){super(e,t,new uv),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]}}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==Qe}_include(e){const t=aT[e];return t.build(this),this.addInclude(t),t}getMethod(e){return void 0!==aT[e]&&this._include(e),oT[e]||e}getBitcastMethod(e,t){const s=this.getComponentType(t),i=this.getComponentType(e);return"float"!==s&&"float"!==i&&this.getTypeLength(t)===this.getTypeLength(e)?this.getType(e):this.getMethod(`bitcast_${s}_${i}`)}getFloatPackingMethod(e,t="2x16"){return this.getMethod(`floatpack_${e}_${t}`)}getFloatUnpackingMethod(e,t="2x16"){return this.getMethod(`floatunpack_${e}_${t}`)}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?ue:he;2===i?n=r?de:ce:3===i?n=r?pe:ne:4===i&&(n=r?me:ae);const a={Float32Array:Q,Uint8Array:W,Uint16Array:X,Uint32Array:K,Int8Array:H,Int16Array:q,Int32Array:Y,Uint8ClampedArray:W},o=Math.pow(2,Math.ceil(Math.log2(Math.sqrt(s/i))));let l=Math.ceil(s/i/o);o*l*i<s&&l++;const h=o*l*i,u=new e.constructor(h);u.set(e,0),t.array=u;const c=new Mr(t.array,o,l,n,a[t.array.constructor.name]||Q);c.needsUpdate=!0,c.isPBOTexture=!0;const d=new ac(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?e.name:super.getPropertyName(e,t)}isReservedKeyword(e){return pT.has(e)}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 a=s.build(this,"uint"),o=this.getDataFromNode(e);let l=o.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="."+aa.join("").slice(0,u),d=`ivec2(${a} % ${h}, ${a} / ${h})`,p=this.generateTextureLoad(null,n,d,"0",null,null);let m="vec4";i.pbo.type===K?m="uvec4":i.pbo.type===Y&&(m="ivec4"),this.addLineFlowCode(`${l} = ${m}(${p})${c}`,e),o.propertyName=l}return l}generateTextureLoad(e,t,s,i,r,n){let a;return null===i&&(i="0"),a=r?n?`texelFetchOffset( ${t}, ivec3( ${s}, ${r} ), int( ${i} ), ${n} )`:`texelFetch( ${t}, ivec3( ${s}, ${r} ), int( ${i} ) )`:n?`texelFetchOffset( ${t}, ${s}, int( ${i} ), ${n} )`:`texelFetch( ${t}, ${s}, int( ${i} ) )`,null!==e&&e.isDepthTexture&&(a+=".x"),a}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} )`}generateTextureSize(e,t,s){return`textureSize( ${t}, ${s} )`}generateTextureLevel(e,t,s,i,r,n){return r&&(s=`vec3( ${s}, ${r} )`),n?`textureLodOffset( ${t}, ${s}, ${i}, ${n} )`:`textureLod( ${t}, ${s}, ${i} )`}generateTextureBias(e,t,s,i,r,n){return r&&(s=`vec3( ${s}, ${r} )`),n?`textureOffset( ${t}, ${s}, ${n}, ${i} )`:`texture( ${t}, ${s}, ${i} )`}generateTextureGrad(e,t,s,i,r,n){return r&&(s=`vec3( ${s}, ${r} )`),n?`textureGradOffset( ${t}, ${s}, ${i[0]}, ${i[1]}, ${n} )`:`textureGrad( ${t}, ${s}, ${i[0]}, ${i[1]} )`}generateTextureCompare(e,t,s,i,r,n,a=this.shaderStage){if("fragment"===a)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} ) )`;At(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${a} shader.`)}generateTextureGather(e,t,s,i,r,n,a){return e.isDepthTexture&&(i="0"),null===n&&(n="ivec2( 0 )"),null===a&&(a="false"),r?(this._include("textureGatherArray"),`tsl_textureGather_array( ${i}, ${t}, vec3( ${s}, ${r} ), ${n}, ${a} )`):(this._include("textureGather"),`tsl_textureGather( ${i}, ${t}, ${s}, ${n}, ${a} )`)}generateTextureGatherCompare(e,t,s,i,r,n,a){return null===n&&(n="ivec2( 0 )"),null===a&&(a="false"),r?(this._include("textureGatherCompareArray"),`tsl_textureGatherCompare_array( ${t}, vec3( ${s}, ${r} ), ${n}, ${i}, ${a} )`):(this._include("textureGatherCompare"),`tsl_textureGatherCompare( ${t}, ${s}, ${n}, ${i}, ${a} )`)}getUniforms(e){const t=this.uniforms[e],s=[],i={};for(const e of t){let t=null,r=!1;if("texture"===e.type||"texture3D"===e.type){const s=e.node,i=s.value,r=this.getComponentTypeFromTexture(i),n="float"===r?"":r.charAt(0);t="texture3D"===e.type&&!1===i.isArrayTexture?`${n}sampler3D ${e.name};`:i.compareFunction&&s.isSampleCompare()?!0===i.isArrayTexture?`sampler2DArrayShadow ${e.name};`:`sampler2DShadow ${e.name};`:!0===i.isArrayTexture||!0===i.isDataArrayTexture||!0===i.isCompressedArrayTexture?`${n}sampler2DArray ${e.name};`:`${n}sampler2D ${e.name};`}else if("cubeTexture"===e.type)t=`samplerCube ${e.name};`;else if("cubeDepthTexture"===e.type){t=e.node.value.compareFunction?`samplerCubeShadow ${e.name};`:`samplerCube ${e.name};`}else if("buffer"===e.type){const s=e.node,i=this.getType(s.bufferType),r=s.bufferCount,n=r>0?r:"";t=`${s.name} {\n\t${i} ${e.name}[${n}];\n};\n`}else{const t=e.groupNode.name;if(void 0===i[t]){const e=this.uniformGroups[t];if(void 0!==e){const s=[];for(const t of e.uniforms){const e=t.getType(),i=this.getVectorType(e),r=t.nodeUniform.node.precision;let n=`${i} ${t.name};`;null!==r&&(n=lT[r]+" "+n),s.push("\t"+n)}i[t]=s}}r=!0}if(!r){const i=e.node.precision;null!==i&&(t=lT[i]+" "+t),t="uniform "+t,s.push(t)}}let r="";for(const e in i){const t=i[e];r+=this._getGLSLUniformStruct(e,t.join("\n"))+"\n"}return r+=s.join("\n"),r}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==Y){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"fragment"===e&&0===i.length&&i.push(`layout( location = 0 ) out ${this.getOutputType()} 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+=`${uT[i.interpolationType]||i.interpolationType} ${cT[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+=`${uT[e.interpolationType]||e.interpolationType} ${cT[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.compute.workgroupSize.reduce((e,t)=>e*t,1)}u`}getSubgroupSize(){At("GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node")}getInvocationSubgroupIndex(){At("GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node")}getSubgroupIndex(){At("GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node")}getDrawIndex(){return this.renderer.backend.extensions.has("WEBGL_multi_draw")?"uint( gl_DrawID )":"nodeUniformDrawId"}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=hT[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)}hT[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${dT}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\n\n// attributes\n${e.attributes}\n\n// vars\n${e.vars}\n\n// codes\n${e.codes}\n\nvoid main() {\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${dT}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\n\n// vars\n${e.vars}\n\n// codes\n${e.codes}\n\nvoid main() {\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+=`${this.format(i.result,r.getNodeType(this),"vec4")};`):"fragment"===t&&(e.outputNode.isOutputStructNode||(s+="fragColor = ",s+=`${this.format(i.result,r.getNodeType(this),this.getOutputType())};`)))}const n=e[t];if(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,!0),n.structs=this.getStructs(t),n.codes=this.getCodes(t),n.transforms=this.getTransforms(t),n.flow=s,"vertex"===t){const e=this.renderer.backend.extensions;this.object.isBatchedMesh&&!1===e.has("WEBGL_multi_draw")&&(n.uniforms+="\nuniform uint nodeUniformDrawId;\n")}}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 a=n.uniformGPU;if(void 0===a){const i=e.groupNode,o=i.name,l=this.getBindGroupArray(o,s);if("texture"===t)a=new iT(r.name,r.node,i),l.push(a);else if("cubeTexture"===t||"cubeDepthTexture"===t)a=new rT(r.name,r.node,i),l.push(a);else if("texture3D"===t)a=new nT(r.name,r.node,i),l.push(a);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 Kv(e,i),s.name=e.name,t.buffer=s),l.push(s),a=s}else{let e=this.uniformGroups[o];void 0===e?(e=new Jv(o,i),this.uniformGroups[o]=e,l.push(e)):-1===l.indexOf(e)&&l.push(e),a=this.getNodeUniform(r,t);const s=a.name,n=e.uniforms.some(e=>e.name===s);n||e.addUniform(a)}n.uniformGPU=a}return r}}let fT=null,gT=null;class yT{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={[gt]:null,[ft]:null},this.trackTimestamp=!0===e.trackTimestamp}async init(e){this.renderer=e}get coordinateSystem(){}beginRender(){}finishRender(){}setXRTarget(){}beginCompute(){}finishCompute(){}draw(){}compute(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}updateBinding(){}createRenderPipeline(){}createComputePipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}updateSampler(){}destroySampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}createUniformBuffer(){}destroyUniformBuffer(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}updateTimeStampUID(e){const t=this.get(e),s=this.renderer.info.frame;let i,r=e.id;Array.isArray(e)?(r=e.map(e=>e.id).join(","),i="c:"+this.renderer.info.compute.frameCalls):i=!0===e.isComputeNode?"c:"+this.renderer.info.compute.frameCalls:"r:"+this.renderer.info.render.frameCalls,t.timestampUID=i+":"+r+":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:")?ft:gt;return this.timestampQueryPool[t]}getTimestamp(e){return this._getQueryPool(e).getTimestamp(e)}get hasTimestamp(){return!1}hasTimestampQuery(e){return this._getQueryPool(e).hasTimestampQuery(e)}isOccluded(){}async resolveTimestampsAsync(e="render"){if(!this.trackTimestamp)return void Nt("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(){}getDrawingBufferSize(){return fT=fT||new $t,this.renderer.getDrawingBufferSize(fT)}setScissorTest(){}resetState(){}getClearColor(){const e=this.renderer;return gT=gT||new Ib,e.getClearColor(gT),gT.getRGB(gT),gT}getDomElement(){let e=this.domElement;return null===e&&(e=void 0!==this.parameters.canvas?this.parameters.canvas:function(){const e=Tt("canvas");return e.style.display="block",e}(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${t} webgpu`),this.domElement=e),e}hasCompatibility(){return!1}initRenderTarget(){}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(){}async dispose(){for(const e of Object.values(this.timestampQueryPool))null!==e&&await e.dispose()}}let bT,_T,xT=0;class vT{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 TT{constructor(e){this.backend=e}createAttribute(e,t){const s=this.backend,{gl:i}=s,r=e.array,n=e.usage||i.STATIC_DRAW,a=e.isInterleavedBufferAttribute?e.data:e,o=s.get(a);let l,h=o.bufferGPU;if(void 0===h&&(h=this._createBuffer(i,t,r,n),o.bufferGPU=h,o.bufferType=t,o.version=a.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===Y,id:xT++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(i,t,r,n);u=new vT(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),a=n.bufferType,o=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(s.bindBuffer(a,n.bufferGPU),0===o.length)s.bufferSubData(a,0,i);else{for(let e=0,t=o.length;e<t;e++){const t=o[e];s.bufferSubData(a,t.start*i.BYTES_PER_ELEMENT,i,t.start,t.count)}r.clearUpdateRanges()}s.bindBuffer(a,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,t=null,s=0,i=-1){const r=this.backend,{gl:n}=r,a=e.isInterleavedBufferAttribute?e.data:e,o=r.get(a),{bufferGPU:l}=o,h=-1===i?o.byteLength-s:i;let u;if(null===t)u=new Uint8Array(new ArrayBuffer(h));else if(t.isReadbackBuffer){if(!0===t._mapped)throw new Error("THREE.WebGPURenderer: ReadbackBuffer must be released before being used again.");const e=()=>{t.buffer=null,t._mapped=!1,t.removeEventListener("release",e),t.removeEventListener("dispose",e)};t.addEventListener("release",e),t.addEventListener("dispose",e),u=new Uint8Array(new ArrayBuffer(h)),t.buffer=u.buffer}else u=new Uint8Array(t);return n.bindBuffer(n.COPY_READ_BUFFER,l),n.getBufferSubData(n.COPY_READ_BUFFER,s,u),n.bindBuffer(n.COPY_READ_BUFFER,null),n.bindBuffer(n.COPY_WRITE_BUFFER,null),t&&t.isReadbackBuffer?t:u.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 ST{constructor(e){this.backend=e,this.gl=this.backend.gl,this.enabled={},this.parameters={},this.currentFlipSided=null,this.currentCullFace=null,this.currentProgram=null,this.currentBlendingEnabled=!1,this.currentBlending=null,this.currentBlendEquation=null,this.currentBlendEquationAlpha=null,this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentBlendColor=new Xs(0,0,0),this.currentBlendAlpha=0,this.currentPremultipledAlpha=null,this.currentPolygonOffsetFactor=null,this.currentPolygonOffsetUnits=null,this.currentColorMask=null,this.currentDepthReversed=!1,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;bT={[n]:e.FUNC_ADD,[a]:e.FUNC_SUBTRACT,[o]:e.FUNC_REVERSE_SUBTRACT,[l]:e.MIN,[h]:e.MAX},_T={[u]:e.ZERO,[c]:e.ONE,[d]:e.SRC_COLOR,[m]:e.SRC_ALPHA,[x]:e.SRC_ALPHA_SATURATE,[b]:e.DST_COLOR,[g]:e.DST_ALPHA,[p]:e.ONE_MINUS_SRC_COLOR,[f]:e.ONE_MINUS_SRC_ALPHA,[_]:e.ONE_MINUS_DST_COLOR,[y]:e.ONE_MINUS_DST_ALPHA,[v]:e.CONSTANT_COLOR,[T]:e.ONE_MINUS_CONSTANT_COLOR,[S]:e.CONSTANT_ALPHA,[w]:e.ONE_MINUS_CONSTANT_ALPHA};const t=e.getParameter(e.SCISSOR_BOX),s=e.getParameter(e.VIEWPORT);this.currentScissor=(new us).fromArray(t),this.currentViewport=(new us).fromArray(s),this._tempVec4=new us}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,t,s){const i=this.gl,r=this.backend.drawBuffersIndexedExt;if(r)for(let n=0;n<e.length;n++){const a=e[n];let o=null;if(null!==t){const e=t.getBlendMode(a.name);6===e.blending?o=s:0!==e.blending&&(o=e)}else o=s;null!==o?this._setMRTBlendingIndex(n,o):r.blendFuncSeparateiOES(n,i.ONE,i.ZERO,i.ONE,i.ZERO)}else Nt("WebGPURenderer: Multiple Render Targets (MRT) blending configuration is not fully supported in compatibility mode. The material blending will be used for all render targets.")}_setMRTBlendingIndex(e,t){const{gl:s}=this,i=this.backend.drawBuffersIndexedExt,r=t.blending,n=t.blendSrc,a=t.blendDst,o=t.blendEquation,l=t.premultipliedAlpha;if(5===r){const s=null!==t.blendSrcAlpha?t.blendSrcAlpha:n,r=null!==t.blendDstAlpha?t.blendDstAlpha:a,l=null!==t.blendEquationAlpha?t.blendEquationAlpha:o;i.blendEquationSeparateiOES(e,bT[o],bT[l]),i.blendFuncSeparateiOES(e,_T[n],_T[a],_T[s],_T[r])}else if(i.blendEquationSeparateiOES(e,s.FUNC_ADD,s.FUNC_ADD),l)switch(r){case 1:default:i.blendFuncSeparateiOES(e,s.ONE,s.ONE_MINUS_SRC_ALPHA,s.ONE,s.ONE_MINUS_SRC_ALPHA);break;case 2:i.blendFuncSeparateiOES(e,s.ONE,s.ONE,s.ONE,s.ONE);break;case 3:i.blendFuncSeparateiOES(e,s.ZERO,s.ONE_MINUS_SRC_COLOR,s.ZERO,s.ONE);break;case 4:i.blendFuncSeparateiOES(e,s.DST_COLOR,s.ONE_MINUS_SRC_ALPHA,s.ZERO,s.ONE)}else switch(r){case 1:default:i.blendFuncSeparateiOES(e,s.SRC_ALPHA,s.ONE_MINUS_SRC_ALPHA,s.ONE,s.ONE_MINUS_SRC_ALPHA);break;case 2:i.blendFuncSeparateiOES(e,s.SRC_ALPHA,s.ONE,s.ONE,s.ONE);break;case 3:i.blendFuncSeparateiOES(e,s.ZERO,s.ONE_MINUS_SRC_COLOR,s.ZERO,s.ONE);break;case 4:i.blendFuncSeparateiOES(e,s.DST_COLOR,s.ONE_MINUS_SRC_ALPHA,s.ZERO,s.ONE)}}setBlending(e,t,s,i,r,a,o,l,h,u){const{gl:c}=this;if(0!==e){if(!1===this.currentBlendingEnabled&&(this.enable(c.BLEND),this.currentBlendingEnabled=!0),5===e)r=r||t,a=a||s,o=o||i,t===this.currentBlendEquation&&r===this.currentBlendEquationAlpha||(c.blendEquationSeparate(bT[t],bT[r]),this.currentBlendEquation=t,this.currentBlendEquationAlpha=r),s===this.currentBlendSrc&&i===this.currentBlendDst&&a===this.currentBlendSrcAlpha&&o===this.currentBlendDstAlpha||(c.blendFuncSeparate(_T[s],_T[i],_T[a],_T[o]),this.currentBlendSrc=s,this.currentBlendDst=i,this.currentBlendSrcAlpha=a,this.currentBlendDstAlpha=o),!1!==l.equals(this.currentBlendColor)&&h===this.currentBlendAlpha||(c.blendColor(l.r,l.g,l.b,h),this.currentBlendColor.copy(l),this.currentBlendAlpha=h),this.currentBlending=e,this.currentPremultipledAlpha=!1;else if(e!==this.currentBlending||u!==this.currentPremultipledAlpha){if(this.currentBlendEquation===n&&this.currentBlendEquationAlpha===n||(c.blendEquation(c.FUNC_ADD),this.currentBlendEquation=n,this.currentBlendEquationAlpha=n),u)switch(e){case 1:c.blendFuncSeparate(c.ONE,c.ONE_MINUS_SRC_ALPHA,c.ONE,c.ONE_MINUS_SRC_ALPHA);break;case 2:c.blendFunc(c.ONE,c.ONE);break;case 3:c.blendFuncSeparate(c.ZERO,c.ONE_MINUS_SRC_COLOR,c.ZERO,c.ONE);break;case 4:c.blendFuncSeparate(c.DST_COLOR,c.ONE_MINUS_SRC_ALPHA,c.ZERO,c.ONE);break;default:At("WebGLState: Invalid blending: ",e)}else switch(e){case 1:c.blendFuncSeparate(c.SRC_ALPHA,c.ONE_MINUS_SRC_ALPHA,c.ONE,c.ONE_MINUS_SRC_ALPHA);break;case 2:c.blendFuncSeparate(c.SRC_ALPHA,c.ONE,c.ONE,c.ONE);break;case 3:At("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case 4:At("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:At("WebGLState: Invalid blending: ",e)}this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentBlending=e,this.currentPremultipledAlpha=u}}else!0===this.currentBlendingEnabled&&(this.disable(c.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)}setReversedDepth(e){if(this.currentDepthReversed!==e){const t=this.backend.extensions.get("EXT_clip_control");e?t.clipControlEXT(t.LOWER_LEFT_EXT,t.ZERO_TO_ONE_EXT):t.clipControlEXT(t.LOWER_LEFT_EXT,t.NEGATIVE_ONE_TO_ONE_EXT),this.currentDepthReversed=e}}setDepthMask(e){this.currentDepthMask!==e&&(this.gl.depthMask(e),this.currentDepthMask=e)}setDepthFunc(e){if(this.currentDepthReversed&&(e=Rt[e]),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.blendColor,e.blendAlpha,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),this.currentClippingPlanes!==s){const e=12288;for(let t=0;t<8;t++)t<s?this.enable(e+t):this.disable(e+t);this.currentClippingPlanes=s}}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:a}=this;void 0===s&&(s=null===r?i.TEXTURE0+a-1:r);let o=n[s];void 0===o&&(o={type:void 0,texture:void 0},n[s]=o),o.type===e&&o.texture===t||(r!==s&&(i.activeTexture(s),this.currentTextureSlot=s),i.bindTexture(e,t),o.type=e,o.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)}getParameter(e){const{gl:t,parameters:s}=this;return void 0!==s[e]?s[e]:t.getParameter(e)}pixelStorei(e,t){const{gl:s,parameters:i}=this;i[e]!==t&&(s.pixelStorei(e,t),i[e]=t)}reset(){const{gl:e}=this;e.disable(e.BLEND),e.disable(e.CULL_FACE),e.disable(e.DEPTH_TEST),e.disable(e.POLYGON_OFFSET_FILL),e.disable(e.SCISSOR_TEST),e.disable(e.STENCIL_TEST),e.disable(e.SAMPLE_ALPHA_TO_COVERAGE),e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ZERO),e.blendFuncSeparate(e.ONE,e.ZERO,e.ONE,e.ZERO),e.blendColor(0,0,0,0),e.colorMask(!0,!0,!0,!0),e.clearColor(0,0,0,0),e.depthMask(!0),e.depthFunc(e.LESS),e.clearDepth(1),e.stencilMask(4294967295),e.stencilFunc(e.ALWAYS,0,4294967295),e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.clearStencil(0),e.cullFace(e.BACK),e.frontFace(e.CCW),e.polygonOffset(0,0),e.activeTexture(e.TEXTURE0),e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),e.bindFramebuffer(e.READ_FRAMEBUFFER,null),e.useProgram(null),e.lineWidth(1),e.scissor(0,0,e.canvas.width,e.canvas.height),e.viewport(0,0,e.canvas.width,e.canvas.height),e.pixelStorei(e.PACK_ALIGNMENT,4),e.pixelStorei(e.UNPACK_ALIGNMENT,4),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!1),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,e.BROWSER_DEFAULT_WEBGL),e.pixelStorei(e.PACK_ROW_LENGTH,0),e.pixelStorei(e.PACK_SKIP_PIXELS,0),e.pixelStorei(e.PACK_SKIP_ROWS,0),e.pixelStorei(e.UNPACK_ROW_LENGTH,0),e.pixelStorei(e.UNPACK_IMAGE_HEIGHT,0),e.pixelStorei(e.UNPACK_SKIP_PIXELS,0),e.pixelStorei(e.UNPACK_SKIP_ROWS,0),e.pixelStorei(e.UNPACK_SKIP_IMAGES,0),this.resetVertexState(),this.enabled={},this.parameters={},this.currentFlipSided=null,this.currentCullFace=null,this.currentProgram=null,this.currentBlendingEnabled=!1,this.currentBlending=null,this.currentBlendEquation=null,this.currentBlendEquationAlpha=null,this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentBlendColor.set(0,0,0),this.currentBlendAlpha=0,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.currentBoundFramebuffers={},this.currentDrawbuffers=new WeakMap,this.currentTextureSlot=null,this.currentBoundTextures={},this.currentBoundBufferBases={},this.currentScissor.set(0,0,e.canvas.width,e.canvas.height),this.currentViewport.set(0,0,e.canvas.width,e.canvas.height),this.currentDepthReversed=!1,!0===this.backend.renderer.reversedDepthBuffer&&this.setReversedDepth(!0)}}class wT{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=Jt.getTransfer(t);if(e===W)return s.UNSIGNED_BYTE;if(e===J)return s.UNSIGNED_SHORT_4_4_4_4;if(e===ee)return s.UNSIGNED_SHORT_5_5_5_1;if(e===se)return s.UNSIGNED_INT_5_9_9_9_REV;if(e===ie)return s.UNSIGNED_INT_10F_11F_11F_REV;if(e===H)return s.BYTE;if(e===q)return s.SHORT;if(e===X)return s.UNSIGNED_SHORT;if(e===Y)return s.INT;if(e===K)return s.UNSIGNED_INT;if(e===Q)return s.FLOAT;if(e===Z)return s.HALF_FLOAT;if(e===re)return s.ALPHA;if(e===ne)return s.RGB;if(e===ae)return s.RGBA;if(e===oe)return s.DEPTH_COMPONENT;if(e===le)return s.DEPTH_STENCIL;if(e===he)return s.RED;if(e===ue)return s.RED_INTEGER;if(e===ce)return s.RG;if(e===de)return s.RG_INTEGER;if(e===me)return s.RGBA_INTEGER;if(e===fe||e===ge||e===ye||e===be)if(n===tt){if(r=i.get("WEBGL_compressed_texture_s3tc_srgb"),null===r)return null;if(e===fe)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(e===ge)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(e===ye)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(e===be)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(r=i.get("WEBGL_compressed_texture_s3tc"),null===r)return null;if(e===fe)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(e===ge)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(e===ye)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(e===be)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(e===_e||e===xe||e===ve||e===Te){if(r=i.get("WEBGL_compressed_texture_pvrtc"),null===r)return null;if(e===_e)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(e===xe)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(e===ve)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(e===Te)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(e===Se||e===we||e===Me||e===Ee||e===Ae||e===Ne||e===Ce){if(r=i.get("WEBGL_compressed_texture_etc"),null===r)return null;if(e===Se||e===we)return n===tt?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(e===Me)return n===tt?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC;if(e===Ee)return r.COMPRESSED_R11_EAC;if(e===Ae)return r.COMPRESSED_SIGNED_R11_EAC;if(e===Ne)return r.COMPRESSED_RG11_EAC;if(e===Ce)return r.COMPRESSED_SIGNED_RG11_EAC}if(e===Re||e===Pe||e===Be||e===Fe||e===Le||e===De||e===Oe||e===Ie||e===Ue||e===ke||e===ze||e===Ve||e===Ge||e===$e){if(r=i.get("WEBGL_compressed_texture_astc"),null===r)return null;if(e===Re)return n===tt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(e===Pe)return n===tt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(e===Be)return n===tt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(e===Fe)return n===tt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(e===Le)return n===tt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(e===De)return n===tt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(e===Oe)return n===tt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(e===Ie)return n===tt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(e===Ue)return n===tt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(e===ke)return n===tt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(e===ze)return n===tt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(e===Ve)return n===tt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(e===Ge)return n===tt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(e===$e)return n===tt?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}if(e===je||e===We||e===He){if(r=i.get("EXT_texture_compression_bptc"),null===r)return null;if(e===je)return n===tt?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(e===We)return r.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(e===He)return r.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}if(e===qe||e===Xe||e===Ye||e===Ke){if(r=i.get("EXT_texture_compression_rgtc"),null===r)return null;if(e===qe)return r.COMPRESSED_RED_RGTC1_EXT;if(e===Xe)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(e===Ye)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(e===Ke)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}return e===te?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 MT,ET,AT,NT=!1;class CT{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},this._srcFramebuffer=null,this._dstFramebuffer=null,!1===NT&&(this._init(),NT=!0)}_init(){const e=this.gl;MT={[O]:e.REPEAT,[I]:e.CLAMP_TO_EDGE,[U]:e.MIRRORED_REPEAT},ET={[k]:e.NEAREST,[z]:e.NEAREST_MIPMAP_NEAREST,[V]:e.NEAREST_MIPMAP_LINEAR,[G]:e.LINEAR,[$]:e.LINEAR_MIPMAP_NEAREST,[j]:e.LINEAR_MIPMAP_LINEAR},AT={[it]:e.NEVER,[ut]:e.ALWAYS,[rt]:e.LESS,[at]:e.LEQUAL,[nt]:e.EQUAL,[ht]:e.GEQUAL,[ot]:e.GREATER,[lt]: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,n=!1){const{gl:a,extensions:o}=this;if(null!==e){if(void 0!==a[e])return a[e];Et("WebGLBackend: Attempt to use non-existing WebGL internal format '"+e+"'")}let l=null;i&&(l=o.get("EXT_texture_norm16"),l||Et("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let h=t;if(t===a.RED&&(s===a.FLOAT&&(h=a.R32F),s===a.HALF_FLOAT&&(h=a.R16F),s===a.UNSIGNED_BYTE&&(h=a.R8),s===a.BYTE&&(h=a.R8_SNORM),s===a.UNSIGNED_SHORT&&l&&(h=l.R16_EXT),s===a.SHORT&&l&&(h=l.R16_SNORM_EXT)),t===a.RED_INTEGER&&(s===a.UNSIGNED_BYTE&&(h=a.R8UI),s===a.UNSIGNED_SHORT&&(h=a.R16UI),s===a.UNSIGNED_INT&&(h=a.R32UI),s===a.BYTE&&(h=a.R8I),s===a.SHORT&&(h=a.R16I),s===a.INT&&(h=a.R32I)),t===a.RG&&(s===a.FLOAT&&(h=a.RG32F),s===a.HALF_FLOAT&&(h=a.RG16F),s===a.UNSIGNED_BYTE&&(h=a.RG8),s===a.BYTE&&(h=a.RG8_SNORM),s===a.UNSIGNED_SHORT&&l&&(h=l.RG16_EXT),s===a.SHORT&&l&&(h=l.RG16_SNORM_EXT)),t===a.RG_INTEGER&&(s===a.UNSIGNED_BYTE&&(h=a.RG8UI),s===a.UNSIGNED_SHORT&&(h=a.RG16UI),s===a.UNSIGNED_INT&&(h=a.RG32UI),s===a.BYTE&&(h=a.RG8I),s===a.SHORT&&(h=a.RG16I),s===a.INT&&(h=a.RG32I)),t===a.RGB){const e=n?et:Jt.getTransfer(r);s===a.FLOAT&&(h=a.RGB32F),s===a.HALF_FLOAT&&(h=a.RGB16F),s===a.UNSIGNED_BYTE&&(h=e===tt?a.SRGB8:a.RGB8),s===a.BYTE&&(h=a.RGB8_SNORM),s===a.UNSIGNED_SHORT&&l&&(h=l.RGB16_EXT),s===a.SHORT&&l&&(h=l.RGB16_SNORM_EXT),s===a.UNSIGNED_SHORT_5_6_5&&(h=a.RGB565),s===a.UNSIGNED_SHORT_5_5_5_1&&(h=a.RGB5_A1),s===a.UNSIGNED_SHORT_4_4_4_4&&(h=a.RGB4),s===a.UNSIGNED_INT_5_9_9_9_REV&&(h=a.RGB9_E5),s===a.UNSIGNED_INT_10F_11F_11F_REV&&(h=a.R11F_G11F_B10F)}if(t===a.RGB_INTEGER&&(s===a.UNSIGNED_BYTE&&(h=a.RGB8UI),s===a.UNSIGNED_SHORT&&(h=a.RGB16UI),s===a.UNSIGNED_INT&&(h=a.RGB32UI),s===a.BYTE&&(h=a.RGB8I),s===a.SHORT&&(h=a.RGB16I),s===a.INT&&(h=a.RGB32I)),t===a.RGBA){const e=n?et:Jt.getTransfer(r);s===a.FLOAT&&(h=a.RGBA32F),s===a.HALF_FLOAT&&(h=a.RGBA16F),s===a.UNSIGNED_BYTE&&(h=e===tt?a.SRGB8_ALPHA8:a.RGBA8),s===a.BYTE&&(h=a.RGBA8_SNORM),s===a.UNSIGNED_SHORT&&l&&(h=l.RGBA16_EXT),s===a.SHORT&&l&&(h=l.RGBA16_SNORM_EXT),s===a.UNSIGNED_SHORT_4_4_4_4&&(h=a.RGBA4),s===a.UNSIGNED_SHORT_5_5_5_1&&(h=a.RGB5_A1)}return t===a.RGBA_INTEGER&&(s===a.UNSIGNED_BYTE&&(h=a.RGBA8UI),s===a.UNSIGNED_SHORT&&(h=a.RGBA16UI),s===a.UNSIGNED_INT&&(h=a.RGBA32UI),s===a.BYTE&&(h=a.RGBA8I),s===a.SHORT&&(h=a.RGBA16I),s===a.INT&&(h=a.RGBA32I)),t===a.DEPTH_COMPONENT&&(s===a.UNSIGNED_SHORT&&(h=a.DEPTH_COMPONENT16),s===a.UNSIGNED_INT&&(h=a.DEPTH_COMPONENT24),s===a.FLOAT&&(h=a.DEPTH_COMPONENT32F)),t===a.DEPTH_STENCIL&&s===a.UNSIGNED_INT_24_8&&(h=a.DEPTH24_STENCIL8),h!==a.R16F&&h!==a.R32F&&h!==a.RG16F&&h!==a.RG32F&&h!==a.RGBA16F&&h!==a.RGBA32F||o.get("EXT_color_buffer_float"),h}setTextureParameters(e,t){const{gl:s,extensions:i,backend:r}=this,{state:n}=this.backend,a=Jt.getPrimaries(Jt.workingColorSpace),o=t.colorSpace===Qe?null:Jt.getPrimaries(t.colorSpace),l=t.colorSpace===Qe||a===o?s.NONE:s.BROWSER_DEFAULT_WEBGL;n.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,t.flipY),n.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),n.pixelStorei(s.UNPACK_ALIGNMENT,t.unpackAlignment),n.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,l),s.texParameteri(e,s.TEXTURE_WRAP_S,MT[t.wrapS]),s.texParameteri(e,s.TEXTURE_WRAP_T,MT[t.wrapT]),e!==s.TEXTURE_3D&&e!==s.TEXTURE_2D_ARRAY||t.isArrayTexture||s.texParameteri(e,s.TEXTURE_WRAP_R,MT[t.wrapR]),s.texParameteri(e,s.TEXTURE_MAG_FILTER,ET[t.magFilter]);const h=void 0!==t.mipmaps&&t.mipmaps.length>0,u=t.minFilter===G&&h?j:t.minFilter;if(s.texParameteri(e,s.TEXTURE_MIN_FILTER,ET[u]),t.compareFunction&&(s.texParameteri(e,s.TEXTURE_COMPARE_MODE,s.COMPARE_REF_TO_TEXTURE),s.texParameteri(e,s.TEXTURE_COMPARE_FUNC,AT[t.compareFunction])),!0===i.has("EXT_texture_filter_anisotropic")){if(t.magFilter===k)return;if(t.minFilter!==V&&t.minFilter!==j)return;if(t.type===Q&&!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.capabilities.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;let r,n,a,o,l;if(!0===e.isExternalTexture)r=e.sourceTexture,n=this.getGLTextureType(e);else{const{levels:h,width:u,height:c,depth:d}=t;a=i.utils.convert(e.format,e.colorSpace),o=i.utils.convert(e.type),l=this.getInternalFormat(e.internalFormat,a,o,e.normalized,e.colorSpace,e.isVideoTexture),r=s.createTexture(),n=this.getGLTextureType(e),i.state.bindTexture(n,r),this.setTextureParameters(n,e),e.isArrayTexture||e.isDataArrayTexture||e.isCompressedArrayTexture?s.texStorage3D(s.TEXTURE_2D_ARRAY,h,l,u,c,d):e.isData3DTexture?s.texStorage3D(s.TEXTURE_3D,h,l,u,c,d):e.isVideoTexture||s.texStorage2D(n,h,l,u,c)}i.set(e,{textureGPU:r,glTextureType:n,glFormat:a,glType:o,glInternalFormat:l})}copyBufferToTexture(e,t){const{gl:s,backend:i}=this,{state:r}=i,{textureGPU:n,glTextureType:a,glFormat:o,glType:l}=i.get(t),{width:h,height:u}=t.source.data;s.bindBuffer(s.PIXEL_UNPACK_BUFFER,e),i.state.bindTexture(a,n),r.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,!1),r.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),s.texSubImage2D(a,0,0,0,h,u,o,l,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:a,glFormat:o,glType:l,glInternalFormat:h}=this.backend.get(e);if(!e.isRenderTargetTexture&&void 0!==n)if(this.backend.state.bindTexture(a,n),this.setTextureParameters(a,e),e.isCompressedTexture){const i=e.mipmaps,r=t.image;for(let t=0;t<i.length;t++){const n=i[t];if(e.isCompressedArrayTexture)if(e.format!==s.RGBA)if(null!==o)if(e.layerUpdates.size>0){const i=Cn(n.width,n.height,e.format,e.type);for(const r of e.layerUpdates){const e=n.data.subarray(r*i/n.data.BYTES_PER_ELEMENT,(r+1)*i/n.data.BYTES_PER_ELEMENT);s.compressedTexSubImage3D(s.TEXTURE_2D_ARRAY,t,0,0,r,n.width,n.height,1,o,e)}}else s.compressedTexSubImage3D(s.TEXTURE_2D_ARRAY,t,0,0,0,n.width,n.height,r.depth,o,n.data);else Et("WebGLBackend: Attempt to load unsupported compressed texture format in .uploadTexture()");else s.texSubImage3D(s.TEXTURE_2D_ARRAY,t,0,0,0,n.width,n.height,r.depth,o,l,n.data);else null!==o?s.compressedTexSubImage2D(s.TEXTURE_2D,t,0,0,n.width,n.height,o,n.data):Et("WebGLBackend: Unsupported compressed texture format")}e.isCompressedArrayTexture&&e.layerUpdates.size>0&&e.clearLayerUpdates()}else if(e.isCubeTexture){const n=t.images,a=e.mipmaps;for(let e=0;e<6;e++){const t=RT(n[e]);s.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,0,0,i,r,o,l,t);for(let t=0;t<a.length;t++){const i=RT(a[t].images[e]);s.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+e,t+1,0,0,i.width,i.height,o,l,i)}}}else if(e.isDataArrayTexture||e.isArrayTexture){const i=t.image;if(e.layerUpdates.size>0){const t=Cn(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,o,l,e)}e.clearLayerUpdates()}else s.texSubImage3D(s.TEXTURE_2D_ARRAY,0,0,0,0,i.width,i.height,i.depth,o,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,o,l,e.data)}else if(e.isVideoTexture)e.update(),s.texImage2D(a,0,h,o,l,t.image);else if(e.isHTMLTexture)"function"==typeof s.texElementImage2D&&(3===s.texElementImage2D.length?s.texElementImage2D(s.TEXTURE_2D,s.RGBA8,t.image):s.texElementImage2D(s.TEXTURE_2D,0,s.RGBA,s.RGBA,s.UNSIGNED_BYTE,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=RT(t);s.texSubImage2D(a,e,0,0,t.width,t.height,o,l,i)}else{const e=RT(t.image);s.texSubImage2D(a,0,0,0,i,r,o,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&&!0!==e.isExternalTexture&&s.deleteTexture(r),i.delete(e)}copyTextureToTexture(e,t,s=null,i=null,r=0,n=0){const{gl:a,backend:o}=this,{state:l}=this.backend,{textureGPU:h,glTextureType:u,glType:c,glFormat:d}=o.get(t);let p,m,f,g,y,b,_,x,v;l.bindTexture(u,h);const T=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(T.width*t),m=Math.floor(T.height*t),f=e.isDataArrayTexture||e.isArrayTexture?T.depth:e.isData3DTexture?Math.floor(T.depth*t):1,g=0,y=0,b=0}null!==i?(_=i.x,x=i.y,v=i.z):(_=0,x=0,v=0),l.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,t.flipY),l.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),l.pixelStorei(a.UNPACK_ALIGNMENT,t.unpackAlignment);const S=l.getParameter(a.UNPACK_ROW_LENGTH),w=l.getParameter(a.UNPACK_IMAGE_HEIGHT),M=l.getParameter(a.UNPACK_SKIP_PIXELS),E=l.getParameter(a.UNPACK_SKIP_ROWS),A=l.getParameter(a.UNPACK_SKIP_IMAGES);l.pixelStorei(a.UNPACK_ROW_LENGTH,T.width),l.pixelStorei(a.UNPACK_IMAGE_HEIGHT,T.height),l.pixelStorei(a.UNPACK_SKIP_PIXELS,g),l.pixelStorei(a.UNPACK_SKIP_ROWS,y),l.pixelStorei(a.UNPACK_SKIP_IMAGES,b);const N=e.isDataArrayTexture||e.isData3DTexture||t.isArrayTexture,C=t.isDataArrayTexture||t.isData3DTexture||t.isArrayTexture;if(e.isDepthTexture){const s=o.get(e),i=o.get(t),u=o.get(s.renderTarget),c=o.get(i.renderTarget),d=u.framebuffers[s.cacheKey],T=c.framebuffers[i.cacheKey],S=l.currentBoundFramebuffers[a.READ_FRAMEBUFFER]??null,w=l.currentBoundFramebuffers[a.DRAW_FRAMEBUFFER]??null;l.bindFramebuffer(a.READ_FRAMEBUFFER,d),l.bindFramebuffer(a.DRAW_FRAMEBUFFER,T);for(let e=0;e<f;e++)N&&(a.framebufferTextureLayer(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,s.textureGPU,r,b+e),a.framebufferTextureLayer(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,h,n,v+e)),a.blitFramebuffer(g,y,p,m,_,x,p,m,a.DEPTH_BUFFER_BIT,a.NEAREST);l.bindFramebuffer(a.READ_FRAMEBUFFER,S),l.bindFramebuffer(a.DRAW_FRAMEBUFFER,w)}else if(0!==r||e.isRenderTargetTexture||o.has(e)){const t=o.get(e);null===this._srcFramebuffer&&(this._srcFramebuffer=a.createFramebuffer()),null===this._dstFramebuffer&&(this._dstFramebuffer=a.createFramebuffer());const s=l.currentBoundFramebuffers[a.READ_FRAMEBUFFER]??null,i=l.currentBoundFramebuffers[a.DRAW_FRAMEBUFFER]??null;l.bindFramebuffer(a.READ_FRAMEBUFFER,this._srcFramebuffer),l.bindFramebuffer(a.DRAW_FRAMEBUFFER,this._dstFramebuffer);for(let e=0;e<f;e++)N?a.framebufferTextureLayer(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,t.textureGPU,r,b+e):a.framebufferTexture2D(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,t.textureGPU,r),C?a.framebufferTextureLayer(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,h,n,v+e):a.framebufferTexture2D(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,h,n),0!==r?a.blitFramebuffer(g,y,p,m,_,x,p,m,a.COLOR_BUFFER_BIT,a.NEAREST):C?a.copyTexSubImage3D(u,n,_,x,v+e,g,y,p,m):a.copyTexSubImage2D(u,n,_,x,g,y,p,m);l.bindFramebuffer(a.READ_FRAMEBUFFER,s),l.bindFramebuffer(a.DRAW_FRAMEBUFFER,i)}else C?e.isDataTexture||e.isData3DTexture?a.texSubImage3D(u,n,_,x,v,p,m,f,d,c,T.data):t.isCompressedArrayTexture?a.compressedTexSubImage3D(u,n,_,x,v,p,m,f,d,T.data):a.texSubImage3D(u,n,_,x,v,p,m,f,d,c,T):e.isDataTexture?a.texSubImage2D(a.TEXTURE_2D,n,_,x,p,m,d,c,T.data):e.isCompressedTexture?a.compressedTexSubImage2D(a.TEXTURE_2D,n,_,x,T.width,T.height,d,T.data):a.texSubImage2D(a.TEXTURE_2D,n,_,x,p,m,d,c,T);l.pixelStorei(a.UNPACK_ROW_LENGTH,S),l.pixelStorei(a.UNPACK_IMAGE_HEIGHT,w),l.pixelStorei(a.UNPACK_SKIP_PIXELS,M),l.pixelStorei(a.UNPACK_SKIP_ROWS,E),l.pixelStorei(a.UNPACK_SKIP_IMAGES,A),0===n&&t.generateMipmaps&&a.generateMipmap(u),l.unbindTexture()}copyFramebufferToTexture(e,t,s){const{gl:i}=this,{state:r}=this.backend,{textureGPU:n}=this.backend.get(e),{x:a,y:o,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!==a||0!==o;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-o-h;i.blitFramebuffer(a,p,a+l,p+h,a,p,a+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,a,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,a,c-h-o,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:a,depthBuffer:o,stencilBuffer:l,width:h,height:u}=n;if(r.bindRenderbuffer(r.RENDERBUFFER,e),o&&!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?(a&&a.isDepthTexture&&a.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 o&&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:a,gl:o}=this,{textureGPU:l,glFormat:h,glType:u}=this.backend.get(e),c=o.createFramebuffer();if(a.state.bindFramebuffer(o.READ_FRAMEBUFFER,c),e.isData3DTexture||e.isDataArrayTexture||e.isArrayTexture)o.framebufferTextureLayer(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,l,0,n);else{const t=e.isCubeTexture?o.TEXTURE_CUBE_MAP_POSITIVE_X+n:o.TEXTURE_2D;o.framebufferTexture2D(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,t,l,0)}const d=this._getTypedArrayType(u),p=i*r*this._getBytesPerTexel(u,h),m=o.createBuffer();o.bindBuffer(o.PIXEL_PACK_BUFFER,m),o.bufferData(o.PIXEL_PACK_BUFFER,p,o.STREAM_READ),o.readPixels(t,s,i,r,h,u,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),await a.utils._clientWaitAsync();const f=new d(p/d.BYTES_PER_ELEMENT);return o.bindBuffer(o.PIXEL_PACK_BUFFER,m),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,f),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),a.state.bindFramebuffer(o.READ_FRAMEBUFFER,null),o.deleteBuffer(m),o.deleteFramebuffer(c),f}_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(`THREE.WebGLTextureUtils: 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 RT(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 PT{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 BT{constructor(e){this.backend=e,this.maxAnisotropy=null,this.maxUniformBlockSize=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}getUniformBufferLimit(){if(null!==this.maxUniformBlockSize)return this.maxUniformBlockSize;const e=this.backend.gl;return this.maxUniformBlockSize=e.getParameter(e.MAX_UNIFORM_BLOCK_SIZE),this.maxUniformBlockSize}}const FT={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 LT{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:a,index:o}=this;0!==o?s.drawElements(i,t,n,e):s.drawArrays(i,e,t),a.update(r,t,1)}renderInstances(e,t,s){const{gl:i,mode:r,type:n,index:a,object:o,info:l}=this;0!==s&&(0!==a?i.drawElementsInstanced(r,t,n,e,s):i.drawArraysInstanced(r,e,t,s),l.update(o,t,s))}renderMultiDraw(e,t,s){const{extensions:i,mode:r,object:n,info:a}=this;if(0===s)return;const o=i.get("WEBGL_multi_draw");if(null===o)for(let i=0;i<s;i++)this.render(e[i],t[i]);else{0!==this.index?o.multiDrawElementsWEBGL(r,t,0,this.type,e,0,s):o.multiDrawArraysWEBGL(r,e,0,t,0,s);let i=0;for(let e=0;e<s;e++)i+=t[e];a.update(n,i,1)}}}class DT{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&&(Et(`TimestampQueryPool: No timestamp available for uid ${e}.`),t=0),t}hasTimestampQuery(e){return this.timestamps.has(e)}allocateQueriesForContext(){}async resolveQueriesAsync(){}dispose(){}}class OT extends DT{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 Et("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;this.currentQueryIndex+2>this.maxQueries&&(this.resolveQueriesAsync(),this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=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){At("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){At("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=[];this.timestamps.clear();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 a=await r;this.timestamps.set(i,a),t[n]+=a}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 At("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){At("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.timestamps.clear(),this.frames=[],this.lastValue=0,this.activeQuery=null}}}const IT=[];class UT extends yT{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 PT(this),this.capabilities=new BT(this),this.attributeUtils=new TT(this),this.textureUtils=new CT(this),this.bufferRenderer=new LT(this),this.state=new ST(this),this.utils=new wT(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.extensions.get("EXT_clip_control"),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"),t.reversedDepthBuffer&&(this.extensions.has("EXT_clip_control")?e.reversedDepthBuffer=!0:(Et("WebGPURenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer."),e.reversedDepthBuffer=!1)),e.reversedDepthBuffer&&this.state.setReversedDepth(!0)}get coordinateSystem(){return pt}get hasTimestamp(){return null!==this.disjoint}async getArrayBufferAsync(e,t=null,s=0,i=-1){return await this.attributeUtils.getArrayBufferAsync(e,t,s,i)}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&&Et("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 OT(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)this.updateScissor(e);else{const{width:e,height:s}=this.getDrawingBufferSize();t.scissor(0,0,e,s)}this.initTimestampQuery(gt,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):void 0!==s.lastOcclusionObject&&(s.lastOcclusionObject=void 0)}finishRender(e){const{gl:t,state:s}=this,i=this.get(e),r=i.previousContext;s.resetVertexState();if(e.occlusionQueryCount>0){const s=i.lastOcclusionObject;s&&!0===s.occlusionTest&&t.endQuery(t.ANY_SAMPLES_PASSED),this.resolveOccludedAsync(e)}const n=e.textures;if(null!==n)for(let e=0;e<n.length;e++){const t=n[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)}if(r.scissor)this.updateScissor(r);else{const{width:e,height:t}=this.getDrawingBufferSize();s.scissor(0,0,e,t)}}this.prepareTimestampBuffer(gt,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 a=!0;for(let t=0;t<s.length;t++){const n=s[t];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)):a=!1)}!1===a?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)}updateScissor(e){const{state:t}=this,{x:s,y:i,width:r,height:n}=e.scissorValue;t.scissor(s,e.height-n-i,r,n)}setScissorTest(e){this.state.setScissorTest(e)}resetState(){this.state.reset()}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:a,renderer:o}=this;if(null===i){i={textures:null,clearColorValue:this.getClearColor()}}let l=0;if(e&&(l|=a.COLOR_BUFFER_BIT),t&&(l|=a.DEPTH_BUFFER_BIT),s&&(l|=a.STENCIL_BUFFER_BIT),0!==l){let h;h=i.clearColorValue?i.clearColorValue:this.getClearColor();const u=o.getClearDepth(),c=o.getClearStencil();if(t&&this.state.setDepthMask(!0),s&&this.state.setStencilMask(4294967295),null===i.textures)e&&a.clearColor(h.r,h.g,h.b,h.a),t&&a.clearDepth(u),s&&a.clearStencil(c),a.clear(l);else{if(r&&this._setFramebuffer(i),e)for(let e=0;e<i.textures.length;e++){const t=i.mrt?i.mrt.getClearColor(i.textures[e].name):null;null!==t?a.clearBufferfv(a.COLOR,e,[t.r,t.g,t.b,t.a]):0===e?a.clearBufferfv(a.COLOR,e,[h.r,h.g,h.b,h.a]):a.clearBufferfv(a.COLOR,e,[0,0,0,1])}t&&s?a.clearBufferfi(a.DEPTH_STENCIL,0,u,c):t?a.clearBufferfv(a.DEPTH,0,[u]):s&&a.clearBufferiv(a.STENCIL,0,[c]),r&&n&&this._resolveRenderTarget(i),r&&null!==this._currentContext&&this._currentContext!==i&&this._setFramebuffer(this._currentContext)}}}beginCompute(e){const{state:t,gl:s}=this;t.bindFramebuffer(s.FRAMEBUFFER,null),this.initTimestampQuery(ft,this.getTimestampUID(e))}compute(e,t,s,i,r=null){const{state:n,gl:a}=this;!1===this.discard&&(n.enable(a.RASTERIZER_DISCARD),this.discard=!0);const{programGPU:o,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(o),this._bindUniforms(s);const d=this._getTransformFeedback(l);a.bindTransformFeedback(a.TRANSFORM_FEEDBACK,d),a.beginTransformFeedback(a.POINTS),r=null!==r?r:t.count,Array.isArray(r)?(Nt("WebGLBackend.compute(): The count parameter must be a single number, not an array."),r=r[0]):r&&"object"==typeof r&&r.isIndirectStorageBufferAttribute&&(Nt("WebGLBackend.compute(): The count parameter must be a single number, not IndirectStorageBufferAttribute"),r=t.count),h[0].isStorageInstancedBufferAttribute?a.drawArraysInstanced(a.POINTS,0,1,r):a.drawArrays(a.POINTS,0,r),a.endTransformFeedback(),a.bindTransformFeedback(a.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(ft,this.getTimestampUID(e)),this._currentContext&&this._setFramebuffer(this._currentContext)}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.isArrayTexture&&e.camera.isArrayCamera}_draw(e,t,s,i,r,n){if(e.isBatchedMesh)if(!1===this.hasFeature("WEBGL_multi_draw")){const{gl:s}=this,i=s.getUniformLocation(n,"nodeUniformDrawId"),r=e._multiDrawStarts,a=e._multiDrawCounts,o=e._multiDrawCount;for(let e=0;e<o;e++)s.uniform1ui(i,e),t.render(r[e],a[e])}else t.renderMultiDraw(e._multiDrawStarts,e._multiDrawCounts,e._multiDrawCount);else r>1?t.renderInstances(s,i,r):t.render(s,i)}draw(e){const{object:t,pipeline:s,material:i,context:r,hardwareClippingPlanes:n}=e,{programGPU:a}=this.get(s),{gl:o,state:l}=this,h=this.get(r),u=e.getDrawParameters();if(null===u)return;this._bindUniforms(e.getBindings());const c=t.isMesh&&t.matrixWorld.determinantAffine()<0;l.setMaterial(i,c,n),null!==r.mrt&&null!==r.textures&&l.setMRTBlending(r.textures,r.mrt,i),l.useProgram(a);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&&(o.endQuery(o.ANY_SAMPLES_PASSED),h.occlusionQueryIndex++),!0===t.occlusionTest){const e=o.createQuery();o.beginQuery(o.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=o.POINTS:t.isLineSegments?b.mode=o.LINES:t.isLine?b.mode=o.LINE_STRIP:t.isLineLoop?b.mode=o.LINE_LOOP:!0===i.wireframe?(l.setLineWidth(i.wireframeLinewidth*this.renderer.getPixelRatio()),b.mode=o.LINES):b.mode=o.TRIANGLES;const{vertexCount:_,instanceCount:x}=u;let{firstVertex:v}=u;if(b.object=t,null!==f){v*=f.array.BYTES_PER_ELEMENT;const e=this.get(f);b.index=f.count,b.type=e.type}else b.index=0;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=o.createBuffer();e[0]=s,o.bindBuffer(o.UNIFORM_BUFFER,i),o.bufferData(o.UNIFORM_BUFFER,e,o.STATIC_DRAW),t.push(i)}s.indexesGPU=t}let n=0;e:for(const t of e.getBindings())for(const e of t.bindings){if(e===r)break e;(e.isUniformsGroup||e.isUniformBuffer)&&n++}const h=this._currentContext.renderTarget,u=null===h||!0===h.isPostProcessingRenderTarget?this.renderer.getPixelRatio():1,c=this._isRenderCameraDepthArray(this._currentContext),d=this._currentContext.activeCubeFace;if(c){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=d,this._currentContext.activeCubeFace=d}}for(let r=0,h=i.length;r<h;r++){const h=i[r];if(t.layers.test(h.layers)){c&&(this.renderer._activeCubeFace=r,this._currentContext.activeCubeFace=r,this._setFramebuffer(this._currentContext));const i=h.viewport;if(void 0!==i){const t=i.x*u,s=i.y*u,r=i.width*u,n=i.height*u;l.viewport(Math.floor(t),Math.floor(e.context.height-n-s),Math.floor(r),Math.floor(n))}l.bindBufferBase(o.UNIFORM_BUFFER,n,s.indexesGPU[r]),this._draw(t,b,v,_,x,a)}this._currentContext.activeCubeFace=d,this.renderer._activeCubeFace=d}}else this._draw(t,b,v,_,x,a)}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 mT(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,a=s.createProgram(),o=this.get(r).shaderGPU,l=this.get(n).shaderGPU;if(s.attachShader(a,o),s.attachShader(a,l),s.linkProgram(a),this.set(i,{programGPU:a,fragmentShader:o,vertexShader:l}),null!==t&&this.parallel){const r=new Promise(t=>{const r=this.parallel,n=()=>{s.getProgramParameter(a,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"),a=this._getShaderErrors(i,t,"fragment");At("WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(e,i.VALIDATE_STATUS)+"\n\nProgram Info Log: "+r+"\n"+n+"\n"+a)}else""!==r&&Et("WebGLProgram: Program Info Log:",r)}}_completeCompile(e,t){const{state:s,gl:i}=this,r=this.get(t),{programGPU:n,fragmentShader:a,vertexShader:o}=r;!1===i.getProgramParameter(n,i.LINK_STATUS)&&this._logProgramError(n,a,o),s.useProgram(n);const l=e.getBindings();this._setupBindings(l,n),this.set(t,{programGPU:n,pipeline:n})}createComputePipeline(e,t,s=null){const{gl:i}=this,r={stage:"fragment",code:"#version 300 es\nprecision highp float;\nvoid main() {}"};this.createProgram(r);const{computeProgram:n}=e,a=i.createProgram(),o=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(a,o),i.attachShader(a,l),i.transformFeedbackVaryings(a,u,i.SEPARATE_ATTRIBS),i.linkProgram(a);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)}if(this.set(e,{programGPU:a,fragmentShader:o,vertexShader:l,transformBuffers:m,attributes:p}),null!==s&&this.parallel){const r=this.parallel,n=new Promise(s=>{const n=()=>{i.getProgramParameter(a,r.COMPLETION_STATUS_KHR)?(this._completeComputeCompile(e,t),s()):requestAnimationFrame(n)};n()});return void s.push(n)}this._completeComputeCompile(e,t)}_completeComputeCompile(e,t){const{state:s,gl:i}=this,{programGPU:r,fragmentShader:n,vertexShader:a}=this.get(e);!1===i.getProgramParameter(r,i.LINK_STATUS)&&this._logProgramError(r,n,a),s.useProgram(r),this._setupBindings(t,r)}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;for(const s of e.bindings){const e=this.get(s);if(s.isUniformsGroup||s.isUniformBuffer){const i=s.buffer,r=e.bufferGPU;t.bindBuffer(t.UNIFORM_BUFFER,r);const n=s.updateRanges;if(t.bindBuffer(t.UNIFORM_BUFFER,r),0===n.length)t.bufferData(t.UNIFORM_BUFFER,i,t.DYNAMIC_DRAW);else{const e=vt(i),s=e?1:i.BYTES_PER_ELEMENT;for(let r=0,a=n.length;r<a;r++){const a=n[r],o=a.start*s,l=a.count*s,h=o*(e?i.BYTES_PER_ELEMENT:1);t.bufferSubData(t.UNIFORM_BUFFER,h,i,o,l)}}this.set(s,e)}else if(s.isSampledTexture){const{textureGPU:t,glTextureType:i}=this.get(s.texture);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=vt(i),s=e?1:i.BYTES_PER_ELEMENT;let n=r[0].start;for(let a=0,o=r.length;a<o;a++){const o=r[a],l=r[a+1],h=o.start+o.count;if(void 0!==l&&l.start===h)continue;const u=n*s,c=(h-n)*s,d=u*(e?i.BYTES_PER_ELEMENT:1);t.bufferSubData(t.UNIFORM_BUFFER,d,i,u,c),void 0!==l&&(n=l.start)}}}}createUniformBuffer(e){const t=this.get(e);if(void 0===t.bufferGPU){const s=this.gl,i=e.buffer;t.bufferGPU=s.createBuffer(),s.bindBuffer(s.UNIFORM_BUFFER,t.bufferGPU),s.bufferData(s.UNIFORM_BUFFER,i.byteLength,s.DYNAMIC_DRAW)}}destroyUniformBuffer(e){const t=this.get(e);this.gl.deleteBuffer(t.bufferGPU),this.delete(e)}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(FT).filter(t=>FT[t]===e),s=this.extensions;for(let e=0;e<t.length;e++)if(s.has(t[e]))return!0;return!1}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)}hasCompatibility(e){return e===yt||super.hasCompatibility(e)}initRenderTarget(e){const{gl:t,state:s}=this;this._setFramebuffer(e),s.bindFramebuffer(t.FRAMEBUFFER,null)}_setFramebuffer(e){const{gl:t,state:s}=this;let i=null;if(null!==e.textures){const r=e.renderTarget,n=this.get(r),{depthBuffer:a,stencilBuffer:o}=r,l=!0===r.isCubeRenderTarget,h=!0===r.isRenderTarget3D,u=r.depth>1,c=!0===r.isXRRenderTarget,d=!0===c&&!0===r._hasExternalTextures;let p=n.msaaFrameBuffer,m=n.depthRenderbuffer;const f=this.extensions.get("WEBGL_multisampled_render_to_texture"),g=this.extensions.get("OVR_multiview2"),y=this._useMultisampledExtension(r);let b=r.samples;null!==e.depthTexture&&e.depthTexture.renderTarget!==r&&!1===y&&b>0&&(Nt('WebGLBackend: Shared depth texture is not supported with MSAA when "WEBGL_multisampled_render_to_texture" is unsupported. Falling back to single-sample rendering.'),b=0);const _=Fb(e);let x;if(l?(n.cubeFramebuffers||(n.cubeFramebuffers={}),x=n.cubeFramebuffers[_]):c&&!1===d?x=this._xrFramebuffer:(n.framebuffers||(n.framebuffers={}),x=n.framebuffers[_]),void 0===x){x=t.createFramebuffer(),s.bindFramebuffer(t.FRAMEBUFFER,x);const i=e.textures,a=[];if(l){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=_;const o=t.COLOR_ATTACHMENT0+s;if(r.multiview)g.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,o,a.textureGPU,0,b,0,2);else if(h||u){const e=this.renderer._activeCubeFace,s=this.renderer._activeMipmapLevel;t.framebufferTextureLayer(t.FRAMEBUFFER,o,a.textureGPU,s,e)}else if(y)f.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,o,t.TEXTURE_2D,a.textureGPU,0,b);else{const e=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,o,t.TEXTURE_2D,a.textureGPU,e)}}}const c=o?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(!0===r._autoAllocateDepthBuffer){const s=t.createRenderbuffer();this.textureUtils.setupRenderBufferStorage(s,e,0,y),n.xrDepthRenderbuffer=s,a.push(o?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT),t.bindRenderbuffer(t.RENDERBUFFER,s),t.framebufferRenderbuffer(t.FRAMEBUFFER,c,t.RENDERBUFFER,s)}else if(null!==e.depthTexture){a.push(o?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT);const s=this.get(e.depthTexture);if(s.renderTarget=e.renderTarget,s.cacheKey=_,r.multiview)g.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,c,s.textureGPU,0,b,0,2);else if(d&&y)f.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,c,t.TEXTURE_2D,s.textureGPU,0,b);else if(e.depthTexture.isArrayTexture){const e=this.renderer._activeCubeFace;t.framebufferTextureLayer(t.FRAMEBUFFER,c,s.textureGPU,0,e)}else if(e.depthTexture.isCubeTexture){const e=this.renderer._activeCubeFace;t.framebufferTexture2D(t.FRAMEBUFFER,c,t.TEXTURE_CUBE_MAP_POSITIVE_X+e,s.textureGPU,0)}else t.framebufferTexture2D(t.FRAMEBUFFER,c,t.TEXTURE_2D,s.textureGPU,0)}n.depthInvalidationArray=a}else{if(this._isRenderCameraDepthArray(e)){s.bindFramebuffer(t.FRAMEBUFFER,x);const i=this.renderer._activeCubeFace,r=this.get(e.depthTexture),n=o?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;t.framebufferTextureLayer(t.FRAMEBUFFER,n,r.textureGPU,0,i)}if((c||y||r.multiview)&&!0!==r._isOpaqueFramebuffer){s.bindFramebuffer(t.FRAMEBUFFER,x);const i=this.get(e.textures[0]);r.multiview?g.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,i.textureGPU,0,b,0,2):y?f.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,i.textureGPU,0,b):t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,i.textureGPU,0);const a=o?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?g.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,a,s.textureGPU,0,b,0,2):y?f.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,a,t.TEXTURE_2D,s.textureGPU,0,b):t.framebufferTexture2D(t.FRAMEBUFFER,a,t.TEXTURE_2D,s.textureGPU,0)}}}if(b>0&&!1===y&&!r.multiview){if(void 0===p){p=t.createFramebuffer(),s.bindFramebuffer(t.FRAMEBUFFER,p);const i=[],r=e.textures;for(let s=0;s<r.length;s++){i[s]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,i[s]);const r=e.textures[s],n=this.get(r);t.renderbufferStorageMultisample(t.RENDERBUFFER,b,n.glInternalFormat,e.width,e.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+s,t.RENDERBUFFER,i[s])}t.bindRenderbuffer(t.RENDERBUFFER,null),n.msaaFrameBuffer=p,n.msaaRenderbuffers=i,a&&void 0===m&&(m=t.createRenderbuffer(),this.textureUtils.setupRenderBufferStorage(m,e,b),n.depthRenderbuffer=m)}i=n.msaaFrameBuffer}else i=x;s.drawBuffers(e,x)}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,a;t.bindBuffer(t.ARRAY_BUFFER,r.bufferGPU),t.enableVertexAttribArray(s),!0===i.isInterleavedBufferAttribute?(n=i.data.stride*r.bytesPerElement,a=i.offset*r.bytesPerElement):(n=0,a=0),r.isInteger?t.vertexAttribIPointer(s,i.itemSize,r.type,n,a):t.vertexAttribPointer(s,i.itemSize,r.type,i.normalized,n,a),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;let i=0,r=0;for(const n of e)for(const e of n.bindings)if(e.isUniformsGroup||e.isUniformBuffer){const r=i++,n=s.getUniformBlockIndex(t,e.name);s.uniformBlockBinding(t,n,r)}else if(e.isSampledTexture){const i=r++,n=s.getUniformLocation(t,e.name);s.uniform1i(n,i)}}_bindUniforms(e){const{gl:t,state:s}=this;let i=0,r=0;for(const n of e)for(const e of n.bindings){const n=this.get(e);if(e.isUniformsGroup||e.isUniformBuffer){const e=i++;s.bindBufferBase(t.UNIFORM_BUFFER,e,n.bufferGPU)}else if(e.isSampledTexture){const e=r++;s.bindTexture(n.glTextureType,n.textureGPU,t.TEXTURE0+e)}}}_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&&void 0!==r.msaaFrameBuffer&&!1===this._useMultisampledExtension(i)){const n=r.framebuffers[e.getCacheKey()];let a=!1===i.resolveColorBuffer?0:t.COLOR_BUFFER_BIT;i.resolveDepthBuffer&&(i.depthBuffer&&(a|=t.DEPTH_BUFFER_BIT),i.stencilBuffer&&i.resolveStencilBuffer&&(a|=t.STENCIL_BUFFER_BIT));const o=r.msaaFrameBuffer,l=r.msaaRenderbuffers,h=e.textures,u=h.length>1;if(s.bindFramebuffer(t.READ_FRAMEBUFFER,o),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,o=e.height-n-i;t.blitFramebuffer(s,o,s+r,o+n,s,o,s+r,o+n,a,t.NEAREST)}else t.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,a,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)}if(!0===this._supportsInvalidateFramebuffer){if(!1===i.storeMultisampledColorBuffer)for(let e=0;e<h.length;e++)IT.push(t.COLOR_ATTACHMENT0+e);i.depthBuffer&&!1===i.storeMultisampledDepthBuffer&&IT.push(i.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT),IT.length>0&&(t.invalidateFramebuffer(t.READ_FRAMEBUFFER,IT),IT.length=0)}}else if(!0===this._supportsInvalidateFramebuffer&&r.framebuffers&&(!0===i._autoAllocateDepthBuffer||i.samples>0&&!1===i.storeMultisampledDepthBuffer)){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}async dispose(){await super.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 kT="point-list",zT="line-list",VT="line-strip",GT="triangle-list",$T="undefined"!=typeof self&&self.GPUShaderStage?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},jT="never",WT="less",HT="equal",qT="less-equal",XT="greater",YT="not-equal",KT="greater-equal",QT="always",ZT="store",JT="discard",eS="load",tS="clear",sS="ccw",iS="cw",rS="none",nS="back",aS="uint16",oS="uint32",lS="r8unorm",hS="r8snorm",uS="r8uint",cS="r8sint",dS="r16uint",pS="r16sint",mS="r16float",fS="rg8unorm",gS="rg8snorm",yS="rg8uint",bS="rg8sint",_S="r16unorm",xS="r16snorm",vS="r32uint",TS="r32sint",SS="r32float",wS="rg16uint",MS="rg16sint",ES="rg16float",AS="rgba8unorm",NS="rgba8unorm-srgb",CS="rgba8snorm",RS="rgba8uint",PS="rgba8sint",BS="bgra8unorm",FS="bgra8unorm-srgb",LS="rg16unorm",DS="rg16snorm",OS="rgb9e5ufloat",IS="rgb10a2unorm",US="rg11b10ufloat",kS="rg32uint",zS="rg32sint",VS="rg32float",GS="rgba16uint",$S="rgba16sint",jS="rgba16float",WS="rgba16unorm",HS="rgba16snorm",qS="rgba32uint",XS="rgba32sint",YS="rgba32float",KS="depth16unorm",QS="depth24plus",ZS="depth24plus-stencil8",JS="depth32float",ew="depth32float-stencil8",tw="bc1-rgba-unorm",sw="bc1-rgba-unorm-srgb",iw="bc2-rgba-unorm",rw="bc2-rgba-unorm-srgb",nw="bc3-rgba-unorm",aw="bc3-rgba-unorm-srgb",ow="bc4-r-unorm",lw="bc4-r-snorm",hw="bc5-rg-unorm",uw="bc5-rg-snorm",cw="bc6h-rgb-ufloat",dw="bc6h-rgb-float",pw="bc7-rgba-unorm",mw="bc7-rgba-unorm-srgb",fw="etc2-rgb8unorm",gw="etc2-rgb8unorm-srgb",yw="etc2-rgb8a1unorm",bw="etc2-rgb8a1unorm-srgb",_w="etc2-rgba8unorm",xw="etc2-rgba8unorm-srgb",vw="eac-r11unorm",Tw="eac-r11snorm",Sw="eac-rg11unorm",ww="eac-rg11snorm",Mw="astc-4x4-unorm",Ew="astc-4x4-unorm-srgb",Aw="astc-5x4-unorm",Nw="astc-5x4-unorm-srgb",Cw="astc-5x5-unorm",Rw="astc-5x5-unorm-srgb",Pw="astc-6x5-unorm",Bw="astc-6x5-unorm-srgb",Fw="astc-6x6-unorm",Lw="astc-6x6-unorm-srgb",Dw="astc-8x5-unorm",Ow="astc-8x5-unorm-srgb",Iw="astc-8x6-unorm",Uw="astc-8x6-unorm-srgb",kw="astc-8x8-unorm",zw="astc-8x8-unorm-srgb",Vw="astc-10x5-unorm",Gw="astc-10x5-unorm-srgb",$w="astc-10x6-unorm",jw="astc-10x6-unorm-srgb",Ww="astc-10x8-unorm",Hw="astc-10x8-unorm-srgb",qw="astc-10x10-unorm",Xw="astc-10x10-unorm-srgb",Yw="astc-12x10-unorm",Kw="astc-12x10-unorm-srgb",Qw="astc-12x12-unorm",Zw="astc-12x12-unorm-srgb",Jw="clamp-to-edge",eM="repeat",tM="mirror-repeat",sM="linear",iM="nearest",rM="zero",nM="one",aM="src",oM="one-minus-src",lM="src-alpha",hM="one-minus-src-alpha",uM="dst",cM="one-minus-dst",dM="dst-alpha",pM="one-minus-dst-alpha",mM="src-alpha-saturated",fM="constant",gM="one-minus-constant",yM="add",bM="subtract",_M="reverse-subtract",xM="min",vM="max",TM=0,SM=15,wM="keep",MM="zero",EM="replace",AM="invert",NM="increment-clamp",CM="decrement-clamp",RM="increment-wrap",PM="decrement-wrap",BM="storage",FM="read-only-storage",LM="write-only",DM="read-only",OM="read-write",IM="non-filtering",UM="comparison",kM="float",zM="unfilterable-float",VM="depth",GM="sint",$M="uint",jM="2d",WM="3d",HM="2d",qM="2d-array",XM="cube",YM="3d",KM="all",QM="vertex",ZM="instance",JM={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"},eE={"texture-compression-s3tc":"texture-compression-bc","texture-compression-etc1":"texture-compression-etc2"};class tE extends eT{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 sE extends qv{constructor(e,t){super(e,t?t.array:null),this._attribute=t,this.isStorageBuffer=!0}get attribute(){return this._attribute}}let iE=0;class rE extends sE{constructor(e,t){super("StorageBuffer_"+(e&&e.name?e.name:iE++),e?e.value:null),this.nodeUniform=e,this.access=e?e.access:ia,this.groupNode=t}get attribute(){return this.nodeUniform.value}get buffer(){return this.nodeUniform.value.array}}const nE=[null];class aE{constructor(e){this.backend=e,this._preferredCanvasFormat=null}getCurrentDepthStencilFormat(e){let t;return e.depth&&(t=null!==e.depthTexture?this.getTextureFormatGPU(e.depthTexture):e.stencil?!0===this.backend.renderer.reversedDepthBuffer?ew:ZS:!0===this.backend.renderer.reversedDepthBuffer?JS:QS),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 s=this.backend.get(e);t=void 0!==s.texture?s.texture.sampleCount:this.backend.renderer.currentSamples}else e.renderTarget&&(t=e.renderTarget.samples);t=this.getSampleCount(t||1);const s=t>1&&null!==e.renderTarget&&!0!==e.isDepthTexture&&!0!==e.isFramebufferTexture,i=t>1&&null!==e.renderTarget&&!0===e.isDepthTexture&&!0===e.isArrayTexture;return{samples:t,primarySamples:s||i?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?kT:e.isLineSegments||e.isMesh&&!0===t.wireframe?zT:e.isLine?VT:e.isMesh?GT: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 null===this._preferredCanvasFormat&&(this._preferredCanvasFormat=navigator.gpu.getPreferredCanvasFormat()),this._preferredCanvasFormat;if(e===W)return BS;if(e===Z)return jS;throw new Error("THREE.WebGPUUtils: Unsupported output buffer type.")}}function oE(e,t){nE[0]=t,e.queue.submit(nE),nE[0]=null}class lE{constructor(){this.label="",this.layout=null,this.entries=[]}reset(){this.label="",this.layout=null,this.entries.length=0}}class hE{constructor(){this.label="",this.size=0,this.usage=0,this.mappedAtCreation=!1}reset(){this.label="",this.size=0,this.usage=0,this.mappedAtCreation=!1}}class uE{constructor(){this.label=""}reset(){this.label=""}}class cE{constructor(){this.label="",this.colorFormats=null,this.depthStencilFormat=void 0,this.sampleCount=1,this.depthReadOnly=!1,this.stencilReadOnly=!1}reset(){this.label="",this.colorFormats=null,this.depthStencilFormat=void 0,this.sampleCount=1,this.depthReadOnly=!1,this.stencilReadOnly=!1}}class dE{constructor(){this.view=null,this.depthSlice=void 0,this.resolveTarget=void 0,this.clearValue=void 0,this.loadOp=void 0,this.storeOp=void 0}reset(){this.view=null,this.depthSlice=void 0,this.resolveTarget=void 0,this.clearValue=void 0,this.loadOp=void 0,this.storeOp=void 0}}class pE{constructor(){this.label="",this.colorAttachments=[],this.depthStencilAttachment=void 0,this.occlusionQuerySet=void 0,this.timestampWrites=void 0,this.maxDrawCount=5e7}reset(){this.label="",this.colorAttachments.length=0,this.depthStencilAttachment=void 0,this.occlusionQuerySet=void 0,this.timestampWrites=void 0,this.maxDrawCount=5e7}}class mE{constructor(){this.label="",this.layout=null,this.vertex=null,this.primitive={},this.depthStencil=void 0,this.multisample=new fE,this.fragment=null}reset(){this.label="",this.layout=null,this.vertex=null,this.primitive={},this.depthStencil=void 0,this.multisample.reset(),this.fragment=null}}class fE{constructor(){this.count=1,this.mask=4294967295,this.alphaToCoverageEnabled=!1}reset(){this.count=1,this.mask=4294967295,this.alphaToCoverageEnabled=!1}}class gE{constructor(){this.label="",this.code="",this.compilationHints=[]}reset(){this.label="",this.code="",this.compilationHints.length=0}}class yE{constructor(){this.label="",this.size={width:0,height:1,depthOrArrayLayers:1},this.mipLevelCount=1,this.sampleCount=1,this.dimension="2d",this.format=void 0,this.usage=void 0,this.viewFormats=[],this.textureBindingViewDimension=void 0}reset(){this.label="",this.size.width=0,this.size.height=1,this.size.depthOrArrayLayers=1,this.mipLevelCount=1,this.sampleCount=1,this.dimension="2d",this.format=void 0,this.usage=void 0,this.viewFormats.length=0,this.textureBindingViewDimension=void 0}}class bE{constructor(){this.label="",this.format=void 0,this.dimension=void 0,this.usage=0,this.aspect="all",this.baseMipLevel=0,this.mipLevelCount=void 0,this.baseArrayLayer=0,this.arrayLayerCount=void 0,this.swizzle="rgba"}reset(){this.label="",this.format=void 0,this.dimension=void 0,this.usage=0,this.aspect="all",this.baseMipLevel=0,this.mipLevelCount=void 0,this.baseArrayLayer=0,this.arrayLayerCount=void 0,this.swizzle="rgba"}}const _E=new lE,xE=new hE,vE=new uE,TE=new cE,SE=new pE,wE=new mE,ME=new dE,EE=new gE,AE=new yE,NE=new bE;class CE extends rb{constructor(e){super(),this.device=e;this.mipmapSampler=e.createSampler({minFilter:sM}),this.flipYSampler=e.createSampler({minFilter:iM}),xE.size=4,xE.usage=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,this.flipUniformBuffer=e.createBuffer(xE),xE.reset(),e.queue.writeBuffer(this.flipUniformBuffer,0,new Uint32Array([1])),xE.size=4,xE.usage=GPUBufferUsage.UNIFORM,this.noFlipUniformBuffer=e.createBuffer(xE),xE.reset(),this.transferPipelines={},EE.label="mipmap",EE.code="\nstruct VarysStruct {\n\t@builtin( position ) Position: vec4f,\n\t@location( 0 ) vTex : vec2f,\n\t@location( 1 ) @interpolate(flat, either) vBaseArrayLayer: u32,\n};\n\n@group( 0 ) @binding ( 2 )\nvar<uniform> flipY: u32;\n\n@vertex\nfn mainVS(\n\t\t@builtin( vertex_index ) vertexIndex : u32,\n\t\t@builtin( instance_index ) instanceIndex : u32 ) -> VarysStruct {\n\n\tvar Varys : VarysStruct;\n\n\tvar pos = array(\n\t\tvec2f( -1, -1 ),\n\t\tvec2f( -1, 3 ),\n\t\tvec2f( 3, -1 ),\n\t);\n\n\tlet p = pos[ vertexIndex ];\n\tlet mult = select( vec2f( 0.5, -0.5 ), vec2f( 0.5, 0.5 ), flipY != 0 );\n\tVarys.vTex = p * mult + vec2f( 0.5 );\n\tVarys.Position = vec4f( p, 0, 1 );\n\tVarys.vBaseArrayLayer = instanceIndex;\n\n\treturn Varys;\n\n}\n\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img2d : texture_2d<f32>;\n\n@fragment\nfn main_2d( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {\n\n\treturn textureSample( img2d, imgSampler, Varys.vTex );\n\n}\n\n@group( 0 ) @binding( 1 )\nvar img2dArray : texture_2d_array<f32>;\n\n@fragment\nfn main_2d_array( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {\n\n\treturn textureSample( img2dArray, imgSampler, Varys.vTex, Varys.vBaseArrayLayer );\n\n}\n\nconst faceMat = array(\n mat3x3f( 0, 0, -2, 0, -2, 0, 1, 1, 1 ), // pos-x\n mat3x3f( 0, 0, 2, 0, -2, 0, -1, 1, -1 ), // neg-x\n mat3x3f( 2, 0, 0, 0, 0, 2, -1, 1, -1 ), // pos-y\n mat3x3f( 2, 0, 0, 0, 0, -2, -1, -1, 1 ), // neg-y\n mat3x3f( 2, 0, 0, 0, -2, 0, -1, 1, 1 ), // pos-z\n mat3x3f( -2, 0, 0, 0, -2, 0, 1, 1, -1 ), // neg-z\n);\n\n@group( 0 ) @binding( 1 )\nvar imgCube : texture_cube<f32>;\n\n@fragment\nfn main_cube( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {\n\n\treturn textureSample( imgCube, imgSampler, faceMat[ Varys.vBaseArrayLayer ] * vec3f( fract( Varys.vTex ), 1 ) );\n\n}\n",this.mipmapShaderModule=e.createShaderModule(EE),EE.reset()}getTransferPipeline(e,t){const s=`${e}-${t=t||"2d-array"}`;let i=this.transferPipelines[s];return void 0===i&&(wE.label=`mipmap-${e}-${t}`,wE.vertex={module:this.mipmapShaderModule},wE.fragment={module:this.mipmapShaderModule,entryPoint:`main_${t.replace("-","_")}`,targets:[{format:e}]},wE.layout="auto",i=this.device.createRenderPipeline(wE),wE.reset(),this.transferPipelines[s]=i),i}flipY(e,t,s=0){const i=t.format,{width:r,height:n}=t.size;AE.size.width=r,AE.size.height=n,AE.format=i,AE.usage=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING;const a=this.device.createTexture(AE);AE.reset();const o=this.getTransferPipeline(i,e.textureBindingViewDimension),l=this.getTransferPipeline(i,a.textureBindingViewDimension),h=this.device.createCommandEncoder(vE),u=(e,t,s,i,r,n)=>{const a=e.getBindGroupLayout(0);NE.dimension=t.textureBindingViewDimension||"2d-array",NE.mipLevelCount=1;const o=t.createView(NE);NE.reset(),_E.layout=a,_E.entries.push({binding:0,resource:this.flipYSampler},{binding:1,resource:o},{binding:2,resource:{buffer:n?this.flipUniformBuffer:this.noFlipUniformBuffer}});const l=this.device.createBindGroup(_E);_E.reset(),NE.dimension="2d",NE.mipLevelCount=1,NE.baseArrayLayer=r,NE.arrayLayerCount=1;const u=i.createView(NE);NE.reset(),ME.view=u,ME.loadOp=tS,ME.storeOp=ZT,SE.colorAttachments.push(ME);const c=h.beginRenderPass(SE);SE.reset(),ME.reset(),c.setPipeline(e),c.setBindGroup(0,l),c.draw(3,1,0,s),c.end()};u(o,e,s,a,0,!1),u(l,a,0,e,s,!0),oE(this.device,h.finish()),a.destroy()}generateMipmaps(e,t=null){const s=this.get(e),i=s.layers||this._mipmapCreateBundles(e);let r=t;null===r&&(vE.label="mipmapEncoder",r=this.device.createCommandEncoder(vE),vE.reset()),this._mipmapRunBundles(r,i),null===t&&oE(this.device,r.finish()),s.layers=i}_mipmapCreateBundles(e){const t=e.textureBindingViewDimension||"2d-array",s=this.getTransferPipeline(e.format,t),i=s.getBindGroupLayout(0),r=[];for(let n=1;n<e.mipLevelCount;n++)for(let a=0;a<e.depthOrArrayLayers;a++){NE.dimension=t,NE.baseMipLevel=n-1,NE.mipLevelCount=1;const o=e.createView(NE);NE.reset(),_E.layout=i,_E.entries.push({binding:0,resource:this.mipmapSampler},{binding:1,resource:o},{binding:2,resource:{buffer:this.noFlipUniformBuffer}});const l=this.device.createBindGroup(_E);_E.reset(),NE.dimension="2d",NE.baseMipLevel=n,NE.mipLevelCount=1,NE.baseArrayLayer=a,NE.arrayLayerCount=1;const h=e.createView(NE);NE.reset();const u=new dE;u.view=h,u.loadOp=tS,u.storeOp=ZT;const c=new pE;c.colorAttachments.push(u),TE.colorFormats=[e.format];const d=this.device.createRenderBundleEncoder(TE);TE.reset(),d.setPipeline(s),d.setBindGroup(0,l),d.draw(3,1,0,a),r.push({renderBundles:[d.finish()],passDescriptor:c})}return r}_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()}}}class RE{constructor(){this.texture=null,this.mipLevel=0,this.origin={x:0,y:0,z:0},this.aspect="all"}reset(){this.texture=null,this.mipLevel=0,this.origin.x=0,this.origin.y=0,this.origin.z=0,this.aspect="all"}}class PE{constructor(){this.width=0,this.height=1,this.depthOrArrayLayers=1}reset(){this.width=0,this.height=1,this.depthOrArrayLayers=1}}const BE=new hE,FE=new uE,LE=new class{constructor(){this.label="",this.addressModeU="clamp-to-edge",this.addressModeV="clamp-to-edge",this.addressModeW="clamp-to-edge",this.magFilter="nearest",this.minFilter="nearest",this.mipmapFilter="nearest",this.lodMinClamp=0,this.lodMaxClamp=32,this.compare=void 0,this.maxAnisotropy=1}reset(){this.label="",this.addressModeU="clamp-to-edge",this.addressModeV="clamp-to-edge",this.addressModeW="clamp-to-edge",this.magFilter="nearest",this.minFilter="nearest",this.mipmapFilter="nearest",this.lodMinClamp=0,this.lodMaxClamp=32,this.compare=void 0,this.maxAnisotropy=1}},DE=new RE,OE=new class{constructor(){this.buffer=null,this.offset=0,this.bytesPerRow=void 0,this.rowsPerImage=void 0}reset(){this.buffer=null,this.offset=0,this.bytesPerRow=void 0,this.rowsPerImage=void 0}},IE=new class{constructor(){this.offset=0,this.bytesPerRow=void 0,this.rowsPerImage=void 0}reset(){this.offset=0,this.bytesPerRow=void 0,this.rowsPerImage=void 0}},UE=new class{constructor(){this.source=null,this.origin={x:0,y:0},this.flipY=!1}reset(){this.source=null,this.origin.x=0,this.origin.y=0,this.flipY=!1}},kE=new class extends RE{constructor(){super(),this.colorSpace="srgb",this.premultipliedAlpha=!1}reset(){super.reset(),this.colorSpace="srgb",this.premultipliedAlpha=!1}},zE=new yE,VE=new PE,GE={[it]:"never",[rt]:"less",[nt]:"equal",[at]:"less-equal",[ot]:"greater",[ht]:"greater-equal",[ut]:"always",[lt]:"not-equal"},$E=[0,1,3,2,4,5];function jE(e,t,s,i,r,n,a,o,l,h){DE.texture=t,DE.mipLevel=s,DE.origin.z=i,IE.offset=i*n,IE.bytesPerRow=a,IE.rowsPerImage=o,VE.width=l,VE.height=h,e.queue.writeTexture(DE,r.data,IE,VE),DE.reset(),IE.reset(),VE.reset()}class WE{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.texture,i=e.textureNode,r=!0===s.isDepthTexture&&null!==s.compareFunction&&i.isSampleCompare()&&t.hasCompatibility(yt),n=s.minFilter+"-"+s.magFilter+"-"+s.wrapS+"-"+s.wrapT+"-"+(s.wrapR||"0")+"-"+s.anisotropy+"-"+(!0===s.isDepthTexture?1:0)+"-"+(r?s.compareFunction:0);let a=this._samplerCache.get(n);if(void 0===a){LE.addressModeU=this._convertAddressMode(s.wrapS),LE.addressModeV=this._convertAddressMode(s.wrapT),LE.addressModeW=this._convertAddressMode(s.wrapR),LE.magFilter=this._convertFilterMode(s.magFilter),LE.minFilter=this._convertFilterMode(s.minFilter),LE.mipmapFilter=this._convertMipmapFilterMode(s.minFilter),s.isDepthTexture&&!1===r&&(LE.magFilter=iM,LE.minFilter=iM,LE.mipmapFilter=iM),LE.magFilter===sM&&LE.minFilter===sM&&LE.mipmapFilter===sM&&(LE.maxAnisotropy=s.anisotropy),r&&(LE.compare=GE[s.compareFunction]);const e=t.device.createSampler(LE);LE.reset(),a={sampler:e,usedTimes:0},this._samplerCache.set(n,a)}const o=t.get(e);return o.sampler!==a.sampler&&(this._releaseSampler(o),o.samplerKey=n,o.sampler=a.sampler,a.usedTimes++),n}destroySampler(e){this._releaseSampler(this.backend.get(e))}_releaseSampler(e){if(void 0!==e.sampler){const t=this._samplerCache.get(e.samplerKey);t.usedTimes--,0===t.usedTimes&&this._samplerCache.delete(e.samplerKey),e.sampler=void 0,e.samplerKey=void 0}}createDefaultTexture(e){let t;const s=HE(e,this.backend.device);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){if(!0===i.externalTexture)return;throw new Error("THREE.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:a,levels:o}=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||HE(e,s.device);i.format=h;const{samples:u,primarySamples:c,isMSAA:d}=s.utils.getTextureSampleData(e),p=e.renderTarget,m=u>1&&null!==p&&a>1&&l===jM,f=void 0!==GPUTextureUsage.TRANSIENT_ATTACHMENT&&!1===m,g=!0===e.isDepthTexture&&f&&!1===p?.storeMultisampledDepthBuffer&&(!1===p.stencilBuffer||!1===p.storeMultisampledStencilBuffer),y=!0!==e.isDepthTexture&&f&&!1===p?.storeMultisampledColorBuffer;let b=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC;!0===e.isStorageTexture&&(b|=GPUTextureUsage.STORAGE_BINDING),!0!==e.isCompressedTexture&&!0!==e.isCompressedArrayTexture&&h!==OS&&(b|=GPUTextureUsage.RENDER_ATTACHMENT),c>1&&g&&(b=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TRANSIENT_ATTACHMENT);const _=new yE;if(_.label=e.name,_.size.width=r,_.size.height=n,_.size.depthOrArrayLayers=a,_.mipLevelCount=o,_.sampleCount=c,_.dimension=l,_.format=h,_.usage=b,void 0===h)return Et("WebGPURenderer: Texture format not supported."),void this.createDefaultTexture(e);e.isCubeTexture&&(_.textureBindingViewDimension=XM);try{i.texture=s.device.createTexture(_)}catch(t){return Et("WebGPURenderer: Failed to create texture with descriptor:",_),void this.createDefaultTexture(e)}if(d||m){const e=Object.assign({},_);if(e.label=e.label+"-msaa",e.sampleCount=u,e.mipLevelCount=1,(g||y)&&(e.usage=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TRANSIENT_ATTACHMENT),m){e.size=Object.assign({},e.size,{depthOrArrayLayers:1}),i.msaaTextures=[];for(let t=0;t<a;t++)e.label=_.label+"-msaa-"+t,i.msaaTextures.push(s.device.createTexture(e))}else i.msaaTexture=s.device.createTexture(e)}i.initialized=!0,i.textureDescriptorGPU=_}destroyTexture(e,t=!1){const s=this.backend,i=s.get(e);if(void 0!==i.texture&&!1===t&&!0!==e.isExternalTexture&&!0!==i.externalTexture&&i.texture.destroy(),void 0!==i.msaaTexture&&i.msaaTexture.destroy(),void 0!==i.msaaTextures)for(const e of i.msaaTextures)e.destroy();s.delete(e)}generateMipmaps(e,t=null){const s=this.backend.get(e);this._generateMipmaps(s.texture,t)}getColorBuffer(){const e=this.backend,t=e.renderer.getCanvasTarget(),{width:s,height:i}=e.getDrawingBufferSize(),r=e.renderer.currentSamples,n=t.colorTexture,a=e.get(n);if(n.width===s&&n.height===i&&n.samples===r)return a.texture;let o=a.texture;return o&&o.destroy(),zE.label="colorBuffer",zE.size.width=s,zE.size.height=i,zE.sampleCount=e.utils.getSampleCount(e.renderer.currentSamples),zE.format=e.utils.getPreferredCanvasFormat(),zE.usage=GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,o=e.device.createTexture(zE),zE.reset(),n.source.width=s,n.source.height=i,n.samples=r,a.texture=o,o}getDepthBuffer(e=!0,t=!1){const s=this.backend,i=s.renderer.getCanvasTarget(),{width:r,height:n}=s.getDrawingBufferSize(),a=s.renderer.currentSamples,o=i.depthTexture;if(o.width===r&&o.height===n&&o.samples===a&&o.depth===e&&o.stencil===t)return s.get(o).texture;const l=s.get(o).texture;let h,u;if(t?(h=le,u=!0===s.renderer.reversedDepthBuffer?Q:te):e&&(h=oe,u=!0===s.renderer.reversedDepthBuffer?Q:K),void 0!==l){if(o.image.width===r&&o.image.height===n&&o.format===h&&o.type===u&&o.samples===a)return l;this.destroyTexture(o)}return o.name="depthBuffer",o.format=h,o.type=u,o.image.width=r,o.image.height=n,o.samples=a,this.createTexture(o,{width:r,height:n}),s.get(o).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)if(e.layerUpdates&&e.layerUpdates.size>0){for(const i of e.layerUpdates)this._copyBufferToTexture(t.image,s.texture,r,i,e.flipY,i);e.clearLayerUpdates()}else 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)e.isCompressedArrayTexture&&e.layerUpdates.size>0?(this._copyCompressedBufferToTexture(e.mipmaps,s.texture,r,e.layerUpdates),e.clearLayerUpdates()):this._copyCompressedBufferToTexture(e.mipmaps,s.texture,r);else if(e.isCubeTexture)this._copyCubeMapToTexture(e,s.texture,r);else if(e.isHTMLTexture){const t=this.backend.device,i=this.backend.renderer.domElement,n=e.image;if("function"!=typeof t.queue.copyElementImageToTexture)return;if(!s.hasPaintCallback)return s.hasPaintCallback=!0,void i.requestPaint();const a=r.size.width,o=r.size.height;2===t.queue.copyElementImageToTexture.length?t.queue.copyElementImageToTexture({source:n},{destination:{texture:s.texture},width:a,height:o}):t.queue.copyElementImageToTexture(n,a,o,{texture:s.texture}),e.flipY&&this._flipY(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 a=this.backend.device,o=this.backend.get(e),l=o.texture,h=o.textureDescriptorGPU.format,u=this._getBytesPerTexel(h);let c=i*u;c=256*Math.ceil(c/256),BE.size=(r-1)*c+i*u,BE.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ;const d=a.createBuffer(BE);BE.reset();const p=a.createCommandEncoder(FE);DE.texture=l,DE.origin.x=t,DE.origin.y=s,DE.origin.z=n,OE.buffer=d,OE.bytesPerRow=c,VE.width=i,VE.height=r,p.copyTextureToBuffer(DE,OE,VE),DE.reset(),OE.reset(),VE.reset();const m=this._getTypedArrayType(h);oE(a,p.finish()),await d.mapAsync(GPUMapMode.READ);const f=d.getMappedRange().slice();return d.destroy(),new m(f)}dispose(){this._samplerCache.clear()}_getDefaultTextureGPU(e){let t=this.defaultTexture[e];if(void 0===t){const s=new hs;s.minFilter=k,s.magFilter=k,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 Or;s.minFilter=k,s.magFilter=k,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 a=i[n],o=!0===e.flipY?$E[n]:n;a.isDataTexture?this._copyBufferToTexture(a.image,t,s,o,e.flipY):this._copyImageToTexture(a,t,s,o,e.flipY,e.premultiplyAlpha);for(let i=0;i<r.length;i++){const a=r[i].images[n];a.isDataTexture?this._copyBufferToTexture(a.image,t,s,o,e.flipY,0,i+1):this._copyImageToTexture(a,t,s,o,e.flipY,e.premultiplyAlpha,i+1)}}}_copyImageToTexture(e,t,s,i,r,n,a=0){const o=this.backend.device,l=a>0?e.width:s.size.width,h=a>0?e.height:s.size.height;UE.source=e,UE.flipY=r,kE.texture=t,kE.mipLevel=a,kE.origin.z=i,kE.premultipliedAlpha=n,VE.width=l,VE.height=h;try{o.queue.copyExternalImageToTexture(UE,kE,VE)}catch(e){}finally{UE.reset(),kE.reset(),VE.reset()}}_getPassUtils(){let e=this._passUtils;return null===e&&(this._passUtils=e=new CE(this.backend.device)),e}_generateMipmaps(e,t=null){this._getPassUtils().generateMipmaps(e,t)}_flipY(e,t,s=0){this._getPassUtils().flipY(e,t,s)}_copyBufferToTexture(e,t,s,i,r,n=0,a=0){const o=this.backend.device,l=e.data,h=this._getBytesPerTexel(s.format),u=e.width*h;DE.texture=t,DE.mipLevel=a,DE.origin.z=i,IE.offset=e.width*e.height*h*n,IE.bytesPerRow=u,VE.width=e.width,VE.height=e.height,o.queue.writeTexture(DE,l,IE,VE),DE.reset(),IE.reset(),VE.reset(),!0===r&&this._flipY(t,s,i)}_copyCompressedBufferToTexture(e,t,s,i=null){const r=this.backend.device,n=this._getBlockData(s.format),a=s.size.depthOrArrayLayers>1,o=i&&i.size>0?i:null;for(let i=0;i<e.length;i++){const l=e[i],h=l.width,u=l.height,c=a?s.size.depthOrArrayLayers:1,d=Math.ceil(h/n.width)*n.byteLength,p=Math.ceil(u/n.height),m=d*p,f=Math.ceil(h/n.width)*n.width,g=p*n.height;if(null!==o)for(const e of o)jE(r,t,i,e,l,m,d,p,f,g);else for(let e=0;e<c;e++)jE(r,t,i,e,l,m,d,p,f,g)}}_getBlockData(e){return e===tw||e===sw?{byteLength:8,width:4,height:4}:e===iw||e===rw||e===nw||e===aw?{byteLength:16,width:4,height:4}:e===ow||e===lw?{byteLength:8,width:4,height:4}:e===hw||e===uw||e===cw||e===dw||e===pw||e===mw?{byteLength:16,width:4,height:4}:e===fw||e===gw||e===yw||e===bw?{byteLength:8,width:4,height:4}:e===_w||e===xw?{byteLength:16,width:4,height:4}:e===vw||e===Tw?{byteLength:8,width:4,height:4}:e===Sw||e===ww||e===Mw||e===Ew?{byteLength:16,width:4,height:4}:e===Aw||e===Nw?{byteLength:16,width:5,height:4}:e===Cw||e===Rw?{byteLength:16,width:5,height:5}:e===Pw||e===Bw?{byteLength:16,width:6,height:5}:e===Fw||e===Lw?{byteLength:16,width:6,height:6}:e===Dw||e===Ow?{byteLength:16,width:8,height:5}:e===Iw||e===Uw?{byteLength:16,width:8,height:6}:e===kw||e===zw?{byteLength:16,width:8,height:8}:e===Vw||e===Gw?{byteLength:16,width:10,height:5}:e===$w||e===jw?{byteLength:16,width:10,height:6}:e===Ww||e===Hw?{byteLength:16,width:10,height:8}:e===qw||e===Xw?{byteLength:16,width:10,height:10}:e===Yw||e===Kw?{byteLength:16,width:12,height:10}:e===Qw||e===Zw?{byteLength:16,width:12,height:12}:void 0}_convertAddressMode(e){let t=Jw;return e===O?t=eM:e===U&&(t=tM),t}_convertFilterMode(e){let t=sM;return e!==k&&1004!==e&&e!==V||(t=iM),t}_convertMipmapFilterMode(e){return e===V||e===j?sM:iM}_getBytesPerTexel(e){return e===lS||e===hS||e===uS||e===cS?1:e===dS||e===pS||e===mS||e===fS||e===gS||e===yS||e===bS||e===_S||e===xS?2:e===vS||e===TS||e===SS||e===wS||e===MS||e===ES||e===AS||e===NS||e===CS||e===RS||e===PS||e===BS||e===FS||e===LS||e===DS||e===OS||e===IS||e===US||e===JS||e===QS||e===ZS||e===ew?4:e===kS||e===zS||e===VS||e===GS||e===$S||e===jS||e===WS||e===HS?8:e===qS||e===XS||e===YS?16:void 0}_getTypedArrayType(e){return e===uS?Uint8Array:e===cS?Int8Array:e===lS?Uint8Array:e===hS?Int8Array:e===yS?Uint8Array:e===bS?Int8Array:e===fS?Uint8Array:e===gS?Int8Array:e===RS?Uint8Array:e===PS?Int8Array:e===AS||e===NS?Uint8Array:e===CS?Int8Array:e===dS?Uint16Array:e===pS?Int16Array:e===wS?Uint16Array:e===MS?Int16Array:e===GS?Uint16Array:e===$S?Int16Array:e===mS||e===ES||e===jS||e===_S?Uint16Array:e===xS?Int16Array:e===LS?Uint16Array:e===DS?Int16Array:e===WS?Uint16Array:e===HS?Int16Array:e===vS?Uint32Array:e===TS?Int32Array:e===SS?Float32Array:e===kS?Uint32Array:e===zS?Int32Array:e===VS?Float32Array:e===qS?Uint32Array:e===XS?Int32Array:e===YS?Float32Array:e===BS||e===FS?Uint8Array:e===IS||e===OS||e===US?Uint32Array:e===JS?Float32Array:e===QS||e===ZS?Uint32Array:e===ew?Float32Array:void 0}_getDimension(e){let t;return t=e.is3DTexture||e.isData3DTexture?WM:jM,t}}function HE(e,t){const s=e.format,i=e.type,r=e.normalized,n=e.colorSpace,a=Jt.getTransfer(n);let o,l=!1;if(r&&(l=t.features.has(JM.TextureFormatsTier1),!1===l&&Et("WebGPURenderer: Unable to use normalized textures without texture-formats-tier1 feature.")),!0===e.isCompressedTexture||!0===e.isCompressedArrayTexture)switch(s){case fe:case ge:o=a===tt?sw:tw;break;case ye:o=a===tt?rw:iw;break;case be:o=a===tt?aw:nw;break;case qe:o=ow;break;case Xe:o=lw;break;case Ye:o=hw;break;case Ke:o=uw;break;case je:o=a===tt?mw:pw;break;case We:o=dw;break;case He:o=cw;break;case we:case Se:o=a===tt?gw:fw;break;case Me:o=a===tt?xw:_w;break;case Ee:o=vw;break;case Ae:o=Tw;break;case Ne:o=Sw;break;case Ce:o=ww;break;case Re:o=a===tt?Ew:Mw;break;case Pe:o=a===tt?Nw:Aw;break;case Be:o=a===tt?Rw:Cw;break;case Fe:o=a===tt?Bw:Pw;break;case Le:o=a===tt?Lw:Fw;break;case De:o=a===tt?Ow:Dw;break;case Oe:o=a===tt?Uw:Iw;break;case Ie:o=a===tt?zw:kw;break;case Ue:o=a===tt?Gw:Vw;break;case ke:o=a===tt?jw:$w;break;case ze:o=a===tt?Hw:Ww;break;case Ve:o=a===tt?Xw:qw;break;case Ge:o=a===tt?Kw:Yw;break;case $e:o=a===tt?Zw:Qw;break;case ae:o=a===tt?NS:AS;break;default:At("WebGPURenderer: Unsupported texture format.",s)}else switch(s){case ae:switch(i){case H:o=CS;break;case q:o=l?HS:$S;break;case X:o=l?WS:GS;break;case K:o=qS;break;case Y:o=XS;break;case W:o=a===tt?NS:AS;break;case Z:o=jS;break;case Q:o=YS;break;default:At("WebGPURenderer: Unsupported texture type with RGBAFormat.",i)}break;case ne:switch(i){case se:o=OS;break;case ie:o=US;break;default:At("WebGPURenderer: Unsupported texture type with RGBFormat.",i)}break;case he:switch(i){case H:o=hS;break;case q:o=l?xS:pS;break;case X:o=l?_S:dS;break;case K:o=vS;break;case Y:o=TS;break;case W:o=lS;break;case Z:o=mS;break;case Q:o=SS;break;default:At("WebGPURenderer: Unsupported texture type with RedFormat.",i)}break;case ce:switch(i){case H:o=gS;break;case q:o=l?DS:MS;break;case X:o=l?LS:wS;break;case K:o=kS;break;case Y:o=zS;break;case W:o=fS;break;case Z:o=ES;break;case Q:o=VS;break;default:At("WebGPURenderer: Unsupported texture type with RGFormat.",i)}break;case oe:switch(i){case X:o=KS;break;case K:o=QS;break;case Q:o=JS;break;default:At("WebGPURenderer: Unsupported texture type with DepthFormat.",i)}break;case le:switch(i){case te:o=ZS;break;case Q:t&&!1===t.features.has(JM.Depth32FloatStencil8)&&At('WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.'),o=ew;break;default:At("WebGPURenderer: Unsupported texture type with DepthStencilFormat.",i)}break;case ue:switch(i){case Y:o=TS;break;case K:o=vS;break;default:At("WebGPURenderer: Unsupported texture type with RedIntegerFormat.",i)}break;case de:switch(i){case Y:o=zS;break;case K:o=kS;break;default:At("WebGPURenderer: Unsupported texture type with RGIntegerFormat.",i)}break;case me:switch(i){case Y:o=XS;break;case K:o=qS;break;default:At("WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.",i)}break;default:At("WebGPURenderer: Unsupported texture format.",s)}return o}const qE=/^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,XE=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,YE={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",sampler_comparison:"samplerComparison",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 KE extends nv{constructor(e){const{type:t,inputs:s,name:i,inputsCode:r,blockCode:n,outputType:a}=(e=>{const t=(e=e.replace(/^(?:\s*\/\/[^\r\n]*|\s*\/\*[\s\S]*?\*\/|\s*)+/,"")).match(qE);if(null!==t&&4===t.length){const s=t[2],i=[];let r=null;for(;null!==(r=XE.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=YE[r]),n.push(new Wx(r,t))}const a=e.substring(t[0].length),o=t[3]||"void",l=void 0!==t[1]?t[1]:"";return{type:YE[o]||o,inputs:n,name:l,inputsCode:s,blockCode:a,outputType:o}}throw new Error("THREE.WGSLNodeFunction: Function is not a WGSL code.")})(e);super(t,s,i),this.inputsCode=r,this.blockCode=n,this.outputType=a}getCode(e=this.name){const t="void"!==this.outputType?"-> "+this.outputType:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class QE extends rv{parseFunction(e){return new KE(e)}}const ZE={[ta]:"read",[sa]:"write",[ia]:"read_write"},JE={[O]:"repeat",[I]:"clamp",[U]:"mirror"},eA={vertex:$T.VERTEX,fragment:$T.FRAGMENT,compute:$T.COMPUTE},tA={instance:!0,swizzleAssign:!1,storageBuffer:!0},sA={"^^":"tsl_xor"},iA={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>"},rA={},nA={tsl_xor:new c_("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new c_("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new c_("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new c_("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new c_("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new c_("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new c_("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new c_("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 c_("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 c_("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new c_("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 c_("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),inverse_mat2:new c_("\nfn tsl_inverse_mat2( m : mat2x2<f32> ) -> mat2x2<f32> {\n\n\tlet det = m[ 0 ][ 0 ] * m[ 1 ][ 1 ] - m[ 0 ][ 1 ] * m[ 1 ][ 0 ];\n\n\treturn mat2x2<f32>(\n\t\tm[ 1 ][ 1 ], - m[ 0 ][ 1 ],\n\t\t- m[ 1 ][ 0 ], m[ 0 ][ 0 ]\n\t) * ( 1.0 / det );\n\n}\n"),inverse_mat3:new c_("\nfn tsl_inverse_mat3( m : mat3x3<f32> ) -> mat3x3<f32> {\n\n\tlet a00 = m[ 0 ][ 0 ]; let a01 = m[ 0 ][ 1 ]; let a02 = m[ 0 ][ 2 ];\n\tlet a10 = m[ 1 ][ 0 ]; let a11 = m[ 1 ][ 1 ]; let a12 = m[ 1 ][ 2 ];\n\tlet a20 = m[ 2 ][ 0 ]; let a21 = m[ 2 ][ 1 ]; let a22 = m[ 2 ][ 2 ];\n\n\tlet b01 = a22 * a11 - a12 * a21;\n\tlet b11 = - a22 * a10 + a12 * a20;\n\tlet b21 = a21 * a10 - a11 * a20;\n\n\tlet det = a00 * b01 + a01 * b11 + a02 * b21;\n\n\treturn mat3x3<f32>(\n\t\tb01, ( - a22 * a01 + a02 * a21 ), ( a12 * a01 - a02 * a11 ),\n\t\tb11, ( a22 * a00 - a02 * a20 ), ( - a12 * a00 + a02 * a10 ),\n\t\tb21, ( - a21 * a00 + a01 * a20 ), ( a11 * a00 - a01 * a10 )\n\t) * ( 1.0 / det );\n\n}\n"),inverse_mat4:new c_("\nfn tsl_inverse_mat4( m : mat4x4<f32> ) -> mat4x4<f32> {\n\n\tlet a00 = m[ 0 ][ 0 ]; let a01 = m[ 0 ][ 1 ]; let a02 = m[ 0 ][ 2 ]; let a03 = m[ 0 ][ 3 ];\n\tlet a10 = m[ 1 ][ 0 ]; let a11 = m[ 1 ][ 1 ]; let a12 = m[ 1 ][ 2 ]; let a13 = m[ 1 ][ 3 ];\n\tlet a20 = m[ 2 ][ 0 ]; let a21 = m[ 2 ][ 1 ]; let a22 = m[ 2 ][ 2 ]; let a23 = m[ 2 ][ 3 ];\n\tlet a30 = m[ 3 ][ 0 ]; let a31 = m[ 3 ][ 1 ]; let a32 = m[ 3 ][ 2 ]; let a33 = m[ 3 ][ 3 ];\n\n\tlet b00 = a00 * a11 - a01 * a10;\n\tlet b01 = a00 * a12 - a02 * a10;\n\tlet b02 = a00 * a13 - a03 * a10;\n\tlet b03 = a01 * a12 - a02 * a11;\n\tlet b04 = a01 * a13 - a03 * a11;\n\tlet b05 = a02 * a13 - a03 * a12;\n\tlet b06 = a20 * a31 - a21 * a30;\n\tlet b07 = a20 * a32 - a22 * a30;\n\tlet b08 = a20 * a33 - a23 * a30;\n\tlet b09 = a21 * a32 - a22 * a31;\n\tlet b10 = a21 * a33 - a23 * a31;\n\tlet b11 = a22 * a33 - a23 * a32;\n\n\tlet det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n\treturn mat4x4<f32>(\n\t\ta11 * b11 - a12 * b10 + a13 * b09,\n\t\ta02 * b10 - a01 * b11 - a03 * b09,\n\t\ta31 * b05 - a32 * b04 + a33 * b03,\n\t\ta22 * b04 - a21 * b05 - a23 * b03,\n\t\ta12 * b08 - a10 * b11 - a13 * b07,\n\t\ta00 * b11 - a02 * b08 + a03 * b07,\n\t\ta32 * b02 - a30 * b05 - a33 * b01,\n\t\ta20 * b05 - a22 * b02 + a23 * b01,\n\t\ta10 * b10 - a11 * b08 + a13 * b06,\n\t\ta01 * b08 - a00 * b10 - a03 * b06,\n\t\ta30 * b04 - a31 * b02 + a33 * b00,\n\t\ta21 * b02 - a20 * b04 - a23 * b00,\n\t\ta11 * b07 - a10 * b09 - a12 * b06,\n\t\ta00 * b09 - a01 * b07 + a02 * b06,\n\t\ta31 * b01 - a30 * b03 - a32 * b00,\n\t\ta20 * b03 - a21 * b01 + a22 * b00\n\t) * ( 1.0 / det );\n\n}\n"),biquadraticTexture:new c_("\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"),biquadraticTextureArray:new c_("\nfn tsl_biquadraticTexture_array( map : texture_2d_array<f32>, coord : vec2f, iRes : vec2u, layer : u32, 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, layer, level );\n\tlet rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, layer, level );\n\tlet rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, layer, level );\n\tlet rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, layer, level );\n\n\treturn mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );\n\n}\n")},aA={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",inverse_mat2:"tsl_inverse_mat2",inverse_mat3:"tsl_inverse_mat3",inverse_mat4:"tsl_inverse_mat4",inversesqrt:"inverseSqrt",faceforward:"faceForward",bitcast:"bitcast<f32>",floatpack_snorm_2x16:"pack2x16snorm",floatpack_unorm_2x16:"pack2x16unorm",floatpack_float16_2x16:"pack2x16float",floatpack_snorm_4x8:"pack4x8snorm",floatpack_unorm_4x8:"pack4x8unorm",floatunpack_snorm_2x16:"unpack2x16snorm",floatunpack_unorm_2x16:"unpack2x16unorm",floatunpack_float16_2x16:"unpack2x16float",floatunpack_snorm_4x8:"unpack4x8snorm",floatunpack_unorm_4x8:"unpack4x8unorm"},oA=new Set(["alias","break","case","const","const_assert","continue","continuing","default","diagnostic","discard","else","enable","false","fn","for","if","let","loop","override","requires","return","struct","switch","true","var","while","NULL","Self","abstract","active","alignas","alignof","as","asm","asm_fragment","async","attribute","auto","await","become","binding_array","cast","catch","class","co_await","co_return","co_yield","coherent","column_major","common","compile","compile_fragment","concept","const_cast","consteval","constexpr","constinit","crate","debugger","decltype","delete","demote","demote_to_helper","do","dynamic_cast","enum","explicit","export","extends","extern","external","fallthrough","filter","final","finally","friend","from","fxgroup","get","goto","groupshared","highp","impl","implements","import","inline","instanceof","interface","layout","lowp","macro","macro_rules","match","mediump","meta","mod","module","move","mut","mutable","namespace","new","nil","noexcept","noinline","nointerpolation","non_coherent","noncoherent","noperspective","null","nullptr","of","operator","package","packoffset","partition","pass","patch","pixelfragment","precise","precision","premerge","priv","protected","pub","public","readonly","ref","regardless","register","reinterpret_cast","require","resource","restrict","self","set","shared","sizeof","smooth","snorm","static","static_assert","static_cast","std","subroutine","super","target","template","this","thread_local","throw","trait","try","type","typedef","typeid","typename","typeof","union","unless","unorm","unsafe","unsized","use","using","varying","virtual","volatile","wgsl","where","with","writeonly","yield","main"]);let lA="";!0!==("undefined"!=typeof navigator&&/Firefox|Deno/g.test(navigator.userAgent))&&(lA+="diagnostic( off, derivative_uniformity );\n");class hA extends $x{constructor(e,t){super(e,t,new QE),this.uniformGroups={},this.uniformGroupsBindings={},this.builtins={},this.directives={},this.scopedArrays=new Map,this.allowEarlyReturns=!0,this.allowGlobalVariables=!0}_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)?r?n?`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${r}, ${i}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${r}, ${i} )`:n?`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,s,n,i,r):this.generateTextureLod(e,t,s,r,n,i)}generateWrapFunction(e){const t=`tsl_coord_${JE[e.wrapS]}S_${JE[e.wrapT]}T_${e.is3DTexture||e.isData3DTexture?"3d":"2d"}`;let s=rA[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 a=(e,t)=>{e===O?(i.push(nA.repeatWrapping_float),n+=`\t\ttsl_repeatWrapping_float( coord.${t} )`):e===I?(i.push(nA.clampWrapping_float),n+=`\t\ttsl_clampWrapping_float( coord.${t} )`):e===U?(i.push(nA.mirrorWrapping_float),n+=`\t\ttsl_mirrorWrapping_float( coord.${t} )`):(n+=`\t\tcoord.${t}`,Et(`WebGPURenderer: Unsupported texture wrap type "${e}" for vertex shader.`))};a(e.wrapS,"x"),n+=",\n",a(e.wrapT,"y"),(e.is3DTexture||e.isData3DTexture)&&(n+=",\n",a(e.wrapR,"z")),n+="\n\t);\n\n}\n",rA[t]=s=new c_(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.cache);void 0===i.dimensionsSnippet&&(i.dimensionsSnippet={});let r=i.dimensionsSnippet[s];if(void 0===i.dimensionsSnippet[s]){let n,a;const{primarySamples:o}=this.renderer.backend.utils.getTextureSampleData(e),l=o>1;a=e.is3DTexture||e.isData3DTexture?"vec3<u32>":"vec2<u32>",n=l||e.isStorageTexture?t:`${t}${s?`, u32( ${s} )`:""}`,r=new lu(new Gu(`textureDimensions( ${n} )`,a)),i.dimensionsSnippet[s]=r,(e.isArrayTexture||e.isDataArrayTexture||e.is3DTexture||e.isData3DTexture)&&(i.arrayLayerCount=new lu(new Gu(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(i.cubeFaceCount=new lu(new Gu("6u","u32")))}return r.build(this)}generateTextureSize(e,t,s){const{primarySamples:i}=this.renderer.backend.utils.getTextureSampleData(e);return`textureDimensions( ${i>1||e.isStorageTexture?t:`${t}, ${s}`} )`}generateFilteredTexture(e,t,s,i,r="0u",n){const a=this.generateWrapFunction(e),o=this.generateTextureDimension(e,t,r);return i&&(s=`${s} + vec2<f32>(${i}) / ${o}`),n?(this._include("biquadraticTextureArray"),`tsl_biquadraticTexture_array( ${t}, ${a}( ${s} ), ${o}, u32( ${n} ), u32( ${r} ) )`):(this._include("biquadraticTexture"),`tsl_biquadraticTexture( ${t}, ${a}( ${s} ), ${o}, u32( ${r} ) )`)}generateTextureLod(e,t,s,i,r,n="0u"){if(!0===e.isCubeTexture){r&&(s=`${s} + vec3<f32>(${r})`);return`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${e.isDepthTexture?"u32":"f32"}( ${n} ) )`}const a=this.generateWrapFunction(e),o=this.generateTextureDimension(e,t,n),l=e.is3DTexture||e.isData3DTexture?"vec3":"vec2";r&&(s=`${s} + ${l}<f32>(${r}) / ${l}<f32>( ${o} )`);return s=`${l}<u32>( clamp( floor( ${a}( ${s} ) * ${l}<f32>( ${o} ) ), ${`${l}<f32>( 0 )`}, ${`${l}<f32>( ${o} - ${"vec3"===l?"vec3<u32>( 1, 1, 1 )":"vec2<u32>( 1, 1 )"} )`} ) )`,this.generateTextureLoad(e,t,s,n,i,null)}generateStorageTextureLoad(e,t,s,i,r,n){let a;return n&&(s=`${s} + ${n}`),a=r?`textureLoad( ${t}, ${s}, ${r} )`:`textureLoad( ${t}, ${s} )`,a}generateTextureLoad(e,t,s,i,r,n){let a;return null===i&&(i="0u"),n&&(s=`${s} + ${n}`),r?a=`textureLoad( ${t}, ${s}, ${r}, u32( ${i} ) )`:(a=`textureLoad( ${t}, ${s}, u32( ${i} ) )`,this.renderer.backend.compatibilityMode&&e.isDepthTexture&&(a+=".x")),a}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&&this.renderer.hasCompatibility(yt)}isUnfilterable(e){return"float"!==this.getComponentTypeFromTexture(e)||!this.isAvailable("float32Filterable")&&e.type===Q||!1===this.isSampleCompare(e)&&e.minFilter===k&&e.magFilter===k||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1||!0===e.normalized&&(e.type===q||e.type===X)}generateTexture(e,t,s,i,r,n=this.shaderStage){let a=null;return a=this.isUnfilterable(e)?this.generateTextureLod(e,t,s,i,r,"0",n):this._generateTextureSample(e,t,s,i,r,n),a}generateTextureGrad(e,t,s,i,r,n,a=this.shaderStage){if("fragment"===a)return r?n?`textureSampleGrad( ${t}, ${t}_sampler, ${s}, ${r}, ${i[0]}, ${i[1]}, ${n} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${s}, ${r}, ${i[0]}, ${i[1]} )`:n?`textureSampleGrad( ${t}, ${t}_sampler, ${s}, ${i[0]}, ${i[1]}, ${n} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${s}, ${i[0]}, ${i[1]} )`;At(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${a} shader.`)}generateTextureCompare(e,t,s,i,r,n,a=this.shaderStage){if("fragment"===a)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} )`;At(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${a} shader.`)}generateTextureGather(e,t,s,i,r,n){const a=!0===e.isDepthTexture?"":`${i}, `;return r?n?`textureGather( ${a}${t}, ${t}_sampler, ${s}, ${r}, ${n} )`:`textureGather( ${a}${t}, ${t}_sampler, ${s}, ${r} )`:n?`textureGather( ${a}${t}, ${t}_sampler, ${s}, ${n} )`:`textureGather( ${a}${t}, ${t}_sampler, ${s})`}generateTextureGatherCompare(e,t,s,i,r,n){return r?n?`textureGatherCompare( ${t}, ${t}_sampler, ${s}, ${r}, ${i}, ${n} )`:`textureGatherCompare( ${t}, ${t}_sampler, ${s}, ${r}, ${i})`:n?`textureGatherCompare( ${t}, ${t}_sampler, ${s}, ${i}, ${n} )`:`textureGatherCompare( ${t}, ${t}_sampler, ${s}, ${i})`}generateTextureLevel(e,t,s,i,r,n){return!1===this.isUnfilterable(e)?r?n?`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${r}, ${i}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${r}, ${i} )`:n?`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,s,n,i,r):this.generateTextureLod(e,t,s,r,n,i)}generateTextureBias(e,t,s,i,r,n,a=this.shaderStage){if("fragment"===a)return r?n?`textureSampleBias( ${t}, ${t}_sampler, ${s}, ${r}, ${i}, ${n} )`:`textureSampleBias( ${t}, ${t}_sampler, ${s}, ${r}, ${i} )`:n?`textureSampleBias( ${t}, ${t}_sampler, ${s}, ${i}, ${n} )`:`textureSampleBias( ${t}, ${t}_sampler, ${s}, ${i} )`;At(`WebGPURenderer: THREE.TextureNode.biasNode does not support ${a} 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)}isReservedKeyword(e){return oA.has(e)}getOutputStructName(){return"output"}getFunctionOperator(e){const t=sA[e];return void 0!==t?(this._include(t),t):null}getNodeAccess(e,t){return"compute"!==t?!0===e.isAtomic?"vertex"===t?(Et("WebGPURenderer: Atomic operations are not supported in the vertex stage. They are only available in the fragment and compute stages."),ta):ia:ta:e.access}getStorageAccess(e,t){return ZE[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 a;const o=e.groupNode,l=o.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);"texture"===t||"storageTexture"===t?i=!0===e.value.is3DTexture?new nT(r.name,r.node,o,n):new iT(r.name,r.node,o,n):"cubeTexture"===t||"cubeDepthTexture"===t?i=new rT(r.name,r.node,o,n):"texture3D"===t&&(i=new nT(r.name,r.node,o,n)),i.store=!0===e.isStorageTextureNode,i.mipLevel=i.store?e.mipLevel:0,i.setVisibility(eA[s]);if(!0===e.value.isCubeTexture||!1===this.isUnfilterable(e.value)&&!1===i.store||null!==e.gatherNode){const e=new tE(`${r.name}_sampler`,r.node,o);e.setVisibility(eA[s]),h.push(e,i),a=[e,i]}else h.push(i),a=[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?Kv:rE)(e,o),n.buffer=l}l.setVisibility(l.getVisibility()|eA[s]),h.push(l),a=l,r.name=i||"NodeBuffer_"+r.id}else{let e=this.uniformGroups[l];void 0===e&&(e=new Jv(l,o),e.setVisibility($T.VERTEX|$T.FRAGMENT|$T.COMPUTE),this.uniformGroups[l]=e),-1===h.indexOf(e)&&h.push(e),a=this.getNodeUniform(r,t);const s=a.name,i=e.uniforms.some(e=>e.name===s);i||e.addUniform(a)}n.uniformGPU=a}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,r){return!1===this.scopedArrays.has(e)&&this.scopedArrays.set(e,{name:e,scope:t,bufferType:s,bufferCount:i,isAtomic:r}),e}getScopedArrays(e){if("compute"!==e)return;const t=[];for(const{name:e,scope:s,bufferType:i,bufferCount:r,isAtomic:n}of this.scopedArrays.values()){let a=this.getType(i);!0===n&&(a=`atomic<${a}>`),t.push(`var<${s}> ${e}: array< ${a}, ${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,i=""){let r=`var${i} ${t} : `;return r+=null!==s?this.generateArrayDeclaration(e,s):this.getType(e),r}getVars(e,t=!1){let s="";t&&(s="<private>");const i=[],r=this.vars[e];if(void 0!==r)for(const e of r)i.push(`${this.getVar(e.type,e.name,e.count,s)};`);return t?i.join("\n"):`\n\t${i.join("\n\t")}\n`}getVaryings(e){const t=[];if("vertex"===e&&this.getBuiltin("position","builtinClipSpace","vec4<f32>","vertex"),"vertex"===e||"fragment"===e){const s=this.varyings,i=this.vars[e];let r=0;for(let n=0;n<s.length;n++){const a=s[n];if(a.needsInterpolation){let e=`@location( ${r++} )`;if(a.interpolationType){const t=null!==a.interpolationSampling?`, ${a.interpolationSampling} )`:" )";e+=` @interpolate( ${a.interpolationType}${t}`}else/^(int|uint|ivec|uvec)/.test(a.type)&&(e+=" @interpolate(flat, either)");t.push(`${e} ${a.name} : ${this.getType(a.type)}`)}else"vertex"===e&&!1===i.includes(a)&&i.push(a)}}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.renderer.backend,s=this.uniforms[e],i=[],r=[],n=[],a={};for(const n of s){const s=n.groupNode.name,o=this.bindingsIndexes[s];if("texture"===n.type||"cubeTexture"===n.type||"cubeDepthTexture"===n.type||"storageTexture"===n.type||"texture3D"===n.type){const s=n.node,r=s.value;let a;(!0===r.isCubeTexture||!1===this.isUnfilterable(r)&&!0!==s.isStorageTextureNode||null!==s.gatherNode)&&(this.isSampleCompare(r)&&s.isSampleCompare()?i.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${n.name}_sampler : sampler_comparison;`):i.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${n.name}_sampler : sampler;`));let l="";const{primarySamples:h}=t.utils.getTextureSampleData(r);if(h>1&&(l="_multisampled"),!0===r.isCubeTexture&&!0===r.isDepthTexture)a="texture_depth_cube";else if(!0===r.isCubeTexture)a="texture_cube<f32>";else if(!0===r.isDepthTexture)a=t.compatibilityMode&&null===r.compareFunction?`texture${l}_2d<f32>`:`texture_depth${l}_2d${!0===r.isArrayTexture?"_array":""}`;else if(!0===n.node.isStorageTextureNode){const s=HE(r,t.device),i=this.getStorageAccess(n.node,e),o=n.node.value.is3DTexture,l=n.node.value.isArrayTexture;a=`texture_storage_${o?"3d":"2d"+(l?"_array":"")}<${s}, ${i}>`}else if(!0===r.isArrayTexture||!0===r.isDataArrayTexture||!0===r.isCompressedArrayTexture){a=`texture_2d_array<${this.getComponentTypeFromTexture(r).charAt(0)}32>`}else if(!0===r.is3DTexture||!0===r.isData3DTexture){a=`texture_3d<${this.getComponentTypeFromTexture(r).charAt(0)}32>`}else{a=`texture${l}_2d<${this.getComponentTypeFromTexture(r).charAt(0)}32>`}i.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${n.name} : ${a};`)}else if("buffer"===n.type||"storageBuffer"===n.type||"indirectStorageBuffer"===n.type){const t=n.node,s=this.getType(t.getNodeType(this)),i=t.bufferCount,a=i>0&&"buffer"===n.type?", "+i:"",l=t.isStorageBufferNode?`storage, ${this.getStorageAccess(t,e)}`:"uniform";if(this.isCustomStruct(n))r.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var<${l}> ${n.name} : ${s};`);else{const e=`\tvalue : array< ${t.isAtomic?`atomic<${s}>`:`${s}`}${a} >`;r.push(this._getWGSLStructBinding(n.name,e,l,o.binding++,o.group))}}else{const e=n.groupNode.name;if(void 0===a[e]){const t=this.uniformGroups[e];if(void 0!==t){const s=[];for(const e of t.uniforms){const t=e.getType(),i=this.getType(this.getVectorType(t));s.push(`\t${e.name} : ${i}`)}let i=this.uniformGroupsBindings[e];void 0===i&&(i={index:o.binding++,id:o.group},this.uniformGroupsBindings[e]=i),a[e]={index:i.index,id:i.id,snippets:s}}}}}for(const e in a){const t=a[e];n.push(this._getWGSLStructBinding(e,t.snippets.join(",\n"),"uniform",t.index,t.id))}return[...i,...r,...n].join("\n")}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){this.shaderStage=t;const s=this.allowGlobalVariables,i=e[t];i.uniforms=this.getUniforms(t),i.attributes=this.getAttributes(t),i.varyings=this.getVaryings(t),i.structs=this.getStructs(t),i.vars=this.getVars(t,s),i.codes=this.getCodes(t),i.directives=this.getDirectives(t),i.scopedArrays=this.getScopedArrays(t);let r="// code\n\n";r+=this.flowCode[t];const n=this.flowNodes[t],a=n[n.length-1],o=a.outputNode,l=void 0!==o&&!0===o.isOutputStructNode;for(const e of n){const s=this.getFlowData(e),n=e.name;if(n&&(r.length>0&&(r+="\n"),r+=`\t// flow -> ${n}\n`),r+=`${s.code}\n\t`,e===a&&"compute"!==t)if(r+="// result\n\n\t","vertex"===t)r+=`varyings.builtinClipSpace = ${s.result};`;else if("fragment"===t)if(l)i.returnType=o.getNodeType(this),i.structs+="var<private> output : "+i.returnType+";",r+=`return ${s.result};`;else{let e=`\t@location( 0 ) color: ${this.getType(this.getOutputType())}`;const t=this.getBuiltins("output");t&&(e+=",\n\t"+t),i.returnType="OutputStruct",i.structs+=this._getWGSLStruct("OutputStruct",e),i.structs+="\nvar<private> output : OutputStruct;",r+=`output.color = ${this.format(s.result,a.getNodeType(this),this.getOutputType())};\n\n\treturn output;`}}i.flow=r}if(this.shaderStage=null,null!==this.material)this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment);else{const t=this.compute.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,t="2x16"){return this.getMethod(`floatpack_${e}_${t}`)}getFloatUnpackingMethod(e,t="2x16"){return this.getMethod(`floatunpack_${e}_${t}`)}getTernary(e,t,s){return`select( ${s}, ${t}, ${e} )`}getType(e){return iA[e]||e}isAvailable(e){let t=tA[e];return void 0===t&&("float32Filterable"===e?t=this.renderer.hasFeature("float32-filterable"):"clipDistance"===e&&(t=this.renderer.hasFeature("clip-distances")),tA[e]=t),t}_getWGSLMethod(e){return void 0!==nA[e]&&this._include(e),aA[e]}_include(e){const t=nA[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// vars\n${e.vars}\n\n// codes\n${e.codes}\n\n@vertex\nfn main( ${e.attributes} ) -> VaryingsStruct {\n\n\t// flow\n\t${e.flow}\n\n\treturn varyings;\n\n}\n`}_getWGSLFragmentCode(e){return`${this.getSignature()}\n// global\n${lA}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// vars\n${e.vars}\n\n// codes\n${e.codes}\n\n@fragment\nfn main( ${e.varyings} ) -> ${e.returnType} {\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// vars\n${this.allowGlobalVariables?e.vars:""}\n\n// codes\n${e.codes}\n\n@compute @workgroup_size( ${s}, ${i}, ${r} )\nfn main( ${e.attributes} ) {\n\n\t// local vars\n\t${this.allowGlobalVariables?"":e.vars}\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// 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};`}}const uA=new hE,cA=new uE,dA=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32"]],[Uint32Array,["uint32"]],[Float32Array,["float32"]]]);"undefined"!=typeof Float16Array&&dA.set(Float16Array,["float16"]);const pA=new Map([[Oi,["float16"]]]),mA=new Map([[Int32Array,"sint32"],[Uint32Array,"uint32"],[Float32Array,"float32"]]);class fA{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 a=i.device;let o,l=s.array;if(!1===e.normalized&&!0!==e.isInterleavedBufferAttribute)if(l.constructor===Int16Array||l.constructor===Int8Array)l=new Int32Array(l);else if((l.constructor===Uint16Array||l.constructor===Uint8Array)&&(l=new Uint32Array(l),t&GPUBufferUsage.INDEX))for(let e=0;e<l.length;e++)65535===l[e]&&(l[e]=4294967295);if(s.array=l,(s.isStorageBufferAttribute||s.isStorageInstancedBufferAttribute)&&3===s.itemSize)o=4;else if(s.itemSize>1&&s.itemSize*l.BYTES_PER_ELEMENT%4!=0){const e=s.itemSize*l.BYTES_PER_ELEMENT;o=4*Math.floor((e+3)/4)/l.BYTES_PER_ELEMENT}if(void 0!==o){const e=s.itemSize,t=new l.constructor(s.count*o);for(let i=0;i<s.count;i++)t.set(l.subarray(i*e,i*e+e),i*o);(s.isStorageBufferAttribute||s.isStorageInstancedBufferAttribute)&&(s.itemSize=o,s.array=t),l=t,r._itemSize=e,r._paddedItemSize=o}const h=l.byteLength,u=h+(4-h%4)%4;uA.label=s.name,uA.size=u,uA.usage=t,uA.mappedAtCreation=!0,n=a.createBuffer(uA),uA.reset(),new l.constructor(n.getMappedRange()).set(l),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 a=t.array;const o=r._itemSize,l=r._paddedItemSize;if(void 0!==l){a=new a.constructor(t.count*l);for(let e=0;e<t.count;e++)a.set(t.array.subarray(e*o,e*o+o),e*l);(t.isStorageBufferAttribute||t.isStorageInstancedBufferAttribute)&&(t.array=a)}const h=t.updateRanges;if(0===h.length)i.queue.writeBuffer(n,0,a,0);else{const e=vt(a),s=e?1:a.BYTES_PER_ELEMENT;for(let t=0,r=h.length;t<r;t++){const r=h[t];let u,c;if(void 0!==l){const e=Math.floor(r.start/o);u=e*l*s,c=(Math.ceil((r.start+r.count)/o)-e)*l*s}else u=r.start*s,c=r.count*s;const d=u*(e?a.BYTES_PER_ELEMENT:1);i.queue.writeBuffer(n,d,a,u,c)}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 a=s.get(n);if(void 0===a){let e,t;!0===i.isInterleavedBufferAttribute?(e=i.data.stride*r,t=i.data.isInstancedInterleavedBuffer?ZM:QM):(e=i.itemSize*r,t=i.isInstancedBufferAttribute?ZM:QM,i.itemSize>1&&e%4!=0&&(e=4*Math.floor((e+3)/4))),a={arrayStride:e,attributes:[],stepMode:t},s.set(n,a)}const o=this._getVertexFormat(i),l=!0===i.isInterleavedBufferAttribute?i.offset*r:0;a.attributes.push({shaderLocation:e,offset:l,format:o})}return Array.from(s.values())}destroyAttribute(e){const t=this.backend;t.get(this._getBufferAttribute(e)).buffer.destroy(),t.delete(e)}async getArrayBufferAsync(e,t=null,s=0,i=-1){const r=this.backend,n=r.device,a=r.get(this._getBufferAttribute(e)).buffer,o=-1===i?a.size-s:i;let l;if(null!==t&&t.isReadbackBuffer){const e=r.get(t);if(!0===t._mapped)throw new Error("THREE.WebGPUAttributeUtils: ReadbackBuffer must be released before being used again.");if(t._mapped=!0,void 0===e.readBufferGPU){uA.label=`${t.name}_readback`,uA.size=t.maxByteLength,uA.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,l=n.createBuffer(uA),uA.reset();const s=()=>{t.buffer=null,t._mapped=!1,l.unmap()},i=()=>{t.buffer=null,t._mapped=!1,l.destroy(),r.delete(t),t.removeEventListener("release",s),t.removeEventListener("dispose",i)};t.addEventListener("release",s),t.addEventListener("dispose",i),e.readBufferGPU=l}else l=e.readBufferGPU}else uA.label=`${e.name}_readback`,uA.size=o,uA.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,l=n.createBuffer(uA),uA.reset();cA.label=`readback_encoder_${e.name}`;const h=n.createCommandEncoder(cA);cA.reset(),h.copyBufferToBuffer(a,s,l,0,o);if(oE(n,h.finish()),await l.mapAsync(GPUMapMode.READ,0,o),null===t){const e=l.getMappedRange(0,o).slice();return l.destroy(),e}if(t.isReadbackBuffer)return t.buffer=l.getMappedRange(0,o),t;{const e=l.getMappedRange(0,o);return new Uint8Array(t).set(new Uint8Array(e)),l.destroy(),t}}_getVertexFormat(e){const{itemSize:t,normalized:s}=e,i=e.array.constructor,r=e.constructor;let n;if(1===t)n=mA.get(i);else{const e=(pA.get(r)||dA.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||At("WebGPUAttributeUtils: Vertex format not supported yet."),n}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}const gA=new lE,yA=new hE,bA=new bE;class _A{constructor(e){this.layoutGPU=e,this.usedTimes=0}}class xA{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=kn(JSON.stringify(r));let a=this._bindGroupLayoutCache.get(n);return void 0===a&&(a=new _A(s.createBindGroupLayout({entries:r})),this._bindGroupLayoutCache.set(n,a)),a.usedTimes++,i.layout=a,i.layoutKey=n,a.layoutGPU}createBindings(e,t,s,i=0){const{backend:r}=this,n=r.get(e),a=this.createBindingsLayout(e);let o;""!==s&&(void 0===n.groups&&(n.groups={},n.versions={}),n.versions[s]===i&&(o=n.groups[s])),void 0===o&&(o=this.createBindGroup(e,a),""!==s&&(n.groups[s]=o,n.versions[s]=i)),n.group=o}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 e=vt(i),t=e?1:i.BYTES_PER_ELEMENT;let a=n[0].start;for(let o=0,l=n.length;o<l;o++){const l=n[o],h=n[o+1],u=l.start+l.count;if(void 0!==h&&h.start===u)continue;const c=a*t,d=(u-a)*t,p=c*(e?i.BYTES_PER_ELEMENT:1);s.queue.writeBuffer(r,p,i,c,d),void 0!==h&&(a=h.start)}}}createBindGroupIndex(e,t){const s=this.backend.device,i=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,r=e[0];yA.label="bindingCameraIndex_"+r,yA.size=16,yA.usage=i;const n=s.createBuffer(yA);yA.reset(),s.queue.writeBuffer(n,0,e,0),gA.label="bindGroupCameraIndex_"+r,gA.layout=t,gA.entries.push({binding:0,resource:{buffer:n}});const a=s.createBindGroup(gA);return gA.reset(),a}createBindGroup(e,t){const s=this.backend,i=s.device;let r=0;gA.label="bindGroup_"+e.name,gA.layout=t;for(const t of e.bindings){if(t.isUniformBuffer){const e=s.get(t);gA.entries.push({binding:r,resource:{buffer:e.buffer}})}else if(t.isStorageBuffer){const e=s.get(t.attribute).buffer;gA.entries.push({binding:r,resource:{buffer:e}})}else if(t.isSampledTexture){const e=s.get(t.texture);let n;if(void 0!==e.externalTexture)n=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}`,n=e[r],void 0===n){const a=KM;let o;o=t.isSampledCubeTexture?XM:t.texture.isArrayTexture||t.texture.isDataArrayTexture||t.texture.isCompressedArrayTexture?qM:t.isSampledTexture3D?YM:HM,bA.aspect=a,bA.dimension=o,bA.mipLevelCount=s,bA.baseMipLevel=i,n=e[r]=e.texture.createView(bA),bA.reset()}}gA.entries.push({binding:r,resource:n})}else if(t.isSampler){const e=s.get(t);gA.entries.push({binding:r,resource:e.sampler})}r++}const n=i.createBindGroup(gA);return gA.reset(),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&$T.COMPUTE?i.access===ia||i.access===sa?e.type=BM:e.type=FM:i.nodeUniform&&i.nodeUniform.isAtomic&&i.visibility&$T.FRAGMENT?e.type=BM:e.type=FM),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===ia?OM:t===sa?LM:DM,i.texture.isArrayTexture?e.viewDimension=qM:i.texture.is3DTexture&&(e.viewDimension=YM),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=zM)),i.texture.isDepthTexture)e.compatibilityMode&&null===i.texture.compareFunction?t.sampleType=zM:t.sampleType=VM;else{const e=i.texture.type;e===Y?t.sampleType=GM:e===K?t.sampleType=$M:!0!==i.texture.normalized||e!==q&&e!==X?e===Q&&(this.backend.hasFeature("float32-filterable")?t.sampleType=kM:t.sampleType=zM):t.sampleType=zM}i.isSampledCubeTexture?t.viewDimension=XM:i.texture.isArrayTexture||i.texture.isDataArrayTexture||i.texture.isCompressedArrayTexture?t.viewDimension=qM:i.isSampledTexture3D&&(t.viewDimension=YM),r.texture=t}else if(i.isSampler){const t={};i.texture.isDepthTexture&&(null!==i.texture.compareFunction&&i.textureNode.isSampleCompare()&&e.hasCompatibility(yt)?t.type=UM:t.type=IM),r.sampler=t}else At(`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 vA{constructor(e){this.backend=e}getMaxAnisotropy(){return 16}getUniformBufferLimit(){return this.backend.device.limits.maxUniformBufferBindingSize}}const TA=new class{constructor(){this.label="",this.layout=null,this.compute=null}reset(){this.label="",this.layout=null,this.compute=null}},SA=new class{constructor(){this.label="",this.bindGroupLayouts=null}reset(){this.label="",this.bindGroupLayouts=null}},wA=new cE,MA=new mE;class EA{constructor(e){this.backend=e}_getSampleCount(e){return this.backend.utils.getSampleCountRenderContext(e)}createRenderPipeline(e,t){const{object:s,material:i,geometry:r,pipeline:n}=e,{vertexProgram:a,fragmentProgram:o}=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,s=e.context.mrt;for(let e=0;e<t.length;e++){const i=t[e],r=u.getTextureFormatGPU(i);let n;if(null!==s)if(!0!==this.backend.compatibilityMode){const e=s.getBlendMode(i.name);6===e.blending?n=m:0!==e.blending&&(n=this._getBlending(e))}else Nt("WebGPURenderer: Multiple Render Targets (MRT) blending configuration is not fully supported in compatibility mode. The material blending will be used for all render targets."),n=m;else n=m;y.push({format:r,blend:n,writeMask:g})}}else{const t=u.getCurrentColorFormat(e.context);y.push({format:t,blend:m,writeMask:g})}const b=l.get(a).module,_=l.get(o).module,x=this._getPrimitiveState(s,r,i),v=this._getDepthCompare(i),T=u.getCurrentDepthStencilFormat(e.context),S=this._getSampleCount(e.context);SA.bindGroupLayouts=d;const w=h.createPipelineLayout(SA);SA.reset(),MA.label=`renderPipeline_${i.name||i.type}_${i.id}`,MA.vertex=Object.assign({},b,{buffers:p}),MA.fragment=Object.assign({},_,{targets:y}),MA.primitive=x,MA.multisample.count=S,MA.multisample.alphaToCoverageEnabled=i.alphaToCoverage&&S>1,MA.layout=w;const M={},E=e.context.depth,A=e.context.stencil;!0!==E&&!0!==A||(!0===E&&(M.format=T,M.depthWriteEnabled=i.depthWrite,M.depthCompare=v),!0===A&&(M.stencilFront=f,M.stencilBack=f,M.stencilReadMask=i.stencilFuncMask,M.stencilWriteMask=i.stencilWriteMask),!0===i.polygonOffset&&x.topology===GT&&(M.depthBias=i.polygonOffsetUnits,M.depthBiasSlopeScale=i.polygonOffsetFactor,M.depthBiasClamp=0),MA.depthStencil=M),h.pushErrorScope("validation");const N=[{program:a,module:b.module},{program:o,module:_.module}],C=MA.label;if(null===t)c.pipeline=h.createRenderPipeline(MA),MA.reset(),h.popErrorScope().then(e=>{null!==e&&(c.error=!0,At(`WebGPURenderer: Render pipeline creation failed (${C}): ${e.message}`),this._reportShaderDiagnostics(N,C))});else{const e=new Promise(async e=>{try{let e=null,t=null;try{t=h.createRenderPipelineAsync(MA)}catch(t){e=t}if(MA.reset(),null!==t)try{c.pipeline=await t}catch(t){e=t}const s=await h.popErrorScope();if(null!==s||null!==e){c.error=!0;const t=s&&s.message||e&&e.message||"unknown";At(`WebGPURenderer: Async render pipeline creation failed (${C}): ${t}`),await this._reportShaderDiagnostics(N,C)}}finally{e()}});t.push(e)}}createBundleEncoder(e,t="renderBundleEncoder"){const s=this.backend,{utils:i,device:r}=s,n=i.getCurrentDepthStencilFormat(e),a=i.getCurrentColorFormats(e),o=this._getSampleCount(e);wA.label=t,wA.colorFormats=a,wA.depthStencilFormat=n,wA.sampleCount=o;const l=r.createRenderBundleEncoder(wA);return wA.reset(),l}createComputePipeline(e,t,s=null){const i=this.backend,r=i.device,n=i.get(e.computeProgram).module,a=i.get(e),o=[];for(const e of t){const t=i.get(e),{layoutGPU:s}=t.layout;o.push(s)}const l=e.computeProgram,h=`computePipeline_${l.stage}${l.name?`_${l.name}`:""}`;r.pushErrorScope("validation"),SA.bindGroupLayouts=o;const u=r.createPipelineLayout(SA);if(SA.reset(),TA.label=h,TA.compute=n,TA.layout=u,null===s)a.pipeline=r.createComputePipeline(TA),TA.reset(),r.popErrorScope().then(e=>{null!==e&&(a.error=!0,At(`WebGPURenderer: Compute pipeline creation failed (${h}): ${e.message}`),this._reportShaderDiagnostics([{program:l,module:n.module}],h))});else{const e=new Promise(async e=>{try{let e=null,t=null;try{t=r.createComputePipelineAsync(TA)}catch(t){e=t}if(TA.reset(),null!==t)try{a.pipeline=await t}catch(t){e=t}const s=await r.popErrorScope();if(null!==s||null!==e){a.error=!0;const t=s&&s.message||e&&e.message||"unknown";At(`WebGPURenderer: Async compute pipeline creation failed (${h}): ${t}`),await this._reportShaderDiagnostics([{program:l,module:n.module}],h)}}finally{e()}});s.push(e)}}async _reportShaderDiagnostics(e,t){for(const{program:s,module:i}of e){const e=await i.getCompilationInfo();if(0===e.messages.length)continue;const r=s.code.split("\n");for(const i of e.messages){const e=i.lineNum>0?` at line ${i.lineNum}${i.linePos>0?`:${i.linePos}`:""}`:"",n=`WebGPURenderer [${t} / ${s.stage} ${i.type}]${e}: ${i.message}`;let a="";i.lineNum>0&&i.lineNum<=r.length&&(a=`\n ${r[i.lineNum-1]}`,i.linePos>0&&(a+=`\n ${" ".repeat(i.linePos-1)}^`)),("error"===i.type?At:Et)(n+a)}}}_getBlending(e){let t,s;const i=e.blending,r=e.blendSrc,n=e.blendDst,a=e.blendEquation;if(5===i){const i=null!==e.blendSrcAlpha?e.blendSrcAlpha:r,o=null!==e.blendDstAlpha?e.blendDstAlpha:n,l=null!==e.blendEquationAlpha?e.blendEquationAlpha:a;t={srcFactor:this._getBlendFactor(r),dstFactor:this._getBlendFactor(n),operation:this._getBlendOperation(a)},s={srcFactor:this._getBlendFactor(i),dstFactor:this._getBlendFactor(o),operation:this._getBlendOperation(l)}}else{const r=(e,i,r,n)=>{t={srcFactor:e,dstFactor:i,operation:yM},s={srcFactor:r,dstFactor:n,operation:yM}};if(e.premultipliedAlpha)switch(i){case 1:r(nM,hM,nM,hM);break;case 2:r(nM,nM,nM,nM);break;case 3:r(rM,oM,rM,nM);break;case 4:r(uM,hM,rM,nM)}else switch(i){case 1:r(lM,hM,nM,hM);break;case 2:r(lM,nM,nM,nM);break;case 3:At(`WebGPURenderer: "SubtractiveBlending" requires "${e.isMaterial?"material":"blendMode"}.premultipliedAlpha = true".`);break;case 4:At(`WebGPURenderer: "MultiplyBlending" requires "${e.isMaterial?"material":"blendMode"}.premultipliedAlpha = true".`)}}if(void 0!==t&&void 0!==s)return{color:t,alpha:s};At("WebGPURenderer: Invalid blending: ",i)}_getBlendFactor(e){let t;switch(e){case u:t=rM;break;case 201:t=nM;break;case 202:t=aM;break;case 203:t=oM;break;case 204:t=lM;break;case 205:t=hM;break;case 208:t=uM;break;case 209:t=cM;break;case 206:t=dM;break;case 207:t=pM;break;case 210:t=mM;break;case 211:case 213:t=fM;break;case 212:case 214:t=gM;break;default:At("WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const s=e.stencilFunc;switch(s){case 512:t=jT;break;case 519:t=QT;break;case 513:t=WT;break;case 515:t=qT;break;case 514:t=HT;break;case 518:t=KT;break;case 516:t=XT;break;case 517:t=YT;break;default:At("WebGPURenderer: Invalid stencil function.",s)}return t}_getStencilOperation(e){let t;switch(e){case st:t=wM;break;case 0:t=MM;break;case 7681:t=EM;break;case 5386:t=AM;break;case 7682:t=NM;break;case 7683:t=CM;break;case 34055:t=RM;break;case 34056:t=PM;break;default:At("WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case n:t=yM;break;case 101:t=bM;break;case 102:t=_M;break;case 103:t=xM;break;case 104:t=vM;break;default:At("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?aS:oS);let n=1===s.side;return e.isMesh&&e.matrixWorld.determinantAffine()<0&&(n=!n),i.frontFace=!0===n?iS:sS,i.cullMode=2===s.side?rS:nS,i}_getColorWriteMask(e){return!0===e.colorWrite?SM:TM}_getDepthCompare(e){let t;if(!1===e.depthTest)t=QT;else{const s=this.backend.parameters.reversedDepthBuffer?Rt[e.depthFunc]:e.depthFunc;switch(s){case 0:t=jT;break;case 1:t=QT;break;case 2:t=WT;break;case 3:t=qT;break;case 4:t=HT;break;case 5:t=KT;break;case 6:t=XT;break;case 7:t=YT;break;default:At("WebGPUPipelineUtils: Invalid depth function.",s)}}return t}}class AA{constructor(){this.label="",this.type=void 0,this.count=0}reset(){this.label="",this.type=void 0,this.count=0}}const NA=new hE,CA=new uE,RA=new AA;class PA extends DT{constructor(e,t,s=2048){super(s),this.device=e,this.type=t,RA.label=`queryset_global_timestamp_${t}`,RA.type="timestamp",RA.count=this.maxQueries,this.querySet=this.device.createQuerySet(RA),RA.reset();const i=8*this.maxQueries;NA.label=`buffer_timestamp_resolve_${t}`,NA.size=i,NA.usage=GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC,this.resolveBuffer=this.device.createBuffer(NA),NA.reset(),NA.label=`buffer_timestamp_result_${t}`,NA.size=i,NA.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ,this.resultBuffer=this.device.createBuffer(NA),NA.reset()}allocateQueriesForContext(e){if(!this.trackTimestamp||this.isDisposed)return null;this.currentQueryIndex+2>this.maxQueries&&(this.resolveQueriesAsync(),this.currentQueryIndex=0,this.queryOffsets.clear());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(CA);i.resolveQuerySet(this.querySet,0,t,this.resolveBuffer,0),i.copyBufferToBuffer(this.resolveBuffer,0,this.resultBuffer,0,s);const r=i.finish();if(oE(this.device,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)),a={},o=[];this.timestamps.clear();for(const[t,s]of e){const e=t.match(/^(.*):f(\d+)$/),i=parseInt(e[2]);!1===o.includes(i)&&o.push(i),void 0===a[i]&&(a[i]=0);const r=n[s],l=n[s+1],h=Number(l-r)/1e6;this.timestamps.set(t,h),a[i]+=h}const l=a[o[o.length-1]];return this.resultBuffer.unmap(),this.lastValue=l,this.frames=o,l}catch(e){return At("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){At("Error waiting for pending resolve:",e)}if(this.resultBuffer&&"mapped"===this.resultBuffer.mapState)try{this.resultBuffer.unmap()}catch(e){At("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.timestamps.clear(),this.frames=[],this.pendingResolve=null}}}class BA{constructor(){this.view=null,this.depthLoadOp=void 0,this.depthStoreOp=void 0,this.depthClearValue=void 0,this.depthReadOnly=!1,this.stencilLoadOp=void 0,this.stencilStoreOp=void 0,this.stencilClearValue=0,this.stencilReadOnly=!1}reset(){this.view=null,this.depthLoadOp=void 0,this.depthStoreOp=void 0,this.depthClearValue=void 0,this.depthReadOnly=!1,this.stencilLoadOp=void 0,this.stencilStoreOp=void 0,this.stencilClearValue=0,this.stencilReadOnly=!1}}const FA={r:0,g:0,b:0,a:1},LA={r:0,g:0,b:0,a:0},DA=new hE,OA=new uE,IA=new class{constructor(){this.label="",this.timestampWrites=void 0}reset(){this.label="",this.timestampWrites=void 0}},UA=new AA,kA=new gE,zA=new class{constructor(){this.querySet=null,this.beginningOfPassWriteIndex=void 0,this.endOfPassWriteIndex=void 0}reset(){this.querySet=null,this.beginningOfPassWriteIndex=void 0,this.endOfPassWriteIndex=void 0}},VA=new RE,GA=new RE,$A=new yE,jA=new bE,WA=new PE;class HA extends yT{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=void 0===e.alpha||e.alpha,this.parameters.requiredLimits=void 0===e.requiredLimits?{}:e.requiredLimits,this.compatibilityMode=null,this.device=null,this.defaultRenderPassdescriptor=null,this.utils=new aE(this),this.attributeUtils=new fA(this),this.bindingUtils=new xA(this),this.capabilities=new vA(this),this.pipelineUtils=new EA(this),this.textureUtils=new WE(this),this.occludedResolveCache=new Map;const t="undefined"==typeof navigator||!1===/Android/.test(navigator.userAgent);this._compatibility={[yt]:t}}async init(e){await super.init(e);const t=this.parameters;let s;if(void 0===t.device){const i={powerPreference:t.powerPreference,featureLevel:"compatibility",xrCompatible:e.xr.enabled},r="undefined"!=typeof navigator?await navigator.gpu.requestAdapter(i):null;if(null===r)throw new Error("THREE.WebGPUBackend: Unable to create WebGPU adapter.");const n=Object.values(JM),a=[];for(const e of n)r.features.has(e)&&a.push(e);const o={requiredFeatures:a,requiredLimits:t.requiredLimits};s=await r.requestDevice(o)}else s=t.device;this.compatibilityMode=!s.features.has("core-features-and-limits"),this.compatibilityMode&&(e._samples=0),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)}),s.onuncapturederror=t=>{const s=t.error,i=s&&s.constructor?s.constructor.name:"GPUError",r=s&&s.message||"Unknown uncaptured GPU error";e.onError({api:"WebGPU",type:i,message:r,originalEvent:t})},this.device=s,this.trackTimestamp=this.trackTimestamp&&this.hasFeature(JM.TimestampQuery),this.updateSize()}setXRRenderTargetTextures(e,t,s=null){const i=this.get(e.texture);i.texture=t,i.format=t.format,i.externalTexture=!0,i.xrViewDescriptors=s,i.initialized=!0}get context(){const e=this.renderer.getCanvasTarget(),s=this.get(e);let i=s.context;if(void 0===i){const r=this.parameters;i=!0===e.isDefaultCanvasTarget&&void 0!==r.context?r.context:e.domElement.getContext("webgpu"),"setAttribute"in e.domElement&&e.domElement.setAttribute("data-engine",`three.js r${t} webgpu`);const n=r.alpha?"premultiplied":"opaque",a=r.outputType===Z?"extended":"standard";i.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:n,toneMapping:{mode:a}}),s.context=i}return i}get coordinateSystem(){return mt}get hasTimestamp(){return!0}async getArrayBufferAsync(e,t=null,s=0,i=-1){return await this.attributeUtils.getArrayBufferAsync(e,t,s,i)}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){if(r=new pE,r.colorAttachments.push(new dE),!0===e.depth||!0===e.stencil){const t=new BA;t.view=this.textureUtils.getDepthBuffer(e.depth,e.stencil).createView(),r.depthStencilAttachment=t}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){const t=e.camera;return e.depthTexture&&!0===e.depthTexture.isArrayTexture&&null!==t&&!0===t.isArrayCamera}_hasExternalTexture(e){const t=e.textures;if(null===t)return!1;for(let e=0;e<t.length;e++)if(!0===this.get(t[e]).externalTexture)return!0;return!1}_getExternalMSAATextures(e,t,s){const i=this.utils.getSampleCount(e.sampleCount);if(1===i){if(void 0!==t.msaaTextures){for(const e of t.msaaTextures)e.destroy();t.msaaTextures=void 0}return null}const r=e.renderTarget,n=r.width,a=r.height,o=t.format;if(void 0===t.msaaTextures||t.msaaTextures.length!==s||t.msaaWidth!==n||t.msaaHeight!==a||t.msaaSamples!==i||t.msaaFormat!==o){if(void 0!==t.msaaTextures)for(const e of t.msaaTextures)e.destroy();$A.size.width=n,$A.size.height=a,$A.sampleCount=i,$A.format=o,$A.usage=GPUTextureUsage.RENDER_ATTACHMENT,t.msaaTextures=[];for(let e=0;e<s;e++)$A.label=r.texture.name+"-msaa-"+e,t.msaaTextures.push(this.device.createTexture($A));$A.reset(),t.msaaWidth=n,t.msaaHeight=a,t.msaaSamples=i,t.msaaFormat=o}return t.msaaTextures}_createExternalTextureViews(e,t){const s=[],i=e.camera,r=t.xrViewDescriptors,n=Math.max(r?.length||0,e.activeCubeFace+1,1),a=this._getExternalMSAATextures(e,t,n);if(r&&null!==i&&!0===i.isArrayCamera)for(let i=0;i<r.length;i++){const n=t.texture.createView(r[i]);s.push({view:null!==a?a[i].createView():n,resolveTarget:null!==a&&!0===e.renderTarget.resolveColorBuffer?n:void 0,depthSlice:void 0})}else{const i=e.activeCubeFace,r=t.texture.createView({dimension:HM,baseArrayLayer:i,arrayLayerCount:1});s.push({view:null!==a?a[i].createView():r,resolveTarget:null!==a&&!0===e.renderTarget.resolveColorBuffer?r:void 0,depthSlice:void 0})}return s}_getRenderPassDescriptor(e,t={}){const s=e.renderTarget,i=this.get(s),r=this._hasExternalTexture(e);let n=i.descriptors;(void 0===n||i.width!==s.width||i.height!==s.height||i.samples!==s.samples||r)&&(n={},i.descriptors=n);const a=e.getCacheKey();let o=n[a];if(void 0===o||r){const t=e.textures,r=[];let l;const h=this._isRenderCameraDepthArray(e);for(let i=0;i<t.length;i++){const n=this.get(t[i]);if(!0!==n.externalTexture){if(jA.label=`colorAttachment_${i}`,jA.baseMipLevel=e.activeMipmapLevel,jA.mipLevelCount=1,jA.baseArrayLayer=e.activeCubeFace,jA.arrayLayerCount=1,jA.dimension=HM,s.isRenderTarget3D)l=e.activeCubeFace,jA.baseArrayLayer=0,jA.dimension=YM;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++){jA.baseArrayLayer=e,jA.arrayLayerCount=1,jA.dimension=HM;const t=n.texture.createView(jA),i=n.msaaTextures?.[e];r.push({view:void 0!==i?i.createView():t,resolveTarget:void 0!==i&&!0===s.resolveColorBuffer?t:void 0,depthSlice:void 0})}}else jA.dimension=qM;if(!0!==h){const t=n.texture.createView(jA);let i,a;void 0!==n.msaaTexture?(i=n.msaaTexture.createView(),a=!0===s.resolveColorBuffer?t:void 0):void 0!==n.msaaTextures?(i=n.msaaTextures[e.activeCubeFace].createView(),a=!0===s.resolveColorBuffer?t:void 0):(i=t,a=void 0),r.push({view:i,resolveTarget:a,depthSlice:l})}jA.reset()}else r.push(...this._createExternalTextureViews(e,n))}const u=[];for(let e=0;e<r.length;e++){const t=r[e],s=new dE;s.view=t.view,s.depthSlice=t.depthSlice,s.resolveTarget=t.resolveTarget,u.push(s)}if(o={textureViews:r,colorAttachments:u,descriptor:new pE},e.depth){const t=this.get(e.depthTexture);(e.depthTexture.isArrayTexture||e.depthTexture.isCubeTexture)&&(jA.dimension=HM,jA.arrayLayerCount=1,jA.baseArrayLayer=e.activeCubeFace);const s=new BA,i=t.msaaTextures?.[e.activeCubeFace];s.view=void 0!==i?i.createView():t.texture.createView(jA),o.depthStencilAttachment=s,jA.reset()}n[a]=o,i.width=s.width,i.height=s.height,i.samples=s.samples,i.activeMipmapLevel=e.activeMipmapLevel,i.activeCubeFace=e.activeCubeFace}const l=o.descriptor;l.reset();for(let e=0;e<o.colorAttachments.length;e++){const s=o.colorAttachments[e];let i={r:0,g:0,b:0,a:1};0===e&&t.clearValue&&(i=t.clearValue),s.loadOp=t.loadOp||eS,s.storeOp=t.storeOp||ZT,s.clearValue=i,l.colorAttachments.push(s)}return o.depthStencilAttachment&&(l.depthStencilAttachment=o.depthStencilAttachment),l}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,UA.label=`occlusionQuerySet_${e.id}`,UA.type="occlusion",UA.count=i,r=s.createQuerySet(UA),UA.reset(),t.occlusionQuerySet=r,t.occlusionQueryIndex=0,t.occlusionQueryObjects=new Array(i),t.lastOcclusionObject=null):void 0!==t.lastOcclusionObject&&(t.lastOcclusionObject=void 0,t.occlusionQuerySet.destroy(),t.occlusionQuerySet=void 0),n=null===e.textures?this._getDefaultRenderPassDescriptor():this._getRenderPassDescriptor(e,{loadOp:eS}),this.initTimestampQuery(gt,this.getTimestampUID(e),n),n.occlusionQuerySet=r;const a=n.depthStencilAttachment,o=e.renderTarget,l=e.sampleCount>1&&!1===o?.storeMultisampledColorBuffer,h=e.sampleCount>1&&!1===o?.storeMultisampledDepthBuffer,u=e.sampleCount>1&&!1===o?.storeMultisampledStencilBuffer,c=!0===e.fullscreenPass&&this._hasExternalTexture(e);if(null!==e.textures){const t=n.colorAttachments;for(let s=0;s<t.length;s++){const i=t[s];if(e.clearColor||l||c){const t=e.mrt?e.mrt.getClearColor(e.textures[s].name):null;null!==t?i.clearValue=t:0===s?i.clearValue=e.clearColorValue:(FA.r=0,FA.g=0,FA.b=0,FA.a=1,i.clearValue=FA),i.loadOp=tS}else i.loadOp=eS;i.storeOp=l?JT:ZT}}else{const t=n.colorAttachments[0];e.clearColor?(t.clearValue=e.clearColorValue,t.loadOp=tS):t.loadOp=eS,t.storeOp=ZT}e.depth&&(e.clearDepth||h?(a.depthClearValue=e.clearDepthValue,a.depthLoadOp=tS):a.depthLoadOp=eS,a.depthStoreOp=h?JT:ZT),e.stencil&&(e.clearStencil||u?(a.stencilClearValue=e.clearStencilValue,a.stencilLoadOp=tS):a.stencilLoadOp=eS,a.stencilStoreOp=u?JT:ZT),OA.label="renderContext_"+e.id;const d=s.createCommandEncoder(OA);if(OA.reset(),!0===this._isRenderCameraDepthArray(e)){const s=e.camera.cameras;t.layerDescriptors&&t.layerDescriptors.length===s.length?this._updateArrayCameraLayerDescriptors(e,t,n,s):this._createArrayCameraLayerDescriptors(e,t,n,s),this._createArrayCameraBundleEncoders(e,t),t.arrayCameraRenderStages=[],t.currentPass=null}else{t.bundleEncoders=void 0,t.bundleSets=void 0,t.arrayCameraRenderStages=void 0;const s=d.beginRenderPass(n);t.currentPass=s,e.viewport&&this.updateViewport(e),e.scissor&&this.updateScissor(e)}t.descriptor=n,t.encoder=d,t.renderBundles=[],this._resetRenderContextData(t)}_resetRenderContextData(e){e.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},void 0===e.currentBlendColor&&(e.currentBlendColor=new Xs),e.currentBlendColor.setRGB(0,0,0),e.currentBlendAlpha=0,e.currentStencilRef=0}_createArrayCameraBundleEncoders(e,t){const s=e.camera.cameras;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)}}_finishArrayCameraBundleEncoders(e){const t=[];for(const s of e.bundleEncoders)t.push(s.finish());return t}_createArrayCameraLayerDescriptors(e,t,s,i){const r=s.depthStencilAttachment;t.layerDescriptors=[];const n=this.get(e.depthTexture);n.viewCache||(n.viewCache=[]);for(let a=0;a<i.length;a++){const i=s.colorAttachments[0],o=s.colorAttachments[a],l=new dE;l.view=o.view,l.depthSlice=o.depthSlice,l.resolveTarget=o.resolveTarget,l.loadOp=i.loadOp,l.storeOp=i.storeOp,l.clearValue=i.clearValue;const h=new pE;if(h.label=s.label,h.occlusionQuerySet=s.occlusionQuerySet,h.timestampWrites=s.timestampWrites,h.colorAttachments.push(l),s.depthStencilAttachment){const t=a;if(!n.viewCache[t]){const e=n.msaaTextures?.[t];void 0!==e?n.viewCache[t]=e.createView():(jA.dimension=HM,jA.baseArrayLayer=a,jA.arrayLayerCount=1,n.viewCache[t]=n.texture.createView(jA)),jA.reset()}const s=new BA;s.view=n.viewCache[t],s.depthLoadOp=r.depthLoadOp||tS,s.depthStoreOp=r.depthStoreOp||ZT,s.depthClearValue=r.depthClearValue||1,e.stencil&&(s.stencilLoadOp=r.stencilLoadOp,s.stencilStoreOp=r.stencilStoreOp,s.stencilClearValue=r.stencilClearValue),h.depthStencilAttachment=s}else{const e=new BA;e.view=r.view,e.depthLoadOp=r.depthLoadOp,e.depthStoreOp=r.depthStoreOp,e.depthClearValue=r.depthClearValue,e.depthReadOnly=r.depthReadOnly,e.stencilLoadOp=r.stencilLoadOp,e.stencilStoreOp=r.stencilStoreOp,e.stencilClearValue=r.stencilClearValue,e.stencilReadOnly=r.stencilReadOnly,h.depthStencilAttachment=e}t.layerDescriptors.push(h)}}_updateArrayCameraLayerDescriptors(e,t,s,i){const r=e.renderTarget,n=e.sampleCount>1&&!1===r?.storeMultisampledDepthBuffer,a=e.sampleCount>1&&!1===r?.storeMultisampledStencilBuffer;for(let r=0;r<i.length;r++){const i=t.layerDescriptors[r],o=s.colorAttachments[0],l=s.colorAttachments[r],h=i.colorAttachments[0];if(h.view=l.view,h.resolveTarget=l.resolveTarget,h.depthSlice=l.depthSlice,h.loadOp=o.loadOp,h.storeOp=o.storeOp,h.clearValue=o.clearValue,i.depthStencilAttachment){const t=i.depthStencilAttachment;e.depth&&(e.clearDepth||n?(t.depthClearValue=e.clearDepthValue,t.depthLoadOp=tS):t.depthLoadOp=eS),e.stencil&&(e.clearStencil||a?(t.stencilClearValue=e.clearStencilValue,t.stencilLoadOp=tS):t.stencilLoadOp=eS)}}}finishRender(e){const t=this.get(e),s=e.occlusionQueryCount;t.renderBundles.length>0&&t.currentPass.executeBundles(t.renderBundles);const i=t.lastOcclusionObject;i&&!0===i.occlusionTest&&t.currentPass.endOcclusionQuery();const r=t.encoder;if(!0===this._isRenderCameraDepthArray(e)){const s=this._finishArrayCameraBundleEncoders(t),i=t.arrayCameraRenderStages;i.push({bundles:s});for(let s=0;s<t.layerDescriptors.length;s++){const n=t.layerDescriptors[s],a=n.colorAttachments.map(e=>e.loadOp),o=n.colorAttachments.map(e=>e.storeOp),l=n.depthStencilAttachment?.depthLoadOp,h=n.depthStencilAttachment?.depthStoreOp,u=n.depthStencilAttachment?.stencilLoadOp,c=n.depthStencilAttachment?.stencilStoreOp;for(let t=0;t<i.length;t++){const d=i[t],p=d.bundles[s],m=t===i.length-1;for(let e=0;e<n.colorAttachments.length;e++){const s=n.colorAttachments[e];s.loadOp=0===t?a[e]:eS,s.storeOp=m?o[e]:ZT}e.depth&&(n.depthStencilAttachment.depthLoadOp=0===t?l:eS,n.depthStencilAttachment.depthStoreOp=m?h:ZT),e.stencil&&(n.depthStencilAttachment.stencilLoadOp=0===t?u:eS,n.depthStencilAttachment.stencilStoreOp=m?c:ZT);const f=r.beginRenderPass(n);if(e.viewport){const{x:t,y:s,width:i,height:r,minDepth:n,maxDepth:a}=e.viewportValue;f.setViewport(t,s,i,r,n,a)}if(e.scissor){const{x:t,y:s,width:i,height:r}=e.scissorValue;f.setScissorRect(t,s,i,r)}if(f.executeBundles([p]),f.end(),void 0!==d.framebufferCopy){const{texture:e,sourceGPU:t,destinationGPU:i,rectangle:n,generateMipmaps:a}=d.framebufferCopy;this._copyFramebufferToTexture(r,e,t,i,n,s,a)}}for(let e=0;e<n.colorAttachments.length;e++)n.colorAttachments[e].loadOp=a[e],n.colorAttachments[e].storeOp=o[e];e.depth&&(n.depthStencilAttachment.depthLoadOp=l,n.depthStencilAttachment.depthStoreOp=h),e.stencil&&(n.depthStencilAttachment.stencilLoadOp=u,n.depthStencilAttachment.stencilStoreOp=c)}}else t.currentPass&&t.currentPass.end();if(s>0){const i=8*s;let r=this.occludedResolveCache.get(i);void 0===r&&(DA.size=i,DA.usage=GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC,r=this.device.createBuffer(DA),DA.reset(),this.occludedResolveCache.set(i,r)),DA.size=i,DA.usage=GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ;const n=this.device.createBuffer(DA);DA.reset(),t.encoder.resolveQuerySet(t.occlusionQuerySet,0,s,r,0),t.encoder.copyBufferToBuffer(r,0,n,0,i),t.occlusionQueryBuffer=n,this.resolveOccludedAsync(e)}if(oE(this.device,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++){const s=i[t];void 0!==s&&n[t]===BigInt(0)&&e.add(s)}s.destroy(),t.occluded=e}}updateViewport(e){const{currentPass:t}=this.get(e),{x:s,y:i,width:r,height:n,minDepth:a,maxDepth:o}=e.viewportValue;t.setViewport(s,i,r,n,a,o)}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 a,o,l,h=[];if(e){const e=this.getClearColor();FA.r=e.r,FA.g=e.g,FA.b=e.b,FA.a=e.a}if(null===i){o=n.depth,l=n.stencil;const t=this._getDefaultRenderPassDescriptor();if(e){h=t.colorAttachments;const e=h[0];e.clearValue=FA,e.loadOp=tS,e.storeOp=ZT}(o||l)&&(a=t.depthStencilAttachment)}else{o=i.depth,l=i.stencil;const r={loadOp:e?tS:eS,clearValue:e?FA:void 0};o&&(r.depthLoadOp=t?tS:eS,r.depthClearValue=t?n.getClearDepth():void 0,r.depthStoreOp=ZT),l&&(r.stencilLoadOp=s?tS:eS,r.stencilClearValue=s?n.getClearStencil():void 0,r.stencilStoreOp=ZT);const u=this._getRenderPassDescriptor(i,r);h=u.colorAttachments,a=u.depthStencilAttachment}o&&a&&(t?(a.depthLoadOp=tS,a.depthClearValue=n.getClearDepth(),a.depthStoreOp=ZT):(a.depthLoadOp=eS,a.depthStoreOp=ZT)),l&&a&&(s?(a.stencilLoadOp=tS,a.stencilClearValue=n.getClearStencil(),a.stencilStoreOp=ZT):(a.stencilLoadOp=eS,a.stencilStoreOp=ZT)),OA.label="clear";const u=r.createCommandEncoder(OA);OA.reset();u.beginRenderPass({colorAttachments:h,depthStencilAttachment:a}).end(),oE(r,u.finish())}beginCompute(e){const t=this.get(e),s="computeGroup_"+e.id;IA.label=s,OA.label=s,this.initTimestampQuery(ft,this.getTimestampUID(e),IA),t.cmdEncoderGPU=this.device.createCommandEncoder(OA),t.passEncoderGPU=t.cmdEncoderGPU.beginComputePass(IA),t.currentPipeline=null,OA.reset(),IA.reset()}compute(e,t,s,i,r=null){const n=this.get(t),a=this.get(e),{passEncoderGPU:o}=a,l=this.get(i).pipeline;a.currentPipeline!==l&&(o.setPipeline(l),a.currentPipeline=l);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.dispatchSize||t.count),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 a=Math.ceil(e/i),o=this.device.limits.maxComputeWorkgroupsPerDimension;r=[a,1,1],a>o&&(r[0]=Math.min(a,o),r[1]=Math.ceil(a/o)),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(),oE(this.device,t.cmdEncoderGPU.finish())}_draw(e,t,s,i,r,n,a,o,l,h=-1){const{object:u,material:c,context:d}=e,p=e.getIndex(),m=null!==p;l.pipeline!==i&&(o.setPipeline(i),l.pipeline=i);const f=l.bindingGroups;for(let e=0,t=r.length;e<t;e++){if(e===h)continue;const t=r[e],s=this.get(t).group;f[e]!==s&&(o.setBindGroup(e,s),f[e]=s)}if(!0===m&&l.index!==p){const e=this.get(p).buffer,t=p.array instanceof Uint16Array?aS:oS;o.setIndexBuffer(e,t),l.index=p}for(let e=0,t=n.length;e<t;e++){const t=n[e];if(l.attributes[e]!==t){const s=this.get(t).buffer;o.setVertexBuffer(e,s),l.attributes[e]=t}}if(!0===d.stencil&&!0===c.stencilWrite&&s.currentStencilRef!==c.stencilRef&&(o.setStencilReference(c.stencilRef),s.currentStencilRef=c.stencilRef),5===c.blending&&void 0!==o.setBlendConstant){const e=c.blendColor,t=c.blendAlpha;!1!==e.equals(s.currentBlendColor)&&t===s.currentBlendAlpha||(LA.r=e.r,LA.g=e.g,LA.b=e.b,LA.a=t,o.setBlendConstant(LA),s.currentBlendColor.copy(e),s.currentBlendAlpha=t)}if(!0===u.isBatchedMesh){const e=u._multiDrawStarts,s=u._multiDrawCounts,i=u._multiDrawCount,r=u._multiDrawBytesPerElement;for(let n=0;n<i;n++)!0===m?o.drawIndexed(s[n],1,e[n]/r,0,n):o.draw(s[n],1,e[n],n),t.update(u,s[n],1)}else if(!0===m){const{vertexCount:s,instanceCount:i,firstVertex:r}=a,n=e.getIndirect();if(null!==n){const t=this.get(n).buffer,s=e.getIndirectOffset(),i=Array.isArray(s)?s:[s];for(let e=0;e<i.length;e++)o.drawIndexedIndirect(t,i[e])}else o.drawIndexed(s,i,r,0,0);t.update(u,s,i)}else{const{vertexCount:s,instanceCount:i,firstVertex:r}=a,n=e.getIndirect();if(null!==n){const t=this.get(n).buffer,s=e.getIndirectOffset(),i=Array.isArray(s)?s:[s];for(let e=0;e<i.length;e++)o.drawIndirect(t,i[e])}else o.draw(s,i,r,0);t.update(u,s,i)}}draw(e,t){const{object:s,context:i,pipeline:r}=e,n=this.get(i),a=this.get(r),o=a.pipeline;if(!0===a.error)return;const l=e.getDrawParameters();if(null===l)return;const h=e.getBindings(),u=e.getVertexBuffers();if(e.camera.isArrayCamera&&e.camera.cameras.length>0){const r=this.get(e.camera),a=e.camera.cameras,c=e.getBindingGroup("cameraIndex");if(void 0===r.indexesGPU||r.indexesGPU.length!==a.length){const e=this.get(c),t=[],s=new Uint32Array([0,0,0,0]);for(let i=0,r=a.length;i<r;i++){s[0]=i;const{layoutGPU:r}=e.layout,n=this.bindingUtils.createBindGroupIndex(s,r);t.push(n)}r.indexesGPU=t}const d=i.renderTarget,p=null===d||!0===d.isPostProcessingRenderTarget?this.renderer.getPixelRatio():1,m=c?h.indexOf(c):-1;for(let c=0,d=a.length;c<d;c++){const d=a[c];if(s.layers.test(d.layers)){const s=d.viewport;let a=n.currentPass,f=n.currentSets;const g=void 0!==n.bundleEncoders;if(g){a=n.bundleEncoders[c],f=n.bundleSets[c]}if(s&&!g&&a.setViewport(Math.floor(s.x*p),Math.floor(s.y*p),Math.floor(s.width*p),Math.floor(s.height*p),i.viewportValue.minDepth,i.viewportValue.maxDepth),-1!==m&&r.indexesGPU){const e=r.indexesGPU[c];f.bindingGroups[m]!==e&&(a.setBindGroup(m,e),f.bindingGroups[m]=e)}this._draw(e,t,n,o,h,u,l,a,f,m)}}}else if(n.currentPass){if(n.currentPass instanceof GPURenderBundleEncoder)!0===s.occlusionTest&&Nt("WebGPUBackend: Occlusion queries can not be recorded into render bundles.");else if(void 0!==n.occlusionQuerySet){const e=n.lastOcclusionObject;e!==s&&(null!==e&&!0===e.occlusionTest&&(n.currentPass.endOcclusionQuery(),n.occlusionQueryIndex++),!0===s.occlusionTest&&(n.currentPass.beginOcclusionQuery(n.occlusionQueryIndex),n.occlusionQueryObjects[n.occlusionQueryIndex]=s),n.lastOcclusionObject=s)}this._draw(e,t,n,o,h,u,l,n.currentPass,n.currentSets)}}needsRenderUpdate(e){const t=this.get(e),{object:s,material:i}=e,r=this.utils,n=r.getSampleCountRenderContext(e.context),a=r.getCurrentColorSpace(e.context),o=r.getCurrentColorFormat(e.context),l=r.getCurrentDepthStencilFormat(e.context),h=r.getPrimitiveTopology(s,i),u=s.isMesh&&s.matrixWorld.determinantAffine()<0;let c=!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.polygonOffset===i.polygonOffset&&t.polygonOffsetFactor===i.polygonOffsetFactor&&t.polygonOffsetUnits===i.polygonOffsetUnits&&t.side===i.side&&t.alphaToCoverage===i.alphaToCoverage&&t.sampleCount===n&&t.colorSpace===a&&t.colorFormat===o&&t.depthStencilFormat===l&&t.primitiveTopology===h&&t.frontFaceCW===u&&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.polygonOffset=i.polygonOffset,t.polygonOffsetFactor=i.polygonOffsetFactor,t.polygonOffsetUnits=i.polygonOffsetUnits,t.side=i.side,t.alphaToCoverage=i.alphaToCoverage,t.sampleCount=n,t.colorSpace=a,t.colorFormat=o,t.depthStencilFormat=l,t.primitiveTopology=h,t.frontFaceCW=u,t.clippingContextCacheKey=e.clippingContextCacheKey,c=!0),c}getRenderCacheKey(e){const{object:t,material:s}=e,i=this.utils,r=e.context,n=t.isMesh&&t.matrixWorld.determinantAffine()<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.polygonOffset,s.polygonOffsetFactor,s.polygonOffsetUnits,s.side,s.alphaToCoverage,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)}destroySampler(e){this.textureUtils.destroySampler(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 PA(this.device,e,2048));const i=this.timestampQueryPool[e],r=i.allocateQueriesForContext(t);zA.querySet=i.querySet,zA.beginningOfPassWriteIndex=r,zA.endOfPassWriteIndex=r+1,s.timestampWrites=zA}createNodeBuilder(e,t){return new hA(e,t)}createProgram(e){const t=this.get(e);kA.label=e.stage+(""!==e.name?`_${e.name}`:""),kA.code=e.code,t.module={module:this.device.createShaderModule(kA),entryPoint:"main"},kA.reset()}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){this.pipelineUtils.createRenderPipeline(e,t)}createComputePipeline(e,t,s=null){this.pipelineUtils.createComputePipeline(e,t,s)}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,s._currentPass=null,s._currentSets=null}addBundle(e,t){this.get(e).renderBundles.push(this.get(t).bundleGPU)}createUniformBuffer(e){const t=this.get(e);if(void 0===t.buffer){const s=e.byteLength,i=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,r=[];e.visibility&$T.VERTEX&&r.push("vertex"),e.visibility&$T.FRAGMENT&&r.push("fragment"),e.visibility&$T.COMPUTE&&r.push("compute");const n=`(${r.join(",")})`;DA.label=`bindingBuffer${e.id}_${e.name}_${n}`,DA.size=s,DA.usage=i;const a=this.device.createBuffer(DA);DA.reset(),t.buffer=a}}destroyUniformBuffer(e){this.get(e).buffer.destroy(),this.delete(e)}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())}hasFeature(e){return void 0!==eE[e]&&(e=eE[e]),this.device.features.has(e)}copyTextureToTexture(e,t,s=null,i=null,r=0,n=0){let a=0,o=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&&(a=i.x,o=i.y,l=i.z||0),OA.label="copyTextureToTexture_"+e.id+"_"+t.id;const f=this.device.createCommandEncoder(OA);OA.reset();const g=this.get(e).texture,y=this.get(t).texture;VA.texture=g,VA.mipLevel=r,VA.origin.x=h,VA.origin.y=u,VA.origin.z=c,GA.texture=y,GA.mipLevel=n,GA.origin.x=a,GA.origin.y=o,GA.origin.z=l,WA.width=d,WA.height=p,WA.depthOrArrayLayers=m,f.copyTextureToTexture(VA,GA,WA),VA.reset(),GA.reset(),WA.reset(),oE(this.device,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 At("WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.",r.format,n.format);if(!0===this._isRenderCameraDepthArray(t)){const a=this._finishArrayCameraBundleEncoders(i);return i.arrayCameraRenderStages.push({bundles:a,framebufferCopy:{texture:e,sourceGPU:r,destinationGPU:n,rectangle:{x:s.x,y:s.y,z:s.z,w:s.w},generateMipmaps:e.generateMipmaps}}),void this._createArrayCameraBundleEncoders(t,i)}let a;if(i.currentPass?(i.currentPass.end(),a=i.encoder):(OA.label="copyFramebufferToTexture_"+e.id,a=this.device.createCommandEncoder(OA),OA.reset()),this._copyFramebufferToTexture(a,e,r,n,s),i.currentPass){const{descriptor:e}=i;for(let t=0;t<e.colorAttachments.length;t++)e.colorAttachments[t].loadOp=eS;t.depth&&(e.depthStencilAttachment.depthLoadOp=eS),t.stencil&&(e.depthStencilAttachment.stencilLoadOp=eS),i.currentPass=a.beginRenderPass(e),this._resetRenderContextData(i),t.viewport&&this.updateViewport(t),t.scissor&&this.updateScissor(t)}else oE(this.device,a.finish())}_copyFramebufferToTexture(e,t,s,i,r,n=0,a=t.generateMipmaps){VA.texture=s,VA.origin.x=r.x,VA.origin.y=r.y,VA.origin.z=n,GA.texture=i,WA.width=r.z,WA.height=r.w,e.copyTextureToTexture(VA,GA,WA),VA.reset(),GA.reset(),WA.reset(),a&&this.textureUtils.generateMipmaps(t,e)}hasCompatibility(e){return void 0!==this._compatibility[e]?this._compatibility[e]:super.hasCompatibility(e)}async dispose(){if(await super.dispose(),this.bindingUtils.dispose(),this.textureUtils.dispose(),this.occludedResolveCache){for(const e of this.occludedResolveCache.values())e.destroy();this.occludedResolveCache.clear()}void 0===this.parameters.device&&null!==this.device&&this.device.destroy()}}class qA extends mn{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 XA extends mn{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 YA extends vv{constructor(){super(),this.addMaterial(jf,"MeshPhongMaterial"),this.addMaterial(Ry,"MeshStandardMaterial"),this.addMaterial(By,"MeshPhysicalMaterial"),this.addMaterial(Oy,"MeshToonMaterial"),this.addMaterial(Df,"MeshBasicMaterial"),this.addMaterial(Gf,"MeshLambertMaterial"),this.addMaterial(vf,"MeshNormalMaterial"),this.addMaterial(ky,"MeshMatcapMaterial"),this.addMaterial(cf,"LineBasicMaterial"),this.addMaterial(pf,"LineDashedMaterial"),this.addMaterial(Hy,"PointsMaterial"),this.addMaterial($y,"SpriteMaterial"),this.addMaterial(Ky,"ShadowMaterial"),this.addLight(rx,gn),this.addLight(qx,_n),this.addLight(iv,vn),this.addLight(Yx,mn),this.addLight(Hx,xn),this.addLight(Xx,Jr),this.addLight(Qx,Sn),this.addLight(Kx,qA),this.addLight(Jx,XA),this.addToneMapping(t_,1),this.addToneMapping(s_,2),this.addToneMapping(i_,3),this.addToneMapping(n_,4),this.addToneMapping(h_,6),this.addToneMapping(u_,7)}}class KA extends jv{constructor(e={}){let t;e.forceWebGL?t=UT:(t=HA,e.getFallback=()=>(Et("WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new UT(e)));super(new t(e),e),this.library=new YA,this.isWebGPURenderer=!0,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}}const QA={type:"change"},ZA={type:"start"},JA={type:"end"},eN=1e-6,tN=-1,sN=0,iN=1,rN=2,nN=3,aN=4,oN=new e.Vector2,lN=new e.Vector2,hN=new e.Vector3,uN=new e.Vector3,cN=new e.Vector3,dN=new e.Quaternion,pN=new e.Vector3,mN=new e.Vector3,fN=new e.Vector3,gN=new e.Vector3;class yN extends e.Controls{constructor(t,s=null){super(t,s),this.screen={left:0,top:0,width:0,height:0},this.rotateSpeed=1,this.zoomSpeed=1.2,this.panSpeed=.3,this.rollSpeed=1,this.noRotate=!1,this.noZoom=!1,this.noPan=!1,this.multiTouchRoll=!1,this.staticMoving=!1,this.dynamicDampingFactor=.2,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.keys=["KeyA","KeyS","KeyD"],this.mouseButtons={LEFT:e.MOUSE.ROTATE,MIDDLE:e.MOUSE.DOLLY,RIGHT:e.MOUSE.PAN},this.target=new e.Vector3,this.state=tN,this.keyState=tN,this._lastPosition=new e.Vector3,this._lastUp=new e.Vector3,this._lastZoom=1,this._touchZoomDistanceStart=0,this._touchZoomDistanceEnd=0,this._touchRollAngle=0,this._touchRollPointerIds="",this._lastAngle=0,this._lastRollAngle=0,this._eye=new e.Vector3,this._movePrev=new e.Vector2,this._moveCurr=new e.Vector2,this._lastAxis=new e.Vector3,this._zoomStart=new e.Vector2,this._zoomEnd=new e.Vector2,this._panStart=new e.Vector2,this._panEnd=new e.Vector2,this._pointers=[],this._pointerPositions={},this._onPointerMove=_N.bind(this),this._onPointerDown=bN.bind(this),this._onPointerUp=xN.bind(this),this._onPointerCancel=vN.bind(this),this._onContextMenu=NN.bind(this),this._onMouseWheel=AN.bind(this),this._onKeyDown=SN.bind(this),this._onKeyUp=TN.bind(this),this._onTouchStart=CN.bind(this),this._onTouchMove=RN.bind(this),this._onTouchEnd=PN.bind(this),this._onMouseDown=wN.bind(this),this._onMouseMove=MN.bind(this),this._onMouseUp=EN.bind(this),this._target0=this.target.clone(),this._position0=this.object.position.clone(),this._up0=this.object.up.clone(),this._zoom0=this.object.zoom,null!==s&&(this.connect(s),this.handleResize()),this.update()}connect(e){super.connect(e),window.addEventListener("keydown",this._onKeyDown),window.addEventListener("keyup",this._onKeyUp),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerCancel),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction="none"}disconnect(){window.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("keyup",this._onKeyUp),this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerCancel),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction=""}dispose(){this.disconnect()}handleResize(){const e=this.domElement.getBoundingClientRect(),t=this.domElement.ownerDocument.documentElement;this.screen.left=e.left+window.pageXOffset-t.clientLeft,this.screen.top=e.top+window.pageYOffset-t.clientTop,this.screen.width=e.width,this.screen.height=e.height}update(){if(this._eye.subVectors(this.object.position,this.target),this.noRotate||(this._rotateCamera(),!0===this.multiTouchRoll&&this._rollCamera()),this.noZoom||this._zoomCamera(),this.noPan||this._panCamera(),this.object.position.addVectors(this.target,this._eye),this.object.isPerspectiveCamera){this._checkDistances(),this.object.lookAt(this.target);const e=this._lastPosition.distanceToSquared(this.object.position)>eN,t=this._lastUp.distanceToSquared(this.object.up)>eN;(e||t)&&(this.dispatchEvent(QA),this._lastPosition.copy(this.object.position),this._lastUp.copy(this.object.up))}else if(this.object.isOrthographicCamera){this.object.lookAt(this.target);const e=this._lastPosition.distanceToSquared(this.object.position)>eN,t=this._lastUp.distanceToSquared(this.object.up)>eN,s=this._lastZoom!==this.object.zoom;(e||t||s)&&(this.dispatchEvent(QA),this._lastPosition.copy(this.object.position),this._lastUp.copy(this.object.up),this._lastZoom=this.object.zoom)}else console.warn("THREE.TrackballControls: Unsupported camera type.")}reset(){this.state=tN,this.keyState=tN,this.target.copy(this._target0),this.object.position.copy(this._position0),this.object.up.copy(this._up0),this.object.zoom=this._zoom0,this.object.updateProjectionMatrix(),this._eye.subVectors(this.object.position,this.target),this.object.lookAt(this.target),this.dispatchEvent(QA),this._lastPosition.copy(this.object.position),this._lastUp.copy(this.object.up),this._lastZoom=this.object.zoom}_panCamera(){if(lN.copy(this._panEnd).sub(this._panStart),lN.lengthSq()){if(this.object.isOrthographicCamera){const e=(this.object.right-this.object.left)/this.object.zoom/this.domElement.clientWidth,t=(this.object.top-this.object.bottom)/this.object.zoom/this.domElement.clientWidth;lN.x*=e,lN.y*=t}lN.multiplyScalar(this._eye.length()*this.panSpeed),uN.copy(this._eye).cross(this.object.up).setLength(lN.x),uN.add(hN.copy(this.object.up).setLength(lN.y)),this.object.position.add(uN),this.target.add(uN),this.staticMoving?this._panStart.copy(this._panEnd):this._panStart.add(lN.subVectors(this._panEnd,this._panStart).multiplyScalar(this.dynamicDampingFactor))}}_rotateCamera(){gN.set(this._moveCurr.x-this._movePrev.x,this._moveCurr.y-this._movePrev.y,0);let e=gN.length();e?(this._eye.copy(this.object.position).sub(this.target),pN.copy(this._eye).normalize(),mN.copy(this.object.up).normalize(),fN.crossVectors(mN,pN).normalize(),mN.setLength(this._moveCurr.y-this._movePrev.y),fN.setLength(this._moveCurr.x-this._movePrev.x),gN.copy(mN.add(fN)),cN.crossVectors(gN,this._eye).normalize(),e*=this.rotateSpeed,dN.setFromAxisAngle(cN,e),this._eye.applyQuaternion(dN),this.object.up.applyQuaternion(dN),this._lastAxis.copy(cN),this._lastAngle=e):!this.staticMoving&&this._lastAngle&&(this._lastAngle*=Math.sqrt(1-this.dynamicDampingFactor),this._eye.copy(this.object.position).sub(this.target),dN.setFromAxisAngle(this._lastAxis,this._lastAngle),this._eye.applyQuaternion(dN),this.object.up.applyQuaternion(dN)),this._movePrev.copy(this._moveCurr)}_rollCamera(){const e=this._getTouchRollAngle();if(e)this._lastRollAngle=e*this.rollSpeed;else{if(this.staticMoving||!this._lastRollAngle)return;this._lastRollAngle*=Math.sqrt(1-this.dynamicDampingFactor)}pN.copy(this._eye).normalize(),dN.setFromAxisAngle(pN,this._lastRollAngle),this.object.up.applyQuaternion(dN)}_getTouchRollAngle(){const e=this._pointers[0],t=this._pointers[1];if(void 0===t||"touch"!==e.pointerType||"touch"!==t.pointerType)return this._touchRollPointerIds="",0;const s=`${e.pointerId},${t.pointerId}`,i=this._pointerPositions[e.pointerId],r=this._pointerPositions[t.pointerId],n=Math.atan2(r.y-i.y,r.x-i.x);if(s!==this._touchRollPointerIds)return this._touchRollPointerIds=s,this._touchRollAngle=n,0;let a=n-this._touchRollAngle;return this._touchRollAngle=n,a>Math.PI?a-=2*Math.PI:a<-Math.PI&&(a+=2*Math.PI),a}_zoomCamera(){let t;this.state===aN?(t=this._touchZoomDistanceStart/this._touchZoomDistanceEnd,this._touchZoomDistanceStart=this._touchZoomDistanceEnd,this.object.isPerspectiveCamera?this._eye.multiplyScalar(t):this.object.isOrthographicCamera?(this.object.zoom=e.MathUtils.clamp(this.object.zoom/t,this.minZoom,this.maxZoom),this._lastZoom!==this.object.zoom&&this.object.updateProjectionMatrix()):console.warn("THREE.TrackballControls: Unsupported camera type")):(t=1+(this._zoomEnd.y-this._zoomStart.y)*this.zoomSpeed,1!==t&&t>0&&(this.object.isPerspectiveCamera?this._eye.multiplyScalar(t):this.object.isOrthographicCamera?(this.object.zoom=e.MathUtils.clamp(this.object.zoom/t,this.minZoom,this.maxZoom),this._lastZoom!==this.object.zoom&&this.object.updateProjectionMatrix()):console.warn("THREE.TrackballControls: Unsupported camera type")),this.staticMoving?this._zoomStart.copy(this._zoomEnd):this._zoomStart.y+=(this._zoomEnd.y-this._zoomStart.y)*this.dynamicDampingFactor)}_getMouseOnScreen(e,t){return oN.set((e-this.screen.left)/this.screen.width,(t-this.screen.top)/this.screen.height),oN}_getMouseOnCircle(e,t){return oN.set((e-.5*this.screen.width-this.screen.left)/(.5*this.screen.width),(this.screen.height+2*(this.screen.top-t))/this.screen.width),oN}_addPointer(e){this._pointers.push(e)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t].pointerId==e.pointerId)return void this._pointers.splice(t,1)}_trackPointer(t){let s=this._pointerPositions[t.pointerId];void 0===s&&(s=new e.Vector2,this._pointerPositions[t.pointerId]=s),s.set(t.pageX,t.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0].pointerId?this._pointers[1]:this._pointers[0];return this._pointerPositions[t.pointerId]}_checkDistances(){this.noZoom&&this.noPan||(this._eye.lengthSq()>this.maxDistance*this.maxDistance&&(this.object.position.addVectors(this.target,this._eye.setLength(this.maxDistance)),this._zoomStart.copy(this._zoomEnd)),this._eye.lengthSq()<this.minDistance*this.minDistance&&(this.object.position.addVectors(this.target,this._eye.setLength(this.minDistance)),this._zoomStart.copy(this._zoomEnd)))}}function bN(e){!1!==this.enabled&&(0===this._pointers.length&&(this.domElement.setPointerCapture(e.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp)),this._addPointer(e),"touch"===e.pointerType?this._onTouchStart(e):this._onMouseDown(e))}function _N(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchMove(e):this._onMouseMove(e))}function xN(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchEnd(e):this._onMouseUp(),this._removePointer(e),0===this._pointers.length&&(this.domElement.releasePointerCapture(e.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp)))}function vN(e){this._removePointer(e)}function TN(){!1!==this.enabled&&(this.keyState=tN,window.addEventListener("keydown",this._onKeyDown))}function SN(e){!1!==this.enabled&&(window.removeEventListener("keydown",this._onKeyDown),this.keyState===tN&&(e.code!==this.keys[sN]||this.noRotate?e.code!==this.keys[iN]||this.noZoom?e.code!==this.keys[rN]||this.noPan||(this.keyState=rN):this.keyState=iN:this.keyState=sN))}function wN(t){let s;switch(t.button){case 0:s=this.mouseButtons.LEFT;break;case 1:s=this.mouseButtons.MIDDLE;break;case 2:s=this.mouseButtons.RIGHT;break;default:s=-1}switch(s){case e.MOUSE.DOLLY:this.state=iN;break;case e.MOUSE.ROTATE:this.state=sN;break;case e.MOUSE.PAN:this.state=rN;break;default:this.state=tN}const i=this.keyState!==tN?this.keyState:this.state;i!==sN||this.noRotate?i!==iN||this.noZoom?i!==rN||this.noPan||(this._panStart.copy(this._getMouseOnScreen(t.pageX,t.pageY)),this._panEnd.copy(this._panStart)):(this._zoomStart.copy(this._getMouseOnScreen(t.pageX,t.pageY)),this._zoomEnd.copy(this._zoomStart)):(this._moveCurr.copy(this._getMouseOnCircle(t.pageX,t.pageY)),this._movePrev.copy(this._moveCurr)),this.dispatchEvent(ZA)}function MN(e){const t=this.keyState!==tN?this.keyState:this.state;t!==sN||this.noRotate?t!==iN||this.noZoom?t!==rN||this.noPan||this._panEnd.copy(this._getMouseOnScreen(e.pageX,e.pageY)):this._zoomEnd.copy(this._getMouseOnScreen(e.pageX,e.pageY)):this._moveCurr.copy(this._getMouseOnCircle(e.pageX,e.pageY))}function EN(){this.state=tN,this.dispatchEvent(JA)}function AN(e){if(!1!==this.enabled&&!0!==this.noZoom){switch(e.preventDefault(),e.deltaMode){case 2:this._zoomStart.y-=.025*e.deltaY;break;case 1:this._zoomStart.y-=.01*e.deltaY;break;default:this._zoomStart.y-=25e-5*e.deltaY}this.dispatchEvent(ZA),this.dispatchEvent(JA)}}function NN(e){!1!==this.enabled&&e.preventDefault()}function CN(e){if(this._trackPointer(e),1===this._pointers.length)this.state=nN,this._moveCurr.copy(this._getMouseOnCircle(this._pointers[0].pageX,this._pointers[0].pageY)),this._movePrev.copy(this._moveCurr);else{this.state=aN;const e=this._pointers[0].pageX-this._pointers[1].pageX,t=this._pointers[0].pageY-this._pointers[1].pageY;this._touchZoomDistanceEnd=this._touchZoomDistanceStart=Math.sqrt(e*e+t*t);const s=(this._pointers[0].pageX+this._pointers[1].pageX)/2,i=(this._pointers[0].pageY+this._pointers[1].pageY)/2;this._panStart.copy(this._getMouseOnScreen(s,i)),this._panEnd.copy(this._panStart)}this.dispatchEvent(ZA)}function RN(e){if(this._trackPointer(e),1===this._pointers.length)this._moveCurr.copy(this._getMouseOnCircle(e.pageX,e.pageY));else{const t=this._getSecondPointerPosition(e),s=e.pageX-t.x,i=e.pageY-t.y;this._touchZoomDistanceEnd=Math.sqrt(s*s+i*i);const r=(e.pageX+t.x)/2,n=(e.pageY+t.y)/2;this._panEnd.copy(this._getMouseOnScreen(r,n))}}function PN(e){switch(this._pointers.length){case 0:this.state=tN;break;case 1:this.state=nN,this._moveCurr.copy(this._getMouseOnCircle(e.pageX,e.pageY)),this._movePrev.copy(this._moveCurr);break;case 2:this.state=aN;for(let t=0;t<this._pointers.length;t++)if(this._pointers[t].pointerId!==e.pointerId){const e=this._pointerPositions[this._pointers[t].pointerId];this._moveCurr.copy(this._getMouseOnCircle(e.x,e.y)),this._movePrev.copy(this._moveCurr);break}}this.dispatchEvent(JA)}const BN={type:"change"},FN={type:"start"},LN={type:"end"},DN=new e.Ray,ON=new e.Plane,IN=Math.cos(70*e.MathUtils.DEG2RAD),UN=new e.Vector3,kN=2*Math.PI,zN=-1,VN=0,GN=1,$N=2,jN=3,WN=4,HN=5,qN=6,XN=1e-6;class YN extends e.Controls{constructor(t,s=null){super(t,s),this.state=zN,this.target=new e.Vector3,this.cursor=new e.Vector3,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:e.MOUSE.ROTATE,MIDDLE:e.MOUSE.DOLLY,RIGHT:e.MOUSE.PAN},this.touches={ONE:e.TOUCH.ROTATE,TWO:e.TOUCH.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._cursorStyle="auto",this._domElementKeyEvents=null,this._lastPosition=new e.Vector3,this._lastQuaternion=new e.Quaternion,this._lastTargetPosition=new e.Vector3,this._quat=(new e.Quaternion).setFromUnitVectors(t.up,new e.Vector3(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new e.Spherical,this._sphericalDelta=new e.Spherical,this._scale=1,this._panOffset=new e.Vector3,this._rotateStart=new e.Vector2,this._rotateEnd=new e.Vector2,this._rotateDelta=new e.Vector2,this._panStart=new e.Vector2,this._panEnd=new e.Vector2,this._panDelta=new e.Vector2,this._dollyStart=new e.Vector2,this._dollyEnd=new e.Vector2,this._dollyDelta=new e.Vector2,this._dollyDirection=new e.Vector3,this._mouse=new e.Vector2,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=QN.bind(this),this._onPointerDown=KN.bind(this),this._onPointerUp=ZN.bind(this),this._onContextMenu=nC.bind(this),this._onMouseWheel=tC.bind(this),this._onKeyDown=sC.bind(this),this._onTouchStart=iC.bind(this),this._onTouchMove=rC.bind(this),this._onMouseDown=JN.bind(this),this._onMouseMove=eC.bind(this),this._interceptControlDown=aC.bind(this),this._interceptControlUp=oC.bind(this),null!==this.domElement&&this.connect(this.domElement),this.update()}set cursorStyle(e){this._cursorStyle=e,this.domElement.style.cursor="grab"===e?"grab":"auto"}get cursorStyle(){return this._cursorStyle}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1});this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.state=zN,this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents();const e=this.domElement.getRootNode();e.removeEventListener("keydown",this._interceptControlDown,{capture:!0}),e.removeEventListener("keyup",this._interceptControlUp,{capture:!0}),this._controlActive=!1,this._pointers.length=0,this._pointerPositions={},this.domElement.style.touchAction="",this.domElement.style.cursor="auto"}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){null!==this._domElementKeyEvents&&(this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null)}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(BN),this.update(),this.state=zN}pan(e,t){this._pan(e,t),this.update()}dollyIn(e){this._dollyIn(e),this.update()}dollyOut(e){this._dollyOut(e),this.update()}rotateLeft(e){this._rotateLeft(e),this.update()}rotateUp(e){this._rotateUp(e),this.update()}update(t=null){const s=this.object.position;UN.copy(s).sub(this.target),UN.applyQuaternion(this._quat),this._spherical.setFromVector3(UN),this.autoRotate&&this.state===zN&&this._rotateLeft(this._getAutoRotationAngle(t)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let i=this.minAzimuthAngle,r=this.maxAzimuthAngle;isFinite(i)&&isFinite(r)&&(i<-Math.PI?i+=kN:i>Math.PI&&(i-=kN),r<-Math.PI?r+=kN:r>Math.PI&&(r-=kN),this._spherical.theta=i<=r?Math.max(i,Math.min(r,this._spherical.theta)):this._spherical.theta>(i+r)/2?Math.max(i,this._spherical.theta):Math.min(r,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),!0===this.enableDamping?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let n=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const e=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),n=e!=this._spherical.radius}if(UN.setFromSpherical(this._spherical),UN.applyQuaternion(this._quatInverse),s.copy(this.target).add(UN),this.object.lookAt(this.target),!0===this.enableDamping?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let t=null;if(this.object.isPerspectiveCamera){const e=UN.length();t=this._clampDistance(e*this._scale);const s=e-t;this.object.position.addScaledVector(this._dollyDirection,s),this.object.updateMatrixWorld(),n=!!s}else if(this.object.isOrthographicCamera){const s=new e.Vector3(this._mouse.x,this._mouse.y,0);s.unproject(this.object);const i=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),n=i!==this.object.zoom;const r=new e.Vector3(this._mouse.x,this._mouse.y,0);r.unproject(this.object),this.object.position.sub(r).add(s),this.object.updateMatrixWorld(),t=UN.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;null!==t&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(t).add(this.object.position):(DN.origin.copy(this.object.position),DN.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(DN.direction))<IN?this.object.lookAt(this.target):(ON.setFromNormalAndCoplanarPoint(this.object.up,this.target),DN.intersectPlane(ON,this.target))))}else if(this.object.isOrthographicCamera){const e=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),e!==this.object.zoom&&(this.object.updateProjectionMatrix(),n=!0)}return this._scale=1,this._performCursorZoom=!1,!!(n||this._lastPosition.distanceToSquared(this.object.position)>XN||8*(1-this._lastQuaternion.dot(this.object.quaternion))>XN||this._lastTargetPosition.distanceToSquared(this.target)>XN)&&(this.dispatchEvent(BN),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0)}_getAutoRotationAngle(e){return null!==e?kN/60*this.autoRotateSpeed*e:kN/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(.01*e);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){UN.setFromMatrixColumn(t,0),UN.multiplyScalar(-e),this._panOffset.add(UN)}_panUp(e,t){!0===this.screenSpacePanning?UN.setFromMatrixColumn(t,1):(UN.setFromMatrixColumn(t,0),UN.crossVectors(this.object.up,UN)),UN.multiplyScalar(e),this._panOffset.add(UN)}_pan(e,t){const s=this.domElement;if(this.object.isPerspectiveCamera){const i=this.object.position;UN.copy(i).sub(this.target);let r=UN.length();r*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*r/s.clientHeight,this.object.matrix),this._panUp(2*t*r/s.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/s.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/s.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;const s=this.domElement.getBoundingClientRect(),i=e-s.left,r=t-s.top,n=s.width,a=s.height;this._mouse.x=i/n*2-1,this._mouse.y=-r/a*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(kN*this._rotateDelta.x/t.clientHeight),this._rotateUp(kN*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(kN*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-kN*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(kN*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-kN*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(1===this._pointers.length)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),s=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._rotateStart.set(s,i)}}_handleTouchStartPan(e){if(1===this._pointers.length)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),s=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panStart.set(s,i)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),s=e.pageX-t.x,i=e.pageY-t.y,r=Math.sqrt(s*s+i*i);this._dollyStart.set(0,r)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(1==this._pointers.length)this._rotateEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),s=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._rotateEnd.set(s,i)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(kN*this._rotateDelta.x/t.clientHeight),this._rotateUp(kN*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(1===this._pointers.length)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),s=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panEnd.set(s,i)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),s=e.pageX-t.x,i=e.pageY-t.y,r=Math.sqrt(s*s+i*i);this._dollyEnd.set(0,r),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const n=.5*(e.pageX+t.x),a=.5*(e.pageY+t.y);this._updateZoomParameters(n,a)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return void this._pointers.splice(t,1)}_isTrackingPointer(e){for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return!0;return!1}_trackPointer(t){let s=this._pointerPositions[t.pointerId];void 0===s&&(s=new e.Vector2,this._pointerPositions[t.pointerId]=s),s.set(t.pageX,t.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){const t=e.deltaMode,s={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:s.deltaY*=16;break;case 2:s.deltaY*=100}return e.ctrlKey&&!this._controlActive&&(s.deltaY*=10),s}}function KN(e){!1!==this.enabled&&(0===this._pointers.length&&(this.domElement.setPointerCapture(e.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp)),this._isTrackingPointer(e)||(this._addPointer(e),"touch"===e.pointerType?this._onTouchStart(e):this._onMouseDown(e),"grab"===this._cursorStyle&&(this.domElement.style.cursor="grabbing")))}function QN(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchMove(e):this._onMouseMove(e))}function ZN(e){switch(this._removePointer(e),this._pointers.length){case 0:this.domElement.releasePointerCapture(e.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(LN),this.state=zN,"grab"===this._cursorStyle&&(this.domElement.style.cursor="grab");break;case 1:const t=this._pointers[0],s=this._pointerPositions[t];this._onTouchStart({pointerId:t,pageX:s.x,pageY:s.y})}}function JN(t){let s;switch(t.button){case 0:s=this.mouseButtons.LEFT;break;case 1:s=this.mouseButtons.MIDDLE;break;case 2:s=this.mouseButtons.RIGHT;break;default:s=-1}switch(s){case e.MOUSE.DOLLY:if(!1===this.enableZoom)return;this._handleMouseDownDolly(t),this.state=GN;break;case e.MOUSE.ROTATE:if(t.ctrlKey||t.metaKey||t.shiftKey){if(!1===this.enablePan)return;this._handleMouseDownPan(t),this.state=$N}else{if(!1===this.enableRotate)return;this._handleMouseDownRotate(t),this.state=VN}break;case e.MOUSE.PAN:if(t.ctrlKey||t.metaKey||t.shiftKey){if(!1===this.enableRotate)return;this._handleMouseDownRotate(t),this.state=VN}else{if(!1===this.enablePan)return;this._handleMouseDownPan(t),this.state=$N}break;default:this.state=zN}this.state!==zN&&this.dispatchEvent(FN)}function eC(e){switch(this.state){case VN:if(!1===this.enableRotate)return;this._handleMouseMoveRotate(e);break;case GN:if(!1===this.enableZoom)return;this._handleMouseMoveDolly(e);break;case $N:if(!1===this.enablePan)return;this._handleMouseMovePan(e)}}function tC(e){!1!==this.enabled&&!1!==this.enableZoom&&this.state===zN&&(e.preventDefault(),this.dispatchEvent(FN),this._handleMouseWheel(this._customWheelEvent(e)),this.dispatchEvent(LN))}function sC(e){!1!==this.enabled&&this._handleKeyDown(e)}function iC(t){switch(this._trackPointer(t),this._pointers.length){case 1:switch(this.touches.ONE){case e.TOUCH.ROTATE:if(!1===this.enableRotate)return;this._handleTouchStartRotate(t),this.state=jN;break;case e.TOUCH.PAN:if(!1===this.enablePan)return;this._handleTouchStartPan(t),this.state=WN;break;default:this.state=zN}break;case 2:switch(this.touches.TWO){case e.TOUCH.DOLLY_PAN:if(!1===this.enableZoom&&!1===this.enablePan)return;this._handleTouchStartDollyPan(t),this.state=HN;break;case e.TOUCH.DOLLY_ROTATE:if(!1===this.enableZoom&&!1===this.enableRotate)return;this._handleTouchStartDollyRotate(t),this.state=qN;break;default:this.state=zN}break;default:this.state=zN}this.state!==zN&&this.dispatchEvent(FN)}function rC(e){switch(this._trackPointer(e),this.state){case jN:if(!1===this.enableRotate)return;this._handleTouchMoveRotate(e),this.update();break;case WN:if(!1===this.enablePan)return;this._handleTouchMovePan(e),this.update();break;case HN:if(!1===this.enableZoom&&!1===this.enablePan)return;this._handleTouchMoveDollyPan(e),this.update();break;case qN:if(!1===this.enableZoom&&!1===this.enableRotate)return;this._handleTouchMoveDollyRotate(e),this.update();break;default:this.state=zN}}function nC(e){!1!==this.enabled&&e.preventDefault()}function aC(e){if("Control"===e.key){this._controlActive=!0;this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}}function oC(e){if("Control"===e.key){this._controlActive=!1;this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}}const lC={type:"change"},hC=1e-6,uC=new e.Quaternion;class cC extends e.Controls{constructor(t,s=null){super(t,s),this.movementSpeed=1,this.rollSpeed=.005,this.dragToLook=!1,this.autoForward=!1,this._moveState={up:0,down:0,left:0,right:0,forward:0,back:0,pitchUp:0,pitchDown:0,yawLeft:0,yawRight:0,rollLeft:0,rollRight:0},this._moveVector=new e.Vector3(0,0,0),this._rotationVector=new e.Vector3(0,0,0),this._lastQuaternion=new e.Quaternion,this._lastPosition=new e.Vector3,this._status=0,this._onKeyDown=dC.bind(this),this._onKeyUp=pC.bind(this),this._onPointerMove=fC.bind(this),this._onPointerDown=mC.bind(this),this._onPointerUp=gC.bind(this),this._onPointerCancel=yC.bind(this),this._onContextMenu=bC.bind(this),null!==s&&this.connect(s)}connect(e){super.connect(e),window.addEventListener("keydown",this._onKeyDown),window.addEventListener("keyup",this._onKeyUp),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointerup",this._onPointerUp),this.domElement.addEventListener("pointercancel",this._onPointerCancel),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction="none"}disconnect(){window.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("keyup",this._onKeyUp),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerCancel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction=""}dispose(){this.disconnect()}update(e){if(!1===this.enabled)return;const t=this.object,s=e*this.movementSpeed,i=e*this.rollSpeed;t.translateX(this._moveVector.x*s),t.translateY(this._moveVector.y*s),t.translateZ(this._moveVector.z*s),uC.set(this._rotationVector.x*i,this._rotationVector.y*i,this._rotationVector.z*i,1).normalize(),t.quaternion.multiply(uC),(this._lastPosition.distanceToSquared(t.position)>hC||8*(1-this._lastQuaternion.dot(t.quaternion))>hC)&&(this.dispatchEvent(lC),this._lastQuaternion.copy(t.quaternion),this._lastPosition.copy(t.position))}_updateMovementVector(){const e=this._moveState.forward||this.autoForward&&!this._moveState.back?1:0;this._moveVector.x=-this._moveState.left+this._moveState.right,this._moveVector.y=-this._moveState.down+this._moveState.up,this._moveVector.z=-e+this._moveState.back}_updateRotationVector(){this._rotationVector.x=-this._moveState.pitchDown+this._moveState.pitchUp,this._rotationVector.y=-this._moveState.yawRight+this._moveState.yawLeft,this._rotationVector.z=-this._moveState.rollRight+this._moveState.rollLeft}_getContainerDimensions(){return this.domElement!=document?{size:[this.domElement.offsetWidth,this.domElement.offsetHeight],offset:[this.domElement.offsetLeft,this.domElement.offsetTop]}:{size:[window.innerWidth,window.innerHeight],offset:[0,0]}}}function dC(e){if(!e.altKey&&!1!==this.enabled){switch(e.code){case"ShiftLeft":case"ShiftRight":this.movementSpeedMultiplier=.1;break;case"KeyW":this._moveState.forward=1;break;case"KeyS":this._moveState.back=1;break;case"KeyA":this._moveState.left=1;break;case"KeyD":this._moveState.right=1;break;case"KeyR":this._moveState.up=1;break;case"KeyF":this._moveState.down=1;break;case"ArrowUp":this._moveState.pitchUp=1;break;case"ArrowDown":this._moveState.pitchDown=1;break;case"ArrowLeft":this._moveState.yawLeft=1;break;case"ArrowRight":this._moveState.yawRight=1;break;case"KeyQ":this._moveState.rollLeft=1;break;case"KeyE":this._moveState.rollRight=1}this._updateMovementVector(),this._updateRotationVector()}}function pC(e){if(!1!==this.enabled){switch(e.code){case"ShiftLeft":case"ShiftRight":this.movementSpeedMultiplier=1;break;case"KeyW":this._moveState.forward=0;break;case"KeyS":this._moveState.back=0;break;case"KeyA":this._moveState.left=0;break;case"KeyD":this._moveState.right=0;break;case"KeyR":this._moveState.up=0;break;case"KeyF":this._moveState.down=0;break;case"ArrowUp":this._moveState.pitchUp=0;break;case"ArrowDown":this._moveState.pitchDown=0;break;case"ArrowLeft":this._moveState.yawLeft=0;break;case"ArrowRight":this._moveState.yawRight=0;break;case"KeyQ":this._moveState.rollLeft=0;break;case"KeyE":this._moveState.rollRight=0}this._updateMovementVector(),this._updateRotationVector()}}function mC(e){if(!1!==this.enabled)if(this.dragToLook)this._status++;else{switch(e.button){case 0:this._moveState.forward=1;break;case 2:this._moveState.back=1}this._updateMovementVector()}}function fC(e){if(!1!==this.enabled&&(!this.dragToLook||this._status>0)){const t=this._getContainerDimensions(),s=t.size[0]/2,i=t.size[1]/2;this._moveState.yawLeft=-(e.pageX-t.offset[0]-s)/s,this._moveState.pitchDown=(e.pageY-t.offset[1]-i)/i,this._updateRotationVector()}}function gC(e){if(!1!==this.enabled){if(this.dragToLook)this._status--,this._moveState.yawLeft=this._moveState.pitchDown=0;else{switch(e.button){case 0:this._moveState.forward=0;break;case 2:this._moveState.back=0}this._updateMovementVector()}this._updateRotationVector()}}function yC(){!1!==this.enabled&&(this.dragToLook?(this._status=0,this._moveState.yawLeft=this._moveState.pitchDown=0):(this._moveState.forward=0,this._moveState.back=0,this._updateMovementVector()),this._updateRotationVector())}function bC(e){!1!==this.enabled&&e.preventDefault()}const _C={name:"CopyShader",uniforms:{tDiffuse:{value:null},opacity:{value:1}},vertexShader:"\n\n\t\tvarying vec2 vUv;\n\n\t\tvoid main() {\n\n\t\t\tvUv = uv;\n\t\t\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\n\t\t}",fragmentShader:"\n\n\t\tuniform float opacity;\n\n\t\tuniform sampler2D tDiffuse;\n\n\t\tvarying vec2 vUv;\n\n\t\tvoid main() {\n\n\t\t\tvec4 texel = texture2D( tDiffuse, vUv );\n\t\t\tgl_FragColor = opacity * texel;\n\n\n\t\t}"};class xC{constructor(){this.isPass=!0,this.enabled=!0,this.needsSwap=!0,this.clear=!1,this.renderToScreen=!1}setSize(){}render(){console.error("THREE.Pass: .render() must be implemented in derived pass.")}dispose(){}}const vC=new e.OrthographicCamera(-1,1,1,-1,0,1);class TC extends e.BufferGeometry{constructor(){super(),this.setAttribute("position",new e.Float32BufferAttribute([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new e.Float32BufferAttribute([0,2,0,0,2,0],2))}}const SC=new TC;class wC{constructor(t){this._mesh=new e.Mesh(SC,t)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,vC)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}class MC extends xC{constructor(t,s="tDiffuse"){super(),this.textureID=s,this.uniforms=null,this.material=null,t instanceof e.ShaderMaterial?(this.uniforms=t.uniforms,this.material=t):t&&(this.uniforms=e.UniformsUtils.clone(t.uniforms),this.material=new e.ShaderMaterial({name:void 0!==t.name?t.name:"unspecified",defines:Object.assign({},t.defines),uniforms:this.uniforms,vertexShader:t.vertexShader,fragmentShader:t.fragmentShader})),this._fsQuad=new wC(this.material)}render(e,t,s){this.uniforms[this.textureID]&&(this.uniforms[this.textureID].value=s.texture),this._fsQuad.material=this.material,this.renderToScreen?(e.setRenderTarget(null),this._fsQuad.render(e)):(e.setRenderTarget(t),this.clear&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),this._fsQuad.render(e))}dispose(){this.material.dispose(),this._fsQuad.dispose()}}class EC extends xC{constructor(e,t){super(),this.scene=e,this.camera=t,this.clear=!0,this.needsSwap=!1,this.inverse=!1}render(e,t,s){const i=e.getContext(),r=e.state;let n,a;r.buffers.color.setMask(!1),r.buffers.depth.setMask(!1),r.buffers.color.setLocked(!0),r.buffers.depth.setLocked(!0),this.inverse?(n=0,a=1):(n=1,a=0),r.buffers.stencil.setTest(!0),r.buffers.stencil.setOp(i.REPLACE,i.REPLACE,i.REPLACE),r.buffers.stencil.setFunc(i.ALWAYS,n,4294967295),r.buffers.stencil.setClear(a),r.buffers.stencil.setLocked(!0),e.setRenderTarget(s),this.clear&&e.clear(),e.render(this.scene,this.camera),e.setRenderTarget(t),this.clear&&e.clear(),e.render(this.scene,this.camera),r.buffers.color.setLocked(!1),r.buffers.depth.setLocked(!1),r.buffers.color.setMask(!0),r.buffers.depth.setMask(!0),r.buffers.stencil.setLocked(!1),r.buffers.stencil.setFunc(i.EQUAL,1,4294967295),r.buffers.stencil.setOp(i.KEEP,i.KEEP,i.KEEP),r.buffers.stencil.setLocked(!0)}}class AC extends xC{constructor(){super(),this.needsSwap=!1}render(e){e.state.buffers.stencil.setLocked(!1),e.state.buffers.stencil.setTest(!1)}}class NC{constructor(t,s){if(this.renderer=t,this._pixelRatio=t.getPixelRatio(),void 0===s){const i=t.getSize(new e.Vector2);this._width=i.width,this._height=i.height,(s=new e.WebGLRenderTarget(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:e.HalfFloatType})).texture.name="EffectComposer.rt1"}else this._width=s.width,this._height=s.height;this.renderTarget1=s,this.renderTarget2=s.clone(),this.renderTarget2.texture.name="EffectComposer.rt2",this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2,this.renderToScreen=!0,this.passes=[],this.copyPass=new MC(_C),this.copyPass.material.blending=e.NoBlending,this.timer=new e.Timer}swapBuffers(){const e=this.readBuffer;this.readBuffer=this.writeBuffer,this.writeBuffer=e}addPass(e){this.passes.push(e),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}insertPass(e,t){this.passes.splice(t,0,e),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}removePass(e){const t=this.passes.indexOf(e);-1!==t&&this.passes.splice(t,1)}isLastEnabledPass(e){for(let t=e+1;t<this.passes.length;t++)if(this.passes[t].enabled)return!1;return!0}render(e){this.timer.update(),void 0===e&&(e=this.timer.getDelta());const t=this.renderer.getRenderTarget();let s=!1;for(let t=0,i=this.passes.length;t<i;t++){const i=this.passes[t];if(!1!==i.enabled){if(i.renderToScreen=this.renderToScreen&&this.isLastEnabledPass(t),i.render(this.renderer,this.writeBuffer,this.readBuffer,e,s),i.needsSwap){if(s){const t=this.renderer.getContext(),s=this.renderer.state.buffers.stencil;s.setFunc(t.NOTEQUAL,1,4294967295),this.copyPass.render(this.renderer,this.writeBuffer,this.readBuffer,e),s.setFunc(t.EQUAL,1,4294967295)}this.swapBuffers()}void 0!==EC&&(i instanceof EC?s=!0:i instanceof AC&&(s=!1))}}this.renderer.setRenderTarget(t)}reset(t){if(void 0===t){const s=this.renderer.getSize(new e.Vector2);this._pixelRatio=this.renderer.getPixelRatio(),this._width=s.width,this._height=s.height,(t=this.renderTarget1.clone()).setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}this.renderTarget1.dispose(),this.renderTarget2.dispose(),this.renderTarget1=t,this.renderTarget2=t.clone(),this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2}setSize(e,t){this._width=e,this._height=t;const s=this._width*this._pixelRatio,i=this._height*this._pixelRatio;this.renderTarget1.setSize(s,i),this.renderTarget2.setSize(s,i);for(let e=0;e<this.passes.length;e++)this.passes[e].setSize(s,i)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget1.dispose(),this.renderTarget2.dispose(),this.copyPass.dispose()}}class CC extends xC{constructor(t,s,i=null,r=null,n=null){super(),this.scene=t,this.camera=s,this.overrideMaterial=i,this.clearColor=r,this.clearAlpha=n,this.clear=!0,this.clearDepth=!1,this.needsSwap=!1,this.isRenderPass=!0,this._oldClearColor=new e.Color}render(e,t,s){const i=e.autoClear;let r,n;e.autoClear=!1,null!==this.overrideMaterial&&(n=this.scene.overrideMaterial,this.scene.overrideMaterial=this.overrideMaterial),null!==this.clearColor&&(e.getClearColor(this._oldClearColor),e.setClearColor(this.clearColor,e.getClearAlpha())),null!==this.clearAlpha&&(r=e.getClearAlpha(),e.setClearAlpha(this.clearAlpha)),1==this.clearDepth&&e.clearDepth(),e.setRenderTarget(this.renderToScreen?null:s),!0===this.clear&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),e.render(this.scene,this.camera),null!==this.clearColor&&e.setClearColor(this._oldClearColor),null!==this.clearAlpha&&e.setClearAlpha(r),null!==this.overrideMaterial&&(this.scene.overrideMaterial=n),e.autoClear=i}}function RC(){return RC=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var s=arguments[t];for(var i in s)({}).hasOwnProperty.call(s,i)&&(e[i]=s[i])}return e},RC.apply(null,arguments)}function PC(e,t){return PC=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},PC(e,t)}function BC(e){return BC=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},BC(e)}function FC(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(FC=function(){return!!e})()}function LC(e){var t="function"==typeof Map?new Map:void 0;return LC=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,s)}function s(){return function(e,t,s){if(FC())return Reflect.construct.apply(null,arguments);var i=[null];i.push.apply(i,t);var r=new(e.bind.apply(e,i));return s&&PC(r,s.prototype),r}(e,arguments,BC(this).constructor)}return s.prototype=Object.create(e.prototype,{constructor:{value:s,enumerable:!1,writable:!0,configurable:!0}}),PC(s,e)},LC(e)}var DC={1:"Passed invalid arguments to hsl, please pass multiple numbers e.g. hsl(360, 0.75, 0.4) or an object e.g. rgb({ hue: 255, saturation: 0.4, lightness: 0.75 }).\n\n",2:"Passed invalid arguments to hsla, please pass multiple numbers e.g. hsla(360, 0.75, 0.4, 0.7) or an object e.g. rgb({ hue: 255, saturation: 0.4, lightness: 0.75, alpha: 0.7 }).\n\n",3:"Passed an incorrect argument to a color function, please pass a string representation of a color.\n\n",4:"Couldn't generate valid rgb string from %s, it returned %s.\n\n",5:"Couldn't parse the color string. Please provide the color as a string in hex, rgb, rgba, hsl or hsla notation.\n\n",6:"Passed invalid arguments to rgb, please pass multiple numbers e.g. rgb(255, 205, 100) or an object e.g. rgb({ red: 255, green: 205, blue: 100 }).\n\n",7:"Passed invalid arguments to rgba, please pass multiple numbers e.g. rgb(255, 205, 100, 0.75) or an object e.g. rgb({ red: 255, green: 205, blue: 100, alpha: 0.75 }).\n\n",8:"Passed invalid argument to toColorString, please pass a RgbColor, RgbaColor, HslColor or HslaColor object.\n\n",9:"Please provide a number of steps to the modularScale helper.\n\n",10:"Please pass a number or one of the predefined scales to the modularScale helper as the ratio.\n\n",11:'Invalid value passed as base to modularScale, expected number or em string but got "%s"\n\n',12:'Expected a string ending in "px" or a number passed as the first argument to %s(), got "%s" instead.\n\n',13:'Expected a string ending in "px" or a number passed as the second argument to %s(), got "%s" instead.\n\n',14:'Passed invalid pixel value ("%s") to %s(), please pass a value like "12px" or 12.\n\n',15:'Passed invalid base value ("%s") to %s(), please pass a value like "12px" or 12.\n\n',16:"You must provide a template to this method.\n\n",17:"You passed an unsupported selector state to this method.\n\n",18:"minScreen and maxScreen must be provided as stringified numbers with the same units.\n\n",19:"fromSize and toSize must be provided as stringified numbers with the same units.\n\n",20:"expects either an array of objects or a single object with the properties prop, fromSize, and toSize.\n\n",21:"expects the objects in the first argument array to have the properties `prop`, `fromSize`, and `toSize`.\n\n",22:"expects the first argument object to have the properties `prop`, `fromSize`, and `toSize`.\n\n",23:"fontFace expects a name of a font-family.\n\n",24:"fontFace expects either the path to the font file(s) or a name of a local copy.\n\n",25:"fontFace expects localFonts to be an array.\n\n",26:"fontFace expects fileFormats to be an array.\n\n",27:"radialGradient requries at least 2 color-stops to properly render.\n\n",28:"Please supply a filename to retinaImage() as the first argument.\n\n",29:"Passed invalid argument to triangle, please pass correct pointingDirection e.g. 'right'.\n\n",30:"Passed an invalid value to `height` or `width`. Please provide a pixel based unit.\n\n",31:"The animation shorthand only takes 8 arguments. See the specification for more information: http://mdn.io/animation\n\n",32:"To pass multiple animations please supply them in arrays, e.g. animation(['rotate', '2s'], ['move', '1s'])\nTo pass a single animation please supply them in simple values, e.g. animation('rotate', '2s')\n\n",33:"The animation shorthand arrays can only have 8 elements. See the specification for more information: http://mdn.io/animation\n\n",34:"borderRadius expects a radius value as a string or number as the second argument.\n\n",35:'borderRadius expects one of "top", "bottom", "left" or "right" as the first argument.\n\n',36:"Property must be a string value.\n\n",37:"Syntax Error at %s.\n\n",38:"Formula contains a function that needs parentheses at %s.\n\n",39:"Formula is missing closing parenthesis at %s.\n\n",40:"Formula has too many closing parentheses at %s.\n\n",41:"All values in a formula must have the same unit or be unitless.\n\n",42:"Please provide a number of steps to the modularScale helper.\n\n",43:"Please pass a number or one of the predefined scales to the modularScale helper as the ratio.\n\n",44:"Invalid value passed as base to modularScale, expected number or em/rem string but got %s.\n\n",45:"Passed invalid argument to hslToColorString, please pass a HslColor or HslaColor object.\n\n",46:"Passed invalid argument to rgbToColorString, please pass a RgbColor or RgbaColor object.\n\n",47:"minScreen and maxScreen must be provided as stringified numbers with the same units.\n\n",48:"fromSize and toSize must be provided as stringified numbers with the same units.\n\n",49:"Expects either an array of objects or a single object with the properties prop, fromSize, and toSize.\n\n",50:"Expects the objects in the first argument array to have the properties prop, fromSize, and toSize.\n\n",51:"Expects the first argument object to have the properties prop, fromSize, and toSize.\n\n",52:"fontFace expects either the path to the font file(s) or a name of a local copy.\n\n",53:"fontFace expects localFonts to be an array.\n\n",54:"fontFace expects fileFormats to be an array.\n\n",55:"fontFace expects a name of a font-family.\n\n",56:"linearGradient requries at least 2 color-stops to properly render.\n\n",57:"radialGradient requries at least 2 color-stops to properly render.\n\n",58:"Please supply a filename to retinaImage() as the first argument.\n\n",59:"Passed invalid argument to triangle, please pass correct pointingDirection e.g. 'right'.\n\n",60:"Passed an invalid value to `height` or `width`. Please provide a pixel based unit.\n\n",61:"Property must be a string value.\n\n",62:"borderRadius expects a radius value as a string or number as the second argument.\n\n",63:'borderRadius expects one of "top", "bottom", "left" or "right" as the first argument.\n\n',64:"The animation shorthand only takes 8 arguments. See the specification for more information: http://mdn.io/animation.\n\n",65:"To pass multiple animations please supply them in arrays, e.g. animation(['rotate', '2s'], ['move', '1s'])\\nTo pass a single animation please supply them in simple values, e.g. animation('rotate', '2s').\n\n",66:"The animation shorthand arrays can only have 8 elements. See the specification for more information: http://mdn.io/animation.\n\n",67:"You must provide a template to this method.\n\n",68:"You passed an unsupported selector state to this method.\n\n",69:'Expected a string ending in "px" or a number passed as the first argument to %s(), got %s instead.\n\n',70:'Expected a string ending in "px" or a number passed as the second argument to %s(), got %s instead.\n\n',71:'Passed invalid pixel value %s to %s(), please pass a value like "12px" or 12.\n\n',72:'Passed invalid base value %s to %s(), please pass a value like "12px" or 12.\n\n',73:"Please provide a valid CSS variable.\n\n",74:"CSS variable not found and no default was provided.\n\n",75:"important requires a valid style object, got a %s instead.\n\n",76:"fromSize and toSize must be provided as stringified numbers with the same units as minScreen and maxScreen.\n\n",77:'remToPx expects a value in "rem" but you provided it in "%s".\n\n',78:'base must be set in "px" or "%" but you set it in "%s".\n'};function OC(){for(var e=arguments.length,t=new Array(e),s=0;s<e;s++)t[s]=arguments[s];var i,r=t[0],n=[];for(i=1;i<t.length;i+=1)n.push(t[i]);return n.forEach(function(e){r=r.replace(/%[a-z]/,e)}),r}var IC=function(e){function t(t){var s;if("production"===process.env.NODE_ENV)s=e.call(this,"An error occurred. See https://github.com/styled-components/polished/blob/main/src/internalHelpers/errors.md#"+t+" for more information.")||this;else{for(var i=arguments.length,r=new Array(i>1?i-1:0),n=1;n<i;n++)r[n-1]=arguments[n];s=e.call(this,OC.apply(void 0,[DC[t]].concat(r)))||this}return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(s)}return function(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,PC(e,t)}(t,e),t}(LC(Error));function UC(e){return Math.round(255*e)}function kC(e,t,s){return UC(e)+","+UC(t)+","+UC(s)}function zC(e,t,s,i){if(void 0===i&&(i=kC),0===t)return i(s,s,s);var r=(e%360+360)%360/60,n=(1-Math.abs(2*s-1))*t,a=n*(1-Math.abs(r%2-1)),o=0,l=0,h=0;r>=0&&r<1?(o=n,l=a):r>=1&&r<2?(o=a,l=n):r>=2&&r<3?(l=n,h=a):r>=3&&r<4?(l=a,h=n):r>=4&&r<5?(o=a,h=n):r>=5&&r<6&&(o=n,h=a);var u=s-n/2;return i(o+u,l+u,h+u)}var VC={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"00ffff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"0000ff",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"00ffff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"ff00ff",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"639",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"};var GC=/^#[a-fA-F0-9]{6}$/,$C=/^#[a-fA-F0-9]{8}$/,jC=/^#[a-fA-F0-9]{3}$/,WC=/^#[a-fA-F0-9]{4}$/,HC=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,qC=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,XC=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,YC=/^hsl(?:a)?\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i;function KC(e){if("string"!=typeof e)throw new IC(3);var t=function(e){if("string"!=typeof e)return e;var t=e.toLowerCase();return VC[t]?"#"+VC[t]:e}(e);if(t.match(GC))return{red:parseInt(""+t[1]+t[2],16),green:parseInt(""+t[3]+t[4],16),blue:parseInt(""+t[5]+t[6],16)};if(t.match($C)){var s=parseFloat((parseInt(""+t[7]+t[8],16)/255).toFixed(2));return{red:parseInt(""+t[1]+t[2],16),green:parseInt(""+t[3]+t[4],16),blue:parseInt(""+t[5]+t[6],16),alpha:s}}if(t.match(jC))return{red:parseInt(""+t[1]+t[1],16),green:parseInt(""+t[2]+t[2],16),blue:parseInt(""+t[3]+t[3],16)};if(t.match(WC)){var i=parseFloat((parseInt(""+t[4]+t[4],16)/255).toFixed(2));return{red:parseInt(""+t[1]+t[1],16),green:parseInt(""+t[2]+t[2],16),blue:parseInt(""+t[3]+t[3],16),alpha:i}}var r=HC.exec(t);if(r)return{red:parseInt(""+r[1],10),green:parseInt(""+r[2],10),blue:parseInt(""+r[3],10)};var n=qC.exec(t.substring(0,50));if(n)return{red:parseInt(""+n[1],10),green:parseInt(""+n[2],10),blue:parseInt(""+n[3],10),alpha:parseFloat(""+n[4])>1?parseFloat(""+n[4])/100:parseFloat(""+n[4])};var a=XC.exec(t);if(a){var o="rgb("+zC(parseInt(""+a[1],10),parseInt(""+a[2],10)/100,parseInt(""+a[3],10)/100)+")",l=HC.exec(o);if(!l)throw new IC(4,t,o);return{red:parseInt(""+l[1],10),green:parseInt(""+l[2],10),blue:parseInt(""+l[3],10)}}var h=YC.exec(t.substring(0,50));if(h){var u="rgb("+zC(parseInt(""+h[1],10),parseInt(""+h[2],10)/100,parseInt(""+h[3],10)/100)+")",c=HC.exec(u);if(!c)throw new IC(4,t,u);return{red:parseInt(""+c[1],10),green:parseInt(""+c[2],10),blue:parseInt(""+c[3],10),alpha:parseFloat(""+h[4])>1?parseFloat(""+h[4])/100:parseFloat(""+h[4])}}throw new IC(5)}function QC(e){return function(e){var t,s=e.red/255,i=e.green/255,r=e.blue/255,n=Math.max(s,i,r),a=Math.min(s,i,r),o=(n+a)/2;if(n===a)return void 0!==e.alpha?{hue:0,saturation:0,lightness:o,alpha:e.alpha}:{hue:0,saturation:0,lightness:o};var l=n-a,h=o>.5?l/(2-n-a):l/(n+a);switch(n){case s:t=(i-r)/l+(i<r?6:0);break;case i:t=(r-s)/l+2;break;default:t=(s-i)/l+4}return t*=60,void 0!==e.alpha?{hue:t,saturation:h,lightness:o,alpha:e.alpha}:{hue:t,saturation:h,lightness:o}}(KC(e))}var ZC=function(e){return 7===e.length&&e[1]===e[2]&&e[3]===e[4]&&e[5]===e[6]?"#"+e[1]+e[3]+e[5]:e};function JC(e){var t=e.toString(16);return 1===t.length?"0"+t:t}function eR(e){return JC(Math.round(255*e))}function tR(e,t,s){return ZC("#"+eR(e)+eR(t)+eR(s))}function sR(e,t,s){return zC(e,t,s,tR)}function iR(e,t,s){if("number"==typeof e&&"number"==typeof t&&"number"==typeof s)return ZC("#"+JC(e)+JC(t)+JC(s));if("object"==typeof e&&void 0===t&&void 0===s)return ZC("#"+JC(e.red)+JC(e.green)+JC(e.blue));throw new IC(6)}function rR(e,t,s,i){if("object"==typeof e&&void 0===t&&void 0===s&&void 0===i)return e.alpha>=1?iR(e.red,e.green,e.blue):"rgba("+e.red+","+e.green+","+e.blue+","+e.alpha+")";throw new IC(7)}function nR(e){if("object"!=typeof e)throw new IC(8);if(function(e){return"number"==typeof e.red&&"number"==typeof e.green&&"number"==typeof e.blue&&"number"==typeof e.alpha}(e))return rR(e);if(function(e){return"number"==typeof e.red&&"number"==typeof e.green&&"number"==typeof e.blue&&("number"!=typeof e.alpha||void 0===e.alpha)}(e))return iR(e);if(function(e){return"number"==typeof e.hue&&"number"==typeof e.saturation&&"number"==typeof e.lightness&&"number"==typeof e.alpha}(e))return function(e,t,s,i){if("object"==typeof e&&void 0===t&&void 0===s&&void 0===i)return e.alpha>=1?sR(e.hue,e.saturation,e.lightness):"rgba("+zC(e.hue,e.saturation,e.lightness)+","+e.alpha+")";throw new IC(2)}(e);if(function(e){return"number"==typeof e.hue&&"number"==typeof e.saturation&&"number"==typeof e.lightness&&("number"!=typeof e.alpha||void 0===e.alpha)}(e))return function(e,t,s){if("object"==typeof e&&void 0===t&&void 0===s)return sR(e.hue,e.saturation,e.lightness);throw new IC(1)}(e);throw new IC(8)}function aR(e,t,s){return function(){var i=s.concat(Array.prototype.slice.call(arguments));return i.length>=t?e.apply(this,i):aR(e,t,i)}}function oR(e){return aR(e,e.length,[])}function lR(e,t,s){return Math.max(e,Math.min(t,s))}oR(function(e,t){if("transparent"===t)return t;var s=QC(t);return nR(RC({},s,{hue:s.hue+parseFloat(e)}))}),oR(function(e,t){if("transparent"===t)return t;var s=QC(t);return nR(RC({},s,{lightness:lR(0,1,s.lightness-parseFloat(e))}))}),oR(function(e,t){if("transparent"===t)return t;var s=QC(t);return nR(RC({},s,{saturation:lR(0,1,s.saturation-parseFloat(e))}))}),oR(function(e,t){if("transparent"===t)return t;var s=QC(t);return nR(RC({},s,{lightness:lR(0,1,s.lightness+parseFloat(e))}))});var hR=oR(function(e,t,s){if("transparent"===t)return s;if("transparent"===s)return t;if(0===e)return s;var i=KC(t),r=RC({},i,{alpha:"number"==typeof i.alpha?i.alpha:1}),n=KC(s),a=RC({},n,{alpha:"number"==typeof n.alpha?n.alpha:1}),o=r.alpha-a.alpha,l=2*parseFloat(e)-1,h=((l*o===-1?l:l+o)/(1+l*o)+1)/2,u=1-h;return rR({red:Math.floor(r.red*h+a.red*u),green:Math.floor(r.green*h+a.green*u),blue:Math.floor(r.blue*h+a.blue*u),alpha:r.alpha*parseFloat(e)+a.alpha*(1-parseFloat(e))})}),uR=hR;var cR=oR(function(e,t){if("transparent"===t)return t;var s=KC(t);return rR(RC({},s,{alpha:lR(0,1,(100*("number"==typeof s.alpha?s.alpha:1)+100*parseFloat(e))/100)}))}),dR=cR;oR(function(e,t){if("transparent"===t)return t;var s=QC(t);return nR(RC({},s,{saturation:lR(0,1,s.saturation+parseFloat(e))}))}),oR(function(e,t){return"transparent"===t?t:nR(RC({},QC(t),{hue:parseFloat(e)}))}),oR(function(e,t){return"transparent"===t?t:nR(RC({},QC(t),{lightness:parseFloat(e)}))}),oR(function(e,t){return"transparent"===t?t:nR(RC({},QC(t),{saturation:parseFloat(e)}))}),oR(function(e,t){return"transparent"===t?t:uR(parseFloat(e),"rgb(0, 0, 0)",t)}),oR(function(e,t){return"transparent"===t?t:uR(parseFloat(e),"rgb(255, 255, 255)",t)}),oR(function(e,t){if("transparent"===t)return t;var s=KC(t);return rR(RC({},s,{alpha:lR(0,1,+(100*("number"==typeof s.alpha?s.alpha:1)-100*parseFloat(e)).toFixed(2)/100)}))});var pR=Object.freeze({Linear:Object.freeze({None:function(e){return e},In:function(e){return e},Out:function(e){return e},InOut:function(e){return e}}),Quadratic:Object.freeze({In:function(e){return e*e},Out:function(e){return e*(2-e)},InOut:function(e){return(e*=2)<1?.5*e*e:-.5*(--e*(e-2)-1)}}),Cubic:Object.freeze({In:function(e){return e*e*e},Out:function(e){return--e*e*e+1},InOut:function(e){return(e*=2)<1?.5*e*e*e:.5*((e-=2)*e*e+2)}}),Quartic:Object.freeze({In:function(e){return e*e*e*e},Out:function(e){return 1- --e*e*e*e},InOut:function(e){return(e*=2)<1?.5*e*e*e*e:-.5*((e-=2)*e*e*e-2)}}),Quintic:Object.freeze({In:function(e){return e*e*e*e*e},Out:function(e){return--e*e*e*e*e+1},InOut:function(e){return(e*=2)<1?.5*e*e*e*e*e:.5*((e-=2)*e*e*e*e+2)}}),Sinusoidal:Object.freeze({In:function(e){return 1-Math.sin((1-e)*Math.PI/2)},Out:function(e){return Math.sin(e*Math.PI/2)},InOut:function(e){return.5*(1-Math.sin(Math.PI*(.5-e)))}}),Exponential:Object.freeze({In:function(e){return 0===e?0:Math.pow(1024,e-1)},Out:function(e){return 1===e?1:1-Math.pow(2,-10*e)},InOut:function(e){return 0===e?0:1===e?1:(e*=2)<1?.5*Math.pow(1024,e-1):.5*(2-Math.pow(2,-10*(e-1)))}}),Circular:Object.freeze({In:function(e){return 1-Math.sqrt(1-e*e)},Out:function(e){return Math.sqrt(1- --e*e)},InOut:function(e){return(e*=2)<1?-.5*(Math.sqrt(1-e*e)-1):.5*(Math.sqrt(1-(e-=2)*e)+1)}}),Elastic:Object.freeze({In:function(e){return 0===e?0:1===e?1:-Math.pow(2,10*(e-1))*Math.sin(5*(e-1.1)*Math.PI)},Out:function(e){return 0===e?0:1===e?1:Math.pow(2,-10*e)*Math.sin(5*(e-.1)*Math.PI)+1},InOut:function(e){return 0===e?0:1===e?1:(e*=2)<1?-.5*Math.pow(2,10*(e-1))*Math.sin(5*(e-1.1)*Math.PI):.5*Math.pow(2,-10*(e-1))*Math.sin(5*(e-1.1)*Math.PI)+1}}),Back:Object.freeze({In:function(e){var t=1.70158;return 1===e?1:e*e*((t+1)*e-t)},Out:function(e){var t=1.70158;return 0===e?0:--e*e*((t+1)*e+t)+1},InOut:function(e){var t=2.5949095;return(e*=2)<1?e*e*((t+1)*e-t)*.5:.5*((e-=2)*e*((t+1)*e+t)+2)}}),Bounce:Object.freeze({In:function(e){return 1-pR.Bounce.Out(1-e)},Out:function(e){return e<1/2.75?7.5625*e*e:e<2/2.75?7.5625*(e-=1.5/2.75)*e+.75:e<2.5/2.75?7.5625*(e-=2.25/2.75)*e+.9375:7.5625*(e-=2.625/2.75)*e+.984375},InOut:function(e){return e<.5?.5*pR.Bounce.In(2*e):.5*pR.Bounce.Out(2*e-1)+.5}}),generatePow:function(e){return void 0===e&&(e=4),e=(e=e<Number.EPSILON?Number.EPSILON:e)>1e4?1e4:e,{In:function(t){return Math.pow(t,e)},Out:function(t){return 1-Math.pow(1-t,e)},InOut:function(t){return t<.5?Math.pow(2*t,e)/2:(1-Math.pow(2-2*t,e))/2+.5}}}}),mR=function(){return performance.now()},fR=function(){function e(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];this._tweens={},this._tweensAddedDuringUpdate={},this.add.apply(this,e)}return e.prototype.getAll=function(){var e=this;return Object.keys(this._tweens).map(function(t){return e._tweens[t]})},e.prototype.removeAll=function(){this._tweens={}},e.prototype.add=function(){for(var e,t=[],s=0;s<arguments.length;s++)t[s]=arguments[s];for(var i=0,r=t;i<r.length;i++){var n=r[i];null===(e=n._group)||void 0===e||e.remove(n),n._group=this,this._tweens[n.getId()]=n,this._tweensAddedDuringUpdate[n.getId()]=n}},e.prototype.remove=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var s=0,i=e;s<i.length;s++){var r=i[s];r._group=void 0,delete this._tweens[r.getId()],delete this._tweensAddedDuringUpdate[r.getId()]}},e.prototype.allStopped=function(){return this.getAll().every(function(e){return!e.isPlaying()})},e.prototype.update=function(e,t){void 0===e&&(e=mR()),void 0===t&&(t=!0);var s=Object.keys(this._tweens);if(0!==s.length)for(;s.length>0;){this._tweensAddedDuringUpdate={};for(var i=0;i<s.length;i++){var r=this._tweens[s[i]],n=!t;r&&!1===r.update(e,n)&&!t&&this.remove(r)}s=Object.keys(this._tweensAddedDuringUpdate)}},e}(),gR={Linear:function(e,t){var s=e.length-1,i=s*t,r=Math.floor(i),n=gR.Utils.Linear;return t<0?n(e[0],e[1],i):t>1?n(e[s],e[s-1],s-i):n(e[r],e[r+1>s?s:r+1],i-r)},Utils:{Linear:function(e,t,s){return(t-e)*s+e}}},yR=function(){function e(){}return e.nextId=function(){return e._nextId++},e._nextId=0,e}(),bR=new fR,_R=function(){function e(e,t){this._isPaused=!1,this._pauseStart=0,this._valuesStart={},this._valuesEnd={},this._valuesStartRepeat={},this._duration=1e3,this._isDynamic=!1,this._initialRepeat=0,this._repeat=0,this._yoyo=!1,this._isPlaying=!1,this._reversed=!1,this._delayTime=0,this._startTime=0,this._easingFunction=pR.Linear.None,this._interpolationFunction=gR.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=yR.nextId(),this._isChainStopped=!1,this._propertiesAreSetUp=!1,this._goToEnd=!1,this._object=e,"object"==typeof t?(this._group=t,t.add(this)):!0===t&&(this._group=bR,bR.add(this))}return e.prototype.getId=function(){return this._id},e.prototype.isPlaying=function(){return this._isPlaying},e.prototype.isPaused=function(){return this._isPaused},e.prototype.getDuration=function(){return this._duration},e.prototype.to=function(e,t){if(void 0===t&&(t=1e3),this._isPlaying)throw new Error("Can not call Tween.to() while Tween is already started or paused. Stop the Tween first.");return this._valuesEnd=e,this._propertiesAreSetUp=!1,this._duration=t<0?0:t,this},e.prototype.duration=function(e){return void 0===e&&(e=1e3),this._duration=e<0?0:e,this},e.prototype.dynamic=function(e){return void 0===e&&(e=!1),this._isDynamic=e,this},e.prototype.start=function(e,t){if(void 0===e&&(e=mR()),void 0===t&&(t=!1),this._isPlaying)return this;if(this._repeat=this._initialRepeat,this._reversed)for(var s in this._reversed=!1,this._valuesStartRepeat)this._swapEndStartRepeatValues(s),this._valuesStart[s]=this._valuesStartRepeat[s];if(this._isPlaying=!0,this._isPaused=!1,this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._isChainStopped=!1,this._startTime=e,this._startTime+=this._delayTime,!this._propertiesAreSetUp||t){if(this._propertiesAreSetUp=!0,!this._isDynamic){var i={};for(var r in this._valuesEnd)i[r]=this._valuesEnd[r];this._valuesEnd=i}this._setupProperties(this._object,this._valuesStart,this._valuesEnd,this._valuesStartRepeat,t)}return this},e.prototype.startFromCurrentValues=function(e){return this.start(e,!0)},e.prototype._setupProperties=function(e,t,s,i,r){for(var n in s){var a=e[n],o=Array.isArray(a),l=o?"array":typeof a,h=!o&&Array.isArray(s[n]);if("undefined"!==l&&"function"!==l){if(h){if(0===(g=s[n]).length)continue;for(var u=[a],c=0,d=g.length;c<d;c+=1){var p=this._handleRelativeValue(a,g[c]);if(isNaN(p)){h=!1,console.warn("Found invalid interpolation list. Skipping.");break}u.push(p)}h&&(s[n]=u)}if("object"!==l&&!o||!a||h)(void 0===t[n]||r)&&(t[n]=a),o||(t[n]*=1),i[n]=h?s[n].slice().reverse():t[n]||0;else{t[n]=o?[]:{};var m=a;for(var f in m)t[n][f]=m[f];i[n]=o?[]:{};var g=s[n];if(!this._isDynamic){var y={};for(var f in g)y[f]=g[f];s[n]=g=y}this._setupProperties(m,t[n],g,i[n],r)}}}},e.prototype.stop=function(){return this._isChainStopped||(this._isChainStopped=!0,this.stopChainedTweens()),this._isPlaying?(this._isPlaying=!1,this._isPaused=!1,this._onStopCallback&&this._onStopCallback(this._object),this):this},e.prototype.end=function(){return this._goToEnd=!0,this.update(this._startTime+this._duration),this},e.prototype.pause=function(e){return void 0===e&&(e=mR()),this._isPaused||!this._isPlaying||(this._isPaused=!0,this._pauseStart=e),this},e.prototype.resume=function(e){return void 0===e&&(e=mR()),this._isPaused&&this._isPlaying?(this._isPaused=!1,this._startTime+=e-this._pauseStart,this._pauseStart=0,this):this},e.prototype.stopChainedTweens=function(){for(var e=0,t=this._chainedTweens.length;e<t;e++)this._chainedTweens[e].stop();return this},e.prototype.group=function(e){return e?(e.add(this),this):(console.warn("tween.group() without args has been removed, use group.add(tween) instead."),this)},e.prototype.remove=function(){var e;return null===(e=this._group)||void 0===e||e.remove(this),this},e.prototype.delay=function(e){return void 0===e&&(e=0),this._delayTime=e,this},e.prototype.repeat=function(e){return void 0===e&&(e=0),this._initialRepeat=e,this._repeat=e,this},e.prototype.repeatDelay=function(e){return this._repeatDelayTime=e,this},e.prototype.yoyo=function(e){return void 0===e&&(e=!1),this._yoyo=e,this},e.prototype.easing=function(e){return void 0===e&&(e=pR.Linear.None),this._easingFunction=e,this},e.prototype.interpolation=function(e){return void 0===e&&(e=gR.Linear),this._interpolationFunction=e,this},e.prototype.chain=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return this._chainedTweens=e,this},e.prototype.onStart=function(e){return this._onStartCallback=e,this},e.prototype.onEveryStart=function(e){return this._onEveryStartCallback=e,this},e.prototype.onUpdate=function(e){return this._onUpdateCallback=e,this},e.prototype.onRepeat=function(e){return this._onRepeatCallback=e,this},e.prototype.onComplete=function(e){return this._onCompleteCallback=e,this},e.prototype.onStop=function(e){return this._onStopCallback=e,this},e.prototype.update=function(t,s){var i,r,n=this;if(void 0===t&&(t=mR()),void 0===s&&(s=e.autoStartOnUpdate),this._isPaused)return!0;if(!this._goToEnd&&!this._isPlaying){if(!s)return!1;this.start(t,!0)}if(this._goToEnd=!1,t<this._startTime)return!0;!1===this._onStartCallbackFired&&(this._onStartCallback&&this._onStartCallback(this._object),this._onStartCallbackFired=!0),!1===this._onEveryStartCallbackFired&&(this._onEveryStartCallback&&this._onEveryStartCallback(this._object),this._onEveryStartCallbackFired=!0);var a=t-this._startTime,o=this._duration+(null!==(i=this._repeatDelayTime)&&void 0!==i?i:this._delayTime),l=this._duration+this._repeat*o,h=function(){if(0===n._duration)return 1;if(a>l)return 1;var e=Math.trunc(a/o),t=a-e*o,s=Math.min(t/n._duration,1);return 0===s&&a===n._duration?1:s}(),u=this._easingFunction(h);if(this._updateProperties(this._object,this._valuesStart,this._valuesEnd,u),this._onUpdateCallback&&this._onUpdateCallback(this._object,h),0===this._duration||a>=this._duration){if(this._repeat>0){var c=Math.min(Math.trunc((a-this._duration)/o)+1,this._repeat);for(r in isFinite(this._repeat)&&(this._repeat-=c),this._valuesStartRepeat)this._yoyo||"string"!=typeof this._valuesEnd[r]||(this._valuesStartRepeat[r]=this._valuesStartRepeat[r]+parseFloat(this._valuesEnd[r])),this._yoyo&&this._swapEndStartRepeatValues(r),this._valuesStart[r]=this._valuesStartRepeat[r];return this._yoyo&&(this._reversed=!this._reversed),this._startTime+=o*c,this._onRepeatCallback&&this._onRepeatCallback(this._object),this._onEveryStartCallbackFired=!1,!0}this._onCompleteCallback&&this._onCompleteCallback(this._object);for(var d=0,p=this._chainedTweens.length;d<p;d++)this._chainedTweens[d].start(this._startTime+this._duration,!1);return this._isPlaying=!1,!1}return!0},e.prototype._updateProperties=function(e,t,s,i){for(var r in s)if(void 0!==t[r]){var n=t[r]||0,a=s[r],o=Array.isArray(e[r]),l=Array.isArray(a);!o&&l?e[r]=this._interpolationFunction(a,i):"object"==typeof a&&a?this._updateProperties(e[r],n,a,i):"number"==typeof(a=this._handleRelativeValue(n,a))&&(e[r]=n+(a-n)*i)}},e.prototype._handleRelativeValue=function(e,t){return"string"!=typeof t?t:"+"===t.charAt(0)||"-"===t.charAt(0)?e+parseFloat(t):parseFloat(t)},e.prototype._swapEndStartRepeatValues=function(e){var t=this._valuesStartRepeat[e],s=this._valuesEnd[e];this._valuesStartRepeat[e]="string"==typeof s?this._valuesStartRepeat[e]+parseFloat(s):this._valuesEnd[e],this._valuesEnd[e]=t},e.autoStartOnUpdate=!1,e}();yR.nextId;var xR=bR;xR.getAll.bind(xR),xR.removeAll.bind(xR),xR.add.bind(xR),xR.remove.bind(xR),xR.update.bind(xR);function vR(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}var TR="object"==typeof global&&global&&global.Object===Object&&global,SR="object"==typeof self&&self&&self.Object===Object&&self,wR=TR||SR||Function("return this")(),MR=function(){return wR.Date.now()},ER=/\s/;var AR=/^\s+/;function NR(e){return e?e.slice(0,function(e){for(var t=e.length;t--&&ER.test(e.charAt(t)););return t}(e)+1).replace(AR,""):e}var CR=wR.Symbol,RR=Object.prototype,PR=RR.hasOwnProperty,BR=RR.toString,FR=CR?CR.toStringTag:void 0;var LR=Object.prototype.toString;var DR=CR?CR.toStringTag:void 0;function OR(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":DR&&DR in Object(e)?function(e){var t=PR.call(e,FR),s=e[FR];try{e[FR]=void 0;var i=!0}catch(e){}var r=BR.call(e);return i&&(t?e[FR]=s:delete e[FR]),r}(e):function(e){return LR.call(e)}(e)}var IR=/^[-+]0x[0-9a-f]+$/i,UR=/^0b[01]+$/i,kR=/^0o[0-7]+$/i,zR=parseInt;function VR(e){if("number"==typeof e)return e;if(function(e){return"symbol"==typeof e||function(e){return null!=e&&"object"==typeof e}(e)&&"[object Symbol]"==OR(e)}(e))return NaN;if(vR(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=vR(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=NR(e);var s=UR.test(e);return s||kR.test(e)?zR(e.slice(2),s?2:8):IR.test(e)?NaN:+e}var GR=Math.max,$R=Math.min;function jR(e,t,s){var i,r,n,a,o,l,h=0,u=!1,c=!1,d=!0;if("function"!=typeof e)throw new TypeError("Expected a function");function p(t){var s=i,n=r;return i=r=void 0,h=t,a=e.apply(n,s)}function m(e){var s=e-l;return void 0===l||s>=t||s<0||c&&e-h>=n}function f(){var e=MR();if(m(e))return g(e);o=setTimeout(f,function(e){var s=t-(e-l);return c?$R(s,n-(e-h)):s}(e))}function g(e){return o=void 0,d&&i?p(e):(i=r=void 0,a)}function y(){var e=MR(),s=m(e);if(i=arguments,r=this,l=e,s){if(void 0===o)return function(e){return h=e,o=setTimeout(f,t),u?p(e):a}(l);if(c)return clearTimeout(o),o=setTimeout(f,t),p(l)}return void 0===o&&(o=setTimeout(f,t)),a}return t=VR(t)||0,vR(s)&&(u=!!s.leading,n=(c="maxWait"in s)?GR(VR(s.maxWait)||0,t):n,d="trailing"in s?!!s.trailing:d),y.cancel=function(){void 0!==o&&clearTimeout(o),h=0,i=l=r=o=void 0},y.flush=function(){return void 0===o?a:g(MR())},y}function WR(e,t){(null==t||t>e.length)&&(t=e.length);for(var s=0,i=Array(t);s<t;s++)i[s]=e[s];return i}function HR(e,t,s){return Object.defineProperty(e,"prototype",{writable:!1}),e}function qR(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var s=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=s){var i,r,n,a,o=[],l=!0,h=!1;try{if(n=(s=s.call(e)).next,0===t);else for(;!(l=(i=n.call(s)).done)&&(o.push(i.value),o.length!==t);l=!0);}catch(e){h=!0,r=e}finally{try{if(!l&&null!=s.return&&(a=s.return(),Object(a)!==a))return}finally{if(h)throw r}}return o}}(e,t)||function(e,t){if(e){if("string"==typeof e)return WR(e,t);var s={}.toString.call(e).slice(8,-1);return"Object"===s&&e.constructor&&(s=e.constructor.name),"Map"===s||"Set"===s?Array.from(e):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?WR(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}var XR=HR(function e(t,s){var i=s.default,r=void 0===i?null:i,n=s.triggerUpdate,a=void 0===n||n,o=s.onChange,l=void 0===o?function(e,t){}:o;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.name=t,this.defaultVal=r,this.triggerUpdate=a,this.onChange=l});function YR(e){var t=e.stateInit,s=void 0===t?function(){return{}}:t,i=e.props,r=void 0===i?{}:i,n=e.methods,a=void 0===n?{}:n,o=e.aliases,l=void 0===o?{}:o,h=e.init,u=void 0===h?function(){}:h,c=e.update,d=void 0===c?function(){}:c,p=Object.keys(r).map(function(e){return new XR(e,r[e])});return function e(){for(var t=arguments.length,i=new Array(t),r=0;r<t;r++)i[r]=arguments[r];var n=!!(this instanceof e?this.constructor:void 0),o=n?i.shift():void 0,h=i[0],c=void 0===h?{}:h,m=Object.assign({},s instanceof Function?s(c):s,{initialised:!1}),f={};function g(e){return y(e,c),b(),g}var y=function(e,t){u.call(g,e,m,t),m.initialised=!0},b=jR(function(){m.initialised&&(d.call(g,m,f),f={})},1);return p.forEach(function(e){g[e.name]=function(e){var t=e.name,s=e.triggerUpdate,i=void 0!==s&&s,r=e.onChange,n=void 0===r?function(e,t){}:r,a=e.defaultVal,o=void 0===a?null:a;return function(e){var s=m[t];if(!arguments.length)return s;var r=void 0===e?o:e;return m[t]=r,n.call(g,r,m,s),!f.hasOwnProperty(t)&&(f[t]=s),i&&b(),g}}(e)}),Object.keys(a).forEach(function(e){g[e]=function(){for(var t,s=arguments.length,i=new Array(s),r=0;r<s;r++)i[r]=arguments[r];return(t=a[e]).call.apply(t,[g,m].concat(i))}}),Object.entries(l).forEach(function(e){var t=qR(e,2),s=t[0],i=t[1];return g[s]=g[i]}),g.resetProps=function(){return p.forEach(function(e){g[e.name](e.defaultVal)}),g},g.resetProps(),m._rerender=b,n&&o&&g(o),g}}var KR="http://www.w3.org/1999/xhtml",QR={svg:"http://www.w3.org/2000/svg",xhtml:KR,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function ZR(e){var t=e+="",s=t.indexOf(":");return s>=0&&"xmlns"!==(t=e.slice(0,s))&&(e=e.slice(s+1)),QR.hasOwnProperty(t)?{space:QR[t],local:e}:e}function JR(e){return function(){var t=this.ownerDocument,s=this.namespaceURI;return s===KR&&t.documentElement.namespaceURI===KR?t.createElement(e):t.createElementNS(s,e)}}function eP(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function tP(e){var t=ZR(e);return(t.local?eP:JR)(t)}function sP(){}function iP(e){return null==e?sP:function(){return this.querySelector(e)}}function rP(){return[]}function nP(e){return function(){return function(e){return null==e?[]:Array.isArray(e)?e:Array.from(e)}(e.apply(this,arguments))}}function aP(e){return function(t){return t.matches(e)}}var oP=Array.prototype.find;function lP(){return this.firstElementChild}var hP=Array.prototype.filter;function uP(){return Array.from(this.children)}function cP(e){return new Array(e.length)}function dP(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}function pP(e,t,s,i,r,n){for(var a,o=0,l=t.length,h=n.length;o<h;++o)(a=t[o])?(a.__data__=n[o],i[o]=a):s[o]=new dP(e,n[o]);for(;o<l;++o)(a=t[o])&&(r[o]=a)}function mP(e,t,s,i,r,n,a){var o,l,h,u=new Map,c=t.length,d=n.length,p=new Array(c);for(o=0;o<c;++o)(l=t[o])&&(p[o]=h=a.call(l,l.__data__,o,t)+"",u.has(h)?r[o]=l:u.set(h,l));for(o=0;o<d;++o)h=a.call(e,n[o],o,n)+"",(l=u.get(h))?(i[o]=l,l.__data__=n[o],u.delete(h)):s[o]=new dP(e,n[o]);for(o=0;o<c;++o)(l=t[o])&&u.get(p[o])===l&&(r[o]=l)}function fP(e){return e.__data__}function gP(e){return"object"==typeof e&&"length"in e?e:Array.from(e)}function yP(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function bP(e){return function(){this.removeAttribute(e)}}function _P(e){return function(){this.removeAttributeNS(e.space,e.local)}}function xP(e,t){return function(){this.setAttribute(e,t)}}function vP(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function TP(e,t){return function(){var s=t.apply(this,arguments);null==s?this.removeAttribute(e):this.setAttribute(e,s)}}function SP(e,t){return function(){var s=t.apply(this,arguments);null==s?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,s)}}function wP(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function MP(e){return function(){this.style.removeProperty(e)}}function EP(e,t,s){return function(){this.style.setProperty(e,t,s)}}function AP(e,t,s){return function(){var i=t.apply(this,arguments);null==i?this.style.removeProperty(e):this.style.setProperty(e,i,s)}}function NP(e){return function(){delete this[e]}}function CP(e,t){return function(){this[e]=t}}function RP(e,t){return function(){var s=t.apply(this,arguments);null==s?delete this[e]:this[e]=s}}function PP(e){return e.trim().split(/^|\s+/)}function BP(e){return e.classList||new FP(e)}function FP(e){this._node=e,this._names=PP(e.getAttribute("class")||"")}function LP(e,t){for(var s=BP(e),i=-1,r=t.length;++i<r;)s.add(t[i])}function DP(e,t){for(var s=BP(e),i=-1,r=t.length;++i<r;)s.remove(t[i])}function OP(e){return function(){LP(this,e)}}function IP(e){return function(){DP(this,e)}}function UP(e,t){return function(){(t.apply(this,arguments)?LP:DP)(this,e)}}function kP(){this.textContent=""}function zP(e){return function(){this.textContent=e}}function VP(e){return function(){var t=e.apply(this,arguments);this.textContent=null==t?"":t}}function GP(){this.innerHTML=""}function $P(e){return function(){this.innerHTML=e}}function jP(e){return function(){var t=e.apply(this,arguments);this.innerHTML=null==t?"":t}}function WP(){this.nextSibling&&this.parentNode.appendChild(this)}function HP(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function qP(){return null}function XP(){var e=this.parentNode;e&&e.removeChild(this)}function YP(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function KP(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function QP(e){return function(){var t=this.__on;if(t){for(var s,i=0,r=-1,n=t.length;i<n;++i)s=t[i],e.type&&s.type!==e.type||s.name!==e.name?t[++r]=s:this.removeEventListener(s.type,s.listener,s.options);++r?t.length=r:delete this.__on}}}function ZP(e,t,s){return function(){var i,r=this.__on,n=function(e){return function(t){e.call(this,t,this.__data__)}}(t);if(r)for(var a=0,o=r.length;a<o;++a)if((i=r[a]).type===e.type&&i.name===e.name)return this.removeEventListener(i.type,i.listener,i.options),this.addEventListener(i.type,i.listener=n,i.options=s),void(i.value=t);this.addEventListener(e.type,n,s),i={type:e.type,name:e.name,value:t,listener:n,options:s},r?r.push(i):this.__on=[i]}}function JP(e,t,s){var i=wP(e),r=i.CustomEvent;"function"==typeof r?r=new r(t,s):(r=i.document.createEvent("Event"),s?(r.initEvent(t,s.bubbles,s.cancelable),r.detail=s.detail):r.initEvent(t,!1,!1)),e.dispatchEvent(r)}function eB(e,t){return function(){return JP(this,e,t)}}function tB(e,t){return function(){return JP(this,e,t.apply(this,arguments))}}dP.prototype={constructor:dP,appendChild:function(e){return this._parent.insertBefore(e,this._next)},insertBefore:function(e,t){return this._parent.insertBefore(e,t)},querySelector:function(e){return this._parent.querySelector(e)},querySelectorAll:function(e){return this._parent.querySelectorAll(e)}},FP.prototype={add:function(e){this._names.indexOf(e)<0&&(this._names.push(e),this._node.setAttribute("class",this._names.join(" ")))},remove:function(e){var t=this._names.indexOf(e);t>=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(e){return this._names.indexOf(e)>=0}};var sB=[null];function iB(e,t){this._groups=e,this._parents=t}iB.prototype={constructor:iB,select:function(e){"function"!=typeof e&&(e=iP(e));for(var t=this._groups,s=t.length,i=new Array(s),r=0;r<s;++r)for(var n,a,o=t[r],l=o.length,h=i[r]=new Array(l),u=0;u<l;++u)(n=o[u])&&(a=e.call(n,n.__data__,u,o))&&("__data__"in n&&(a.__data__=n.__data__),h[u]=a);return new iB(i,this._parents)},selectAll:function(e){e="function"==typeof e?nP(e):function(e){return null==e?rP:function(){return this.querySelectorAll(e)}}(e);for(var t=this._groups,s=t.length,i=[],r=[],n=0;n<s;++n)for(var a,o=t[n],l=o.length,h=0;h<l;++h)(a=o[h])&&(i.push(e.call(a,a.__data__,h,o)),r.push(a));return new iB(i,r)},selectChild:function(e){return this.select(null==e?lP:function(e){return function(){return oP.call(this.children,e)}}("function"==typeof e?e:aP(e)))},selectChildren:function(e){return this.selectAll(null==e?uP:function(e){return function(){return hP.call(this.children,e)}}("function"==typeof e?e:aP(e)))},filter:function(e){"function"!=typeof e&&(e=function(e){return function(){return this.matches(e)}}(e));for(var t=this._groups,s=t.length,i=new Array(s),r=0;r<s;++r)for(var n,a=t[r],o=a.length,l=i[r]=[],h=0;h<o;++h)(n=a[h])&&e.call(n,n.__data__,h,a)&&l.push(n);return new iB(i,this._parents)},data:function(e,t){if(!arguments.length)return Array.from(this,fP);var s=t?mP:pP,i=this._parents,r=this._groups;"function"!=typeof e&&(e=function(e){return function(){return e}}(e));for(var n=r.length,a=new Array(n),o=new Array(n),l=new Array(n),h=0;h<n;++h){var u=i[h],c=r[h],d=c.length,p=gP(e.call(u,u&&u.__data__,h,i)),m=p.length,f=o[h]=new Array(m),g=a[h]=new Array(m);s(u,c,f,g,l[h]=new Array(d),p,t);for(var y,b,_=0,x=0;_<m;++_)if(y=f[_]){for(_>=x&&(x=_+1);!(b=g[x])&&++x<m;);y._next=b||null}}return(a=new iB(a,i))._enter=o,a._exit=l,a},enter:function(){return new iB(this._enter||this._groups.map(cP),this._parents)},exit:function(){return new iB(this._exit||this._groups.map(cP),this._parents)},join:function(e,t,s){var i=this.enter(),r=this,n=this.exit();return"function"==typeof e?(i=e(i))&&(i=i.selection()):i=i.append(e+""),null!=t&&(r=t(r))&&(r=r.selection()),null==s?n.remove():s(n),i&&r?i.merge(r).order():r},merge:function(e){for(var t=e.selection?e.selection():e,s=this._groups,i=t._groups,r=s.length,n=i.length,a=Math.min(r,n),o=new Array(r),l=0;l<a;++l)for(var h,u=s[l],c=i[l],d=u.length,p=o[l]=new Array(d),m=0;m<d;++m)(h=u[m]||c[m])&&(p[m]=h);for(;l<r;++l)o[l]=s[l];return new iB(o,this._parents)},selection:function(){return this},order:function(){for(var e=this._groups,t=-1,s=e.length;++t<s;)for(var i,r=e[t],n=r.length-1,a=r[n];--n>=0;)(i=r[n])&&(a&&4^i.compareDocumentPosition(a)&&a.parentNode.insertBefore(i,a),a=i);return this},sort:function(e){function t(t,s){return t&&s?e(t.__data__,s.__data__):!t-!s}e||(e=yP);for(var s=this._groups,i=s.length,r=new Array(i),n=0;n<i;++n){for(var a,o=s[n],l=o.length,h=r[n]=new Array(l),u=0;u<l;++u)(a=o[u])&&(h[u]=a);h.sort(t)}return new iB(r,this._parents).order()},call:function(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this},nodes:function(){return Array.from(this)},node:function(){for(var e=this._groups,t=0,s=e.length;t<s;++t)for(var i=e[t],r=0,n=i.length;r<n;++r){var a=i[r];if(a)return a}return null},size:function(){let e=0;for(const t of this)++e;return e},empty:function(){return!this.node()},each:function(e){for(var t=this._groups,s=0,i=t.length;s<i;++s)for(var r,n=t[s],a=0,o=n.length;a<o;++a)(r=n[a])&&e.call(r,r.__data__,a,n);return this},attr:function(e,t){var s=ZR(e);if(arguments.length<2){var i=this.node();return s.local?i.getAttributeNS(s.space,s.local):i.getAttribute(s)}return this.each((null==t?s.local?_P:bP:"function"==typeof t?s.local?SP:TP:s.local?vP:xP)(s,t))},style:function(e,t,s){return arguments.length>1?this.each((null==t?MP:"function"==typeof t?AP:EP)(e,t,null==s?"":s)):function(e,t){return e.style.getPropertyValue(t)||wP(e).getComputedStyle(e,null).getPropertyValue(t)}(this.node(),e)},property:function(e,t){return arguments.length>1?this.each((null==t?NP:"function"==typeof t?RP:CP)(e,t)):this.node()[e]},classed:function(e,t){var s=PP(e+"");if(arguments.length<2){for(var i=BP(this.node()),r=-1,n=s.length;++r<n;)if(!i.contains(s[r]))return!1;return!0}return this.each(("function"==typeof t?UP:t?OP:IP)(s,t))},text:function(e){return arguments.length?this.each(null==e?kP:("function"==typeof e?VP:zP)(e)):this.node().textContent},html:function(e){return arguments.length?this.each(null==e?GP:("function"==typeof e?jP:$P)(e)):this.node().innerHTML},raise:function(){return this.each(WP)},lower:function(){return this.each(HP)},append:function(e){var t="function"==typeof e?e:tP(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})},insert:function(e,t){var s="function"==typeof e?e:tP(e),i=null==t?qP:"function"==typeof t?t:iP(t);return this.select(function(){return this.insertBefore(s.apply(this,arguments),i.apply(this,arguments)||null)})},remove:function(){return this.each(XP)},clone:function(e){return this.select(e?KP:YP)},datum:function(e){return arguments.length?this.property("__data__",e):this.node().__data__},on:function(e,t,s){var i,r,n=function(e){return e.trim().split(/^|\s+/).map(function(e){var t="",s=e.indexOf(".");return s>=0&&(t=e.slice(s+1),e=e.slice(0,s)),{type:e,name:t}})}(e+""),a=n.length;if(!(arguments.length<2)){for(o=t?ZP:QP,i=0;i<a;++i)this.each(o(n[i],t,s));return this}var o=this.node().__on;if(o)for(var l,h=0,u=o.length;h<u;++h)for(i=0,l=o[h];i<a;++i)if((r=n[i]).type===l.type&&r.name===l.name)return l.value},dispatch:function(e,t){return this.each(("function"==typeof t?tB:eB)(e,t))},[Symbol.iterator]:function*(){for(var e=this._groups,t=0,s=e.length;t<s;++t)for(var i,r=e[t],n=0,a=r.length;n<a;++n)(i=r[n])&&(yield i)}};var rB,nB,aB,oB,lB,hB,uB,cB,dB,pB,mB,fB,gB,yB,bB,_B={},xB=[],vB=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,TB=Array.isArray;function SB(e,t){for(var s in t)e[s]=t[s];return e}function wB(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function MB(e,t,s,i,r){var n={type:e,props:t,key:s,ref:i,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:null==r?++aB:r,__i:-1,__u:0};return null==r&&null!=nB.vnode&&nB.vnode(n),n}function EB(e){return e.children}function AB(e,t){this.props=e,this.context=t}function NB(e,t){if(null==t)return e.__?NB(e.__,e.__i+1):null;for(var s;t<e.__k.length;t++)if(null!=(s=e.__k[t])&&null!=s.__e)return s.__e;return"function"==typeof e.type?NB(e):null}function CB(e){if(e.__P&&e.__d){var t=e.__v,s=t.__e,i=[],r=[],n=SB({},t);n.__v=t.__v+1,nB.vnode&&nB.vnode(n),zB(e.__P,n,t,e.__n,e.__P.namespaceURI,32&t.__u?[s]:null,i,null==s?NB(t):s,!!(32&t.__u),r),n.__v=t.__v,n.__.__k[n.__i]=n,GB(i,n,r),t.__e=t.__=null,n.__e!=s&&RB(n)}}function RB(e){if(null!=(e=e.__)&&null!=e.__c)return e.__e=e.__c.base=null,e.__k.some(function(t){if(null!=t&&null!=t.__e)return e.__e=e.__c.base=t.__e}),RB(e)}function PB(e){(!e.__d&&(e.__d=!0)&&lB.push(e)&&!BB.__r++||hB!=nB.debounceRendering)&&((hB=nB.debounceRendering)||uB)(BB)}function BB(){try{for(var e,t=1;lB.length;)lB.length>t&&lB.sort(cB),e=lB.shift(),t=lB.length,CB(e)}finally{lB.length=BB.__r=0}}function FB(e,t,s,i,r,n,a,o,l,h,u){var c,d,p,m,f,g,y=i&&i.__k||xB,b=t.length;for(l=LB(s,t,y,l,b),c=0;c<b;c++)null!=(p=s.__k[c])&&(d=-1!=p.__i&&y[p.__i]||_B,p.__i=c,g=zB(e,p,d,r,n,a,o,l,h,u),m=p.__e,p.ref&&d.ref!=p.ref&&(d.ref&&WB(d.ref,null,p),u.push(p.ref,p.__c||m,p)),null==f&&null!=m&&(f=m),4&p.__u?(l=DB(p,l,e),d.__e&&(d.__e=null)):"function"==typeof p.type&&void 0!==g?l=g:m&&(l=m.nextSibling),p.__u&=-7);return s.__e=f,l}function LB(e,t,s,i,r){var n,a,o,l,h,u=s.length,c=u,d=0;for(e.__k=new Array(r),n=0;n<r;n++)null!=(a=t[n])&&"boolean"!=typeof a&&"function"!=typeof a?("string"==typeof a||"number"==typeof a||"bigint"==typeof a||a.constructor==String?a=e.__k[n]=MB(null,a,null,null,null):TB(a)?a=e.__k[n]=MB(EB,{children:a},null,null,null):void 0===a.constructor&&a.__b>0?a=e.__k[n]=MB(a.type,a.props,a.key,a.ref?a.ref:null,a.__v):e.__k[n]=a,l=n+d,a.__=e,a.__b=e.__b+1,o=null,-1!=(h=a.__i=OB(a,s,l,c))&&(c--,(o=s[h])&&(o.__u|=2)),null==o||null==o.__v?(-1==h&&(r>u?d--:r<u&&d++),"function"!=typeof a.type&&(a.__u|=4)):h!=l&&(h==l-1?d--:h==l+1?d++:(h>l?d--:d++,a.__u|=4))):e.__k[n]=null;if(c)for(n=0;n<u;n++)null!=(o=s[n])&&!(2&o.__u)&&(o.__e==i&&(i=NB(o)),HB(o,o));return i}function DB(e,t,s){var i,r;if("function"==typeof e.type){for(i=e.__k,r=0;i&&r<i.length;r++)i[r]&&(i[r].__=e,t=DB(i[r],t,s));return t}e.__e!=t&&(t&&e.type&&!t.parentNode&&(t=NB(e)),t=s.insertBefore(e.__e,t||null));do{t=t&&t.nextSibling}while(null!=t&&8==t.nodeType);return t}function OB(e,t,s,i){var r,n,a,o=e.key,l=e.type,h=t[s],u=null!=h&&!(2&h.__u);if(null===h&&null==o||u&&o==h.key&&l==h.type)return s;if(i>(u?1:0))for(r=s-1,n=s+1;r>=0||n<t.length;)if(null!=(h=t[a=r>=0?r--:n++])&&!(2&h.__u)&&o==h.key&&l==h.type)return a;return-1}function IB(e,t,s){"-"==t[0]?e.setProperty(t,null==s?"":s):e[t]=null==s?"":"number"!=typeof s||vB.test(t)?s:s+"px"}function UB(e,t,s,i,r){var n,a;e:if("style"==t)if("string"==typeof s)e.style.cssText=s;else{if("string"==typeof i&&(e.style.cssText=i=""),i)for(t in i)s&&t in s||IB(e.style,t,"");if(s)for(t in s)i&&s[t]==i[t]||IB(e.style,t,s[t])}else if("o"==t[0]&&"n"==t[1])n=t!=(t=t.replace(fB,"$1")),a=t.toLowerCase(),t=a in e||"onFocusOut"==t||"onFocusIn"==t?a.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+n]=s,s?i?s[mB]=i[mB]:(s[mB]=gB,e.addEventListener(t,n?bB:yB,n)):e.removeEventListener(t,n?bB:yB,n);else{if("http://www.w3.org/2000/svg"==r)t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if("width"!=t&&"height"!=t&&"href"!=t&&"list"!=t&&"form"!=t&&"tabIndex"!=t&&"download"!=t&&"rowSpan"!=t&&"colSpan"!=t&&"role"!=t&&"popover"!=t&&t in e)try{e[t]=null==s?"":s;break e}catch(e){}"function"==typeof s||(null==s||!1===s&&"-"!=t[4]?e.removeAttribute(t):e.setAttribute(t,"popover"==t&&1==s?"":s))}}function kB(e){return function(t){if(this.l){var s=this.l[t.type+e];if(null==t[pB])t[pB]=gB++;else if(t[pB]<s[mB])return;return s(nB.event?nB.event(t):t)}}}function zB(e,t,s,i,r,n,a,o,l,h){var u,c,d,p,m,f,g,y,b,_,x,v,T,S,w,M,E=t.type;if(void 0!==t.constructor)return null;128&s.__u&&(l=!!(32&s.__u),n=[o=t.__e=s.__e]),(u=nB.__b)&&u(t);e:if("function"==typeof E){c=a.length;try{if(b=t.props,_=E.prototype&&E.prototype.render,x=(u=E.contextType)&&i[u.__c],v=u?x?x.props.value:u.__:i,s.__c?y=(d=t.__c=s.__c).__=d.__E:(_?t.__c=d=new E(b,v):(t.__c=d=new AB(b,v),d.constructor=E,d.render=qB),x&&x.sub(d),d.state||(d.state={}),d.__n=i,p=d.__d=!0,d.__h=[],d._sb=[]),_&&null==d.__s&&(d.__s=d.state),_&&null!=E.getDerivedStateFromProps&&(d.__s==d.state&&(d.__s=SB({},d.__s)),SB(d.__s,E.getDerivedStateFromProps(b,d.__s))),m=d.props,f=d.state,d.__v=t,p)_&&null==E.getDerivedStateFromProps&&null!=d.componentWillMount&&d.componentWillMount(),_&&null!=d.componentDidMount&&d.__h.push(d.componentDidMount);else{if(_&&null==E.getDerivedStateFromProps&&b!==m&&null!=d.componentWillReceiveProps&&d.componentWillReceiveProps(b,v),t.__v==s.__v||!d.__e&&null!=d.shouldComponentUpdate&&!1===d.shouldComponentUpdate(b,d.__s,v)){t.__v!=s.__v&&(d.props=b,d.state=d.__s,d.__d=!1),t.__e=s.__e,t.__k=s.__k,t.__k.some(function(e){e&&(e.__=t)}),xB.push.apply(d.__h,d._sb),d._sb=[],d.__h.length&&a.push(d),o=NB(s);break e}null!=d.componentWillUpdate&&d.componentWillUpdate(b,d.__s,v),_&&null!=d.componentDidUpdate&&d.__h.push(function(){d.componentDidUpdate(m,f,g)})}if(d.context=v,d.props=b,d.__P=e,d.__e=!1,T=nB.__r,S=0,_)d.state=d.__s,d.__d=!1,T&&T(t),u=d.render(d.props,d.state,d.context),xB.push.apply(d.__h,d._sb),d._sb=[];else do{d.__d=!1,T&&T(t),u=d.render(d.props,d.state,d.context),d.state=d.__s}while(d.__d&&++S<25);d.state=d.__s,null!=d.getChildContext&&(i=SB(SB({},i),d.getChildContext())),_&&!p&&null!=d.getSnapshotBeforeUpdate&&(g=d.getSnapshotBeforeUpdate(m,f)),w=null!=u&&u.type===EB&&null==u.key?$B(u.props.children):u,o=FB(e,TB(w)?w:[w],t,s,i,r,n,a,o,l,h),d.base=t.__e,t.__u&=-161,d.__h.length&&a.push(d),y&&(d.__E=d.__=null)}catch(e){if(a.length=c,t.__v=null,l||null!=n){if(e.then){for(t.__u|=l?160:128;o&&8==o.nodeType&&o.nextSibling;)o=o.nextSibling;null!=n&&(n[n.indexOf(o)]=null),t.__e=o}else if(null!=n)for(M=n.length;M--;)wB(n[M])}else t.__e=s.__e;null==t.__k&&(t.__k=s.__k||[]),e.then||VB(t),nB.__e(e,t,s)}}else null==n&&t.__v==s.__v?(t.__k=s.__k,t.__e=s.__e):o=t.__e=jB(s.__e,t,s,i,r,n,a,l,h);return(u=nB.diffed)&&u(t),128&t.__u?void 0:o}function VB(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(VB))}function GB(e,t,s){for(var i=0;i<s.length;i++)WB(s[i],s[++i],s[++i]);nB.__c&&nB.__c(t,e),e.some(function(t){try{e=t.__h,t.__h=[],e.some(function(e){e.call(t)})}catch(e){nB.__e(e,t.__v)}})}function $B(e){return"object"!=typeof e||null==e||e.__b>0?e:TB(e)?e.map($B):void 0!==e.constructor?null:SB({},e)}function jB(e,t,s,i,r,n,a,o,l){var h,u,c,d,p,m,f,g=s.props||_B,y=t.props,b=t.type;if("svg"==b?r="http://www.w3.org/2000/svg":"math"==b?r="http://www.w3.org/1998/Math/MathML":r||(r="http://www.w3.org/1999/xhtml"),null!=n)for(h=0;h<n.length;h++)if((p=n[h])&&"setAttribute"in p==!!b&&(b?p.localName==b:3==p.nodeType)){e=p,n[h]=null;break}if(null==e){if(null==b)return document.createTextNode(y);e=document.createElementNS(r,b,y.is&&y),o&&(nB.__m&&nB.__m(t,n),o=!1),n=null}if(null==b)g===y||o&&e.data==y||(e.data=y);else{if(n="textarea"==b&&null!=y.defaultValue?null:n&&rB.call(e.childNodes),!o&&null!=n)for(g={},h=0;h<e.attributes.length;h++)g[(p=e.attributes[h]).name]=p.value;for(h in g)p=g[h],"dangerouslySetInnerHTML"==h?c=p:"children"==h||h in y||"value"==h&&"defaultValue"in y||"checked"==h&&"defaultChecked"in y||UB(e,h,null,p,r);for(h in y)p=y[h],"children"==h?d=p:"dangerouslySetInnerHTML"==h?u=p:"value"==h?m=p:"checked"==h?f=p:o&&"function"!=typeof p||g[h]===p||UB(e,h,p,g[h],r);if(u)o||c&&(u.__html==c.__html||u.__html==e.innerHTML)||(e.innerHTML=u.__html),t.__k=[];else if(c&&(e.innerHTML=""),FB("template"==t.type?e.content:e,TB(d)?d:[d],t,s,i,"foreignObject"==b?"http://www.w3.org/1999/xhtml":r,n,a,n?n[0]:s.__k&&NB(s,0),o,l),null!=n)for(h=n.length;h--;)wB(n[h]);o&&"textarea"!=b||(h="value","progress"==b&&null==m?e.removeAttribute("value"):null!=m&&(m!==e[h]||"progress"==b&&!m||"option"==b&&m!=g[h])&&UB(e,h,m,g[h],r),h="checked",null!=f&&f!=e[h]&&UB(e,h,f,g[h],r))}return e}function WB(e,t,s){try{if("function"==typeof e){var i="function"==typeof e.__u;i&&e.__u(),i&&null==t||(e.__u=e(t))}else e.current=t}catch(e){nB.__e(e,s)}}function HB(e,t,s){var i,r;if(nB.unmount&&nB.unmount(e),(i=e.ref)&&(i.current&&i.current!=e.__e||WB(i,null,t)),null!=(i=e.__c)){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(e){nB.__e(e,t)}i.base=i.__P=i.__n=null}if(i=e.__k)for(r=0;r<i.length;r++)i[r]&&HB(i[r],t,s||"function"!=typeof e.type);s||wB(e.__e),e.__c=e.__=e.__e=void 0}function qB(e,t,s){return this.constructor(e,s)}function XB(e,t,s){var i,r,n;t==document&&(t=document.documentElement),nB.__&&nB.__(e,t),i=!1?null:t.__k,r=[],n=[],zB(t,e=t.__k=function(e,t,s){var i,r,n,a={};for(n in t)"key"==n?i=t[n]:"ref"==n?r=t[n]:a[n]=t[n];if(arguments.length>2&&(a.children=arguments.length>3?rB.call(arguments,2):s),"function"==typeof e&&null!=e.defaultProps)for(n in e.defaultProps)void 0===a[n]&&(a[n]=e.defaultProps[n]);return MB(e,a,i,r,null)}(EB,null,[e]),i||_B,_B,t.namespaceURI,i?null:t.firstChild?rB.call(t.childNodes):null,r,i?i.__e:t.firstChild,false,n),GB(r,e,n),e.props.children=null}function YB(e,t,s){var i,r,n,a,o=SB({},e.props);for(n in e.type&&e.type.defaultProps&&(a=e.type.defaultProps),t)"key"==n?i=t[n]:"ref"==n?r=t[n]:o[n]=void 0===t[n]&&null!=a?a[n]:t[n];return arguments.length>2&&(o.children=arguments.length>3?rB.call(arguments,2):s),MB(e.type,o,i||e.key,r||e.ref,null)}function KB(e,t){(null==t||t>e.length)&&(t=e.length);for(var s=0,i=Array(t);s<t;s++)i[s]=e[s];return i}function QB(e,t,s){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var s=e[Symbol.toPrimitive];if(void 0!==s){var i=s.call(e,t);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[t]=s,e}function ZB(e,t){var s=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),s.push.apply(s,i)}return s}function JB(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var s=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=s){var i,r,n,a,o=[],l=!0,h=!1;try{if(n=(s=s.call(e)).next,0===t);else for(;!(l=(i=n.call(s)).done)&&(o.push(i.value),o.length!==t);l=!0);}catch(e){h=!0,r=e}finally{try{if(!l&&null!=s.return&&(a=s.return(),Object(a)!==a))return}finally{if(h)throw r}}return o}}(e,t)||function(e,t){if(e){if("string"==typeof e)return KB(e,t);var s={}.toString.call(e).slice(8,-1);return"Object"===s&&e.constructor&&(s=e.constructor.name),"Map"===s||"Set"===s?Array.from(e):"Arguments"===s||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(s)?KB(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function eF(e){return eF="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},eF(e)}rB=xB.slice,nB={__e:function(e,t,s,i){for(var r,n,a;t=t.__;)if((r=t.__c)&&!r.__)try{if((n=r.constructor)&&null!=n.getDerivedStateFromError&&(r.setState(n.getDerivedStateFromError(e)),a=r.__d),null!=r.componentDidCatch&&(r.componentDidCatch(e,i||{}),a=r.__d),a)return r.__E=r}catch(t){e=t}throw e}},aB=0,oB=function(e){return null!=e&&void 0===e.constructor},AB.prototype.setState=function(e,t){var s;s=null!=this.__s&&this.__s!=this.state?this.__s:this.__s=SB({},this.state),"function"==typeof e&&(e=e(SB({},s),this.props)),e&&SB(s,e),null!=e&&this.__v&&(t&&this._sb.push(t),PB(this))},AB.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),PB(this))},AB.prototype.render=EB,lB=[],uB="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,cB=function(e,t){return e.__v.__b-t.__v.__b},BB.__r=0,dB=Math.random().toString(8),pB="__d"+dB,mB="__a"+dB,fB=/(PointerCapture)$|Capture$/i,gB=0,yB=kB(!1),bB=kB(!0);var tF=function(e){if("object"!==eF(e))return e;var t,s=YB(e);s.props&&(s.props=function(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?ZB(Object(s),!0).forEach(function(t){QB(e,t,s[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):ZB(Object(s)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))})}return e}({},s.props),null!=s&&null!==(t=s.props)&&void 0!==t&&t.children&&(s.props.children=Array.isArray(s.props.children)?s.props.children.map(tF):tF(s.props.children)));return s};!function(e,t){void 0===t&&(t={});var s=t.insertAt;if("undefined"!=typeof document){var i=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css","top"===s&&i.firstChild?i.insertBefore(r,i.firstChild):i.appendChild(r),r.styleSheet?r.styleSheet.cssText=e:r.appendChild(document.createTextNode(e))}}(".float-tooltip-kap {\n position: absolute;\n width: max-content; /* prevent shrinking near right edge */\n max-width: max(50%, 150px);\n padding: 3px 5px;\n border-radius: 3px;\n font: 12px sans-serif;\n color: #eee;\n background: rgba(0,0,0,0.6);\n pointer-events: none;\n}\n");var sF=YR({props:{content:{default:!1},offsetX:{triggerUpdate:!1},offsetY:{triggerUpdate:!1}},init:function(e,t){var s=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).style,i=void 0===s?{}:s,r=function(e){return"string"==typeof e?new iB([[document.querySelector(e)]],[document.documentElement]):new iB([[e]],sB)}(!!e&&"object"===eF(e)&&!!e.node&&"function"==typeof e.node?e.node():e);"static"===r.style("position")&&r.style("position","relative"),t.tooltipEl=r.append("div").attr("class","float-tooltip-kap"),Object.entries(i).forEach(function(e){var s=JB(e,2),i=s[0],r=s[1];return t.tooltipEl.style(i,r)}),t.tooltipEl.style("left","-10000px").style("display","none");var n="tooltip-".concat(Math.round(1e12*Math.random()));t.mouseInside=!1,r.on("mousemove.".concat(n),function(e){t.mouseInside=!0;var s=function(e,t){if(e=function(e){let t;for(;t=e.sourceEvent;)e=t;return e}(e),void 0===t&&(t=e.currentTarget),t){var s=t.ownerSVGElement||t;if(s.createSVGPoint){var i=s.createSVGPoint();return i.x=e.clientX,i.y=e.clientY,[(i=i.matrixTransform(t.getScreenCTM().inverse())).x,i.y]}if(t.getBoundingClientRect){var r=t.getBoundingClientRect();return[e.clientX-r.left-t.clientLeft,e.clientY-r.top-t.clientTop]}}return[e.pageX,e.pageY]}(e),i=r.node(),n=i.offsetWidth,a=i.offsetHeight,o=[null===t.offsetX||void 0===t.offsetX?"-".concat(s[0]/n*100,"%"):"number"==typeof t.offsetX?"calc(-50% + ".concat(t.offsetX,"px)"):t.offsetX,null===t.offsetY||void 0===t.offsetY?a>130&&a-s[1]<100?"calc(-100% - 6px)":"21px":"number"==typeof t.offsetY?t.offsetY<0?"calc(-100% - ".concat(Math.abs(t.offsetY),"px)"):"".concat(t.offsetY,"px"):t.offsetY];t.tooltipEl.style("left",s[0]+"px").style("top",s[1]+"px").style("transform","translate(".concat(o.join(","),")")),t.content&&t.tooltipEl.style("display","inline")}),r.on("mouseover.".concat(n),function(){t.mouseInside=!0,t.content&&t.tooltipEl.style("display","inline")}),r.on("mouseout.".concat(n),function(){t.mouseInside=!1,t.tooltipEl.style("display","none")})},update:function(e){var t,s;e.tooltipEl.style("display",e.content&&e.mouseInside?"inline":"none"),e.content?e.content instanceof HTMLElement?(e.tooltipEl.text(""),e.tooltipEl.append(function(){return e.content})):"string"==typeof e.content?e.tooltipEl.html(e.content):!function(e){return oB(YB(e))}(e.content)?(e.tooltipEl.style("display","none"),console.warn("Tooltip content is invalid, skipping.",e.content,e.content.toString())):(e.tooltipEl.text(""),t=e.content,delete(s=e.tooltipEl.node()).__k,XB(tF(t),s)):e.tooltipEl.text("")}});const iF=e=>{e instanceof Array?e.forEach(iF):(e.map&&e.map.dispose(),e.dispose())},rF=e=>{e.geometry&&e.geometry.dispose(),e.material&&iF(e.material),e.texture&&e.texture.dispose(),e.children&&e.children.forEach(rF)},nF=window.THREE?window.THREE:{WebGLRenderer:e.WebGLRenderer,Scene:e.Scene,PerspectiveCamera:e.PerspectiveCamera,Raycaster:e.Raycaster,SRGBColorSpace:e.SRGBColorSpace,TextureLoader:e.TextureLoader,Vector2:e.Vector2,Vector3:e.Vector3,Box3:e.Box3,Color:e.Color,Mesh:e.Mesh,SphereGeometry:e.SphereGeometry,MeshBasicMaterial:e.MeshBasicMaterial,BackSide:e.BackSide,Timer:e.Timer};var aF=YR({props:{width:{default:window.innerWidth,onChange(e,t,s){isNaN(e)&&(t.width=s)}},height:{default:window.innerHeight,onChange(e,t,s){isNaN(e)&&(t.height=s)}},viewOffset:{default:[0,0]},backgroundColor:{default:"#000011"},backgroundImageUrl:{},onBackgroundImageLoaded:{},showNavInfo:{default:!0},skyRadius:{default:5e4},objects:{default:[]},lights:{default:[]},enablePointerInteraction:{default:!0,onChange(e,t){t.hoverObj=null,t.tooltip&&t.tooltip.content(null)},triggerUpdate:!1},pointerRaycasterThrottleMs:{default:50,triggerUpdate:!1},lineHoverPrecision:{default:1,triggerUpdate:!1},pointsHoverPrecision:{default:1,triggerUpdate:!1},hoverOrderComparator:{triggerUpdate:!1},hoverFilter:{default:()=>!0,triggerUpdate:!1},tooltipContent:{triggerUpdate:!1},hoverDuringDrag:{default:!1,triggerUpdate:!1},clickAfterDrag:{default:!1,triggerUpdate:!1},onHover:{default:()=>{},triggerUpdate:!1},onClick:{default:()=>{},triggerUpdate:!1},onRightClick:{triggerUpdate:!1}},methods:{tick:function(e){if(e.initialised){e.controls.enabled&&e.controls.update&&e.controls.update(Math.min(1,e.timer.update().getDelta())),e.postProcessingComposer?e.postProcessingComposer.render():e.renderer.render(e.scene,e.camera),e.extraRenderers.forEach(t=>t.render(e.scene,e.camera));const t=+new Date;if(e.enablePointerInteraction&&t-e.lastRaycasterCheck>=e.pointerRaycasterThrottleMs){e.lastRaycasterCheck=t;let s=null;if(e.hoverDuringDrag||!e.isPointerDragging){const t=this.intersectingObjects(e.pointerPos.x,e.pointerPos.y);e.hoverOrderComparator&&t.sort((t,s)=>e.hoverOrderComparator(t.object,s.object));const i=t.find(t=>e.hoverFilter(t.object))||null;s=i?i.object:null,e.intersection=i||null}s!==e.hoverObj&&(e.onHover(s,e.hoverObj,e.intersection),e.tooltip.content(s&&function(e){return"function"==typeof e?e:"string"==typeof e?function(t){return t[e]}:function(t){return e}}(e.tooltipContent)(s,e.intersection)||null),e.hoverObj=s)}e.tweenGroup.update()}return this},getPointerPos:function(e){const{x:t,y:s}=e.pointerPos;return{x:t,y:s}},cameraPosition:function(e,t,s,i){const r=e.camera;if(t&&e.initialised){const l=t,h=s||{x:0,y:0,z:0};if(e.povPosTween?.end(),e.povTgtTween?.end(),i){const t=Object.assign({},r.position),s=o();e.tweenGroup.add(e.povPosTween=new _R(t).to(l,i).easing(pR.Quadratic.Out).onUpdate(n).onComplete(function(){e.povPosTween=void 0,e.tweenGroup.remove(this)}).start()),e.tweenGroup.add(e.povTgtTween=new _R(s).to(h,i/3).easing(pR.Quadratic.Out).onUpdate(a).onComplete(function(){e.povTgtTween=void 0,e.tweenGroup.remove(this)}).start())}else n(l),a(h);return this}return Object.assign({},r.position,{lookAt:o()});function n(e){const{x:t,y:s,z:i}=e;void 0!==t&&(r.position.x=t),void 0!==s&&(r.position.y=s),void 0!==i&&(r.position.z=i)}function a(t){const s=new nF.Vector3(t.x,t.y,t.z);e.controls.enabled&&e.controls.target?e.controls.target=s:r.lookAt(s)}function o(){return Object.assign(new nF.Vector3(0,0,-1e3).applyQuaternion(r.quaternion).add(r.position))}},zoomToFit:function(e,t=0,s=10,i,r){return this.fitToBbox(this.getBbox(i),t,s,r)},fitToBbox:function(e,t,s=0,i=10,r=!1){const n=e.camera;if(t){n.updateMatrixWorld();const a=new nF.Vector3,o=new nF.Vector3,l=new nF.Vector3,h=new nF.Vector3;n.getWorldPosition(h),n.getWorldDirection(l),a.crossVectors(l,n.up).normalize(),o.crossVectors(a,l).normalize();const u=(1-2*i/e.height)*n.fov/2*(Math.PI/180),c=Math.atan(Math.tan(u)*n.aspect),d=new nF.Vector3((t.x[0]+t.x[1])/2,(t.y[0]+t.y[1])/2,(t.z[0]+t.z[1])/2),p=r?l.clone().multiplyScalar(h.distanceTo(d)).add(h):d,m=Math.max(0,...[new nF.Vector3(t.x[0],t.y[0],t.z[0]),new nF.Vector3(t.x[0],t.y[0],t.z[1]),new nF.Vector3(t.x[0],t.y[1],t.z[0]),new nF.Vector3(t.x[0],t.y[1],t.z[1]),new nF.Vector3(t.x[1],t.y[0],t.z[0]),new nF.Vector3(t.x[1],t.y[0],t.z[1]),new nF.Vector3(t.x[1],t.y[1],t.z[0]),new nF.Vector3(t.x[1],t.y[1],t.z[1])].map(e=>{const t=e.clone().sub(p);return Math.max(Math.abs(t.dot(o))/Math.tan(u),Math.abs(t.dot(a))/Math.tan(c))-t.dot(l)})),f=l.clone().negate(),g={x:p.x+f.x*m,y:p.y+f.y*m,z:p.z+f.z*m};this.cameraPosition(g,p,s)}return this},getBbox:function(e,t=()=>!0){const s=new nF.Box3,i=e.objects.filter(t);return i.length?(i.forEach(e=>s.expandByObject(e)),Object.assign(...["x","y","z"].map(e=>({[e]:[s.min[e],s.max[e]]})))):null},getScreenCoords:function(e,t,s,i){const r=new nF.Vector3(t,s,i);return r.project(this.camera()),{x:(r.x+1)*e.width/2,y:-(r.y-1)*e.height/2}},getSceneCoords:function(e,t,s,i=0){const r=new nF.Vector2(t/e.width*2-1,-s/e.height*2+1),n=new nF.Raycaster;return n.setFromCamera(r,e.camera),Object.assign({},n.ray.at(i,new nF.Vector3))},intersectingObjects:function(e,t,s){const i=new nF.Vector2(t/e.width*2-1,-s/e.height*2+1),r=new nF.Raycaster;return r.params.Line.threshold=e.lineHoverPrecision,r.params.Points.threshold=e.pointsHoverPrecision,r.setFromCamera(i,e.camera),r.intersectObjects(e.objects,!0)},renderer:e=>e.renderer,scene:e=>e.scene,camera:e=>e.camera,postProcessingComposer:e=>e.postProcessingComposer,controls:e=>e.controls,tbControls:e=>e.controls,_destructor:function(e){(e=>{for(;e.children.length;){const t=e.children[0];e.remove(t),rF(t)}})(e.scene),e.controls?.dispose(),e.renderer?.dispose(),e.postProcessingComposer?.dispose()}},stateInit:()=>({scene:new nF.Scene,camera:new nF.PerspectiveCamera,timer:new nF.Timer,tweenGroup:new fR,lastRaycasterCheck:0}),init(e,t,{controlType:s="trackball",useWebGPU:i=!1,rendererConfig:r={},extraRenderers:n=[],waitForLoadComplete:a=!0}={}){e.innerHTML="",e.appendChild(t.container=document.createElement("div")),t.container.className="scene-container",t.container.style.position="relative",t.container.appendChild(t.navInfo=document.createElement("div")),t.navInfo.className="scene-nav-info",t.navInfo.textContent={orbit:"Left-click: rotate, Mouse-wheel/middle-click: zoom, Right-click: pan",trackball:"Left-click: rotate, Mouse-wheel/middle-click: zoom, Right-click: pan",fly:"WASD: move, R|F: up | down, Q|E: roll, up|down: pitch, left|right: yaw"}[s]||"",t.navInfo.style.display=t.showNavInfo?null:"none",t.tooltip=new sF(t.container),t.pointerPos=new nF.Vector2,t.pointerPos.x=-2,t.pointerPos.y=-2,["pointermove","pointerdown"].forEach(e=>t.container.addEventListener(e,s=>{if("pointerdown"===e&&(t.isPointerPressed=!0),!t.isPointerDragging&&"pointermove"===s.type&&(s.pressure>0||t.isPointerPressed)&&("mouse"===s.pointerType||void 0===s.movementX||[s.movementX,s.movementY].some(e=>Math.abs(e)>1))&&(t.isPointerDragging=!0),t.enablePointerInteraction){const e=function(e){const t=e.getBoundingClientRect(),s=window.pageXOffset||document.documentElement.scrollLeft,i=window.pageYOffset||document.documentElement.scrollTop;return{top:t.top+i,left:t.left+s}}(t.container);t.pointerPos.x=s.pageX-e.left,t.pointerPos.y=s.pageY-e.top}},{passive:!0})),t.container.addEventListener("pointerup",e=>{t.isPointerPressed&&(t.isPointerPressed=!1,t.isPointerDragging&&(t.isPointerDragging=!1,!t.clickAfterDrag)||requestAnimationFrame(()=>{0===e.button&&t.onClick(t.hoverObj||null,e,t.intersection),2===e.button&&t.onRightClick&&t.onRightClick(t.hoverObj||null,e,t.intersection)}))},{passive:!0,capture:!0}),t.container.addEventListener("contextmenu",e=>{t.onRightClick&&e.preventDefault()}),t.renderer=new(i?KA:nF.WebGLRenderer)(Object.assign({antialias:!0,alpha:!0},r)),t.renderer.setPixelRatio(Math.min(2,window.devicePixelRatio)),t.container.appendChild(t.renderer.domElement),t.extraRenderers=n,t.extraRenderers.forEach(e=>{e.domElement.style.position="absolute",e.domElement.style.top="0px",e.domElement.style.pointerEvents="none",t.container.appendChild(e.domElement)}),t.postProcessingComposer=new NC(t.renderer),t.postProcessingComposer.addPass(new CC(t.scene,t.camera)),t.controls=new{trackball:yN,orbit:YN,fly:cC}[s](t.camera,t.renderer.domElement),"fly"===s&&(t.controls.movementSpeed=300,t.controls.rollSpeed=Math.PI/6,t.controls.dragToLook=!0),"trackball"!==s&&"orbit"!==s||(t.controls.minDistance=.1,t.controls.maxDistance=t.skyRadius,t.controls.addEventListener("start",()=>{t.controlsEngaged=!0}),t.controls.addEventListener("change",()=>{t.controlsEngaged&&(t.controlsDragging=!0)}),t.controls.addEventListener("end",()=>{t.controlsEngaged=!1,t.controlsDragging=!1})),[t.renderer,t.postProcessingComposer,...t.extraRenderers].forEach(e=>e.setSize(t.width,t.height)),t.camera.aspect=t.width/t.height,t.camera.updateProjectionMatrix(),t.camera.position.z=1e3,t.scene.add(t.skysphere=new nF.Mesh),t.skysphere.visible=!1,t.loadComplete=t.scene.visible=!a,window.scene=t.scene},update(e,t){if(e.width&&e.height&&(t.hasOwnProperty("width")||t.hasOwnProperty("height"))){const t=e.width,s=e.height;e.container.style.width=`${t}px`,e.container.style.height=`${s}px`,[e.renderer,e.postProcessingComposer,...e.extraRenderers].forEach(e=>e.setSize(t,s)),e.camera.aspect=t/s;const i=e.viewOffset.slice(0,2);i.some(e=>e)&&e.camera.setViewOffset(t,s,...i,t,s),e.camera.updateProjectionMatrix()}if(t.hasOwnProperty("viewOffset")){const t=e.width,s=e.height,i=e.viewOffset.slice(0,2);i.some(e=>e)?e.camera.setViewOffset(t,s,...i,t,s):e.camera.clearViewOffset()}if(t.hasOwnProperty("skyRadius")&&e.skyRadius&&(e.controls.hasOwnProperty("maxDistance")&&t.skyRadius&&(e.controls.maxDistance=Math.min(e.controls.maxDistance,e.skyRadius)),e.camera.far=2.5*e.skyRadius,e.camera.updateProjectionMatrix(),e.skysphere.geometry=new nF.SphereGeometry(e.skyRadius)),t.hasOwnProperty("backgroundColor")){let t=KC(e.backgroundColor).alpha;void 0===t&&(t=1),e.renderer.setClearColor(new nF.Color(dR(1,e.backgroundColor)),t)}function s(){e.loadComplete=e.scene.visible=!0}t.hasOwnProperty("backgroundImageUrl")&&(e.backgroundImageUrl?(new nF.TextureLoader).load(e.backgroundImageUrl,t=>{t.colorSpace=nF.SRGBColorSpace,e.skysphere.material=new nF.MeshBasicMaterial({map:t,side:nF.BackSide}),e.skysphere.visible=!0,e.onBackgroundImageLoaded&&setTimeout(e.onBackgroundImageLoaded),!e.loadComplete&&s()}):(e.skysphere.visible=!1,e.skysphere.material.map=null,!e.loadComplete&&s())),t.hasOwnProperty("showNavInfo")&&(e.navInfo.style.display=e.showNavInfo?null:"none"),t.hasOwnProperty("lights")&&((t.lights||[]).forEach(t=>e.scene.remove(t)),e.lights.forEach(t=>e.scene.add(t))),t.hasOwnProperty("objects")&&((t.objects||[]).forEach(t=>e.scene.remove(t)),e.objects.forEach(t=>e.scene.add(t)))}});return aF});
|