3d-force-graph 1.78.0 → 1.78.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/3d-force-graph.js +2 -2
- package/dist/3d-force-graph.js.map +1 -1
- package/dist/3d-force-graph.min.js +2 -2
- package/package.json +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
// Version 1.78.
|
|
1
|
+
// Version 1.78.2 3d-force-graph - https://github.com/vasturiano/3d-force-graph
|
|
2
2
|
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).ForceGraph3D=t()}(this,function(){"use strict";function e(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function t(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t);if("object"!=typeof r)return r;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:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function n(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function r(e){for(var r=1;r<arguments.length;r++){var i=null!=arguments[r]?arguments[r]:{};r%2?n(Object(i),!0).forEach(function(n){t(e,n,i[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):n(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}function i(t){return function(t){if(Array.isArray(t))return e(t)}(t)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(t)||function(t,n){if(t){if("string"==typeof t)return e(t,n);var r={}.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?e(t,n):void 0}}(t)||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(e,t){void 0===t&&(t={});var n=t.insertAt;if("undefined"!=typeof document){var r=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");i.type="text/css","top"===n&&r.firstChild?r.insertBefore(i,r.firstChild):r.appendChild(i),i.styleSheet?i.styleSheet.cssText=e:i.appendChild(document.createTextNode(e))}}(".graph-info-msg {\n top: 50%;\n width: 100%;\n text-align: center;\n color: lavender;\n opacity: 0.7;\n font-size: 22px;\n position: absolute;\n font-family: Sans-serif;\n}\n\n.scene-container .clickable {\n cursor: pointer;\n}\n\n.scene-container .grabbable {\n cursor: move;\n cursor: grab;\n cursor: -moz-grab;\n cursor: -webkit-grab;\n}\n\n.scene-container .grabbable:active {\n cursor: grabbing;\n cursor: -moz-grabbing;\n cursor: -webkit-grabbing;\n}");const s="178",a=0,o=1,l=2,u=0,c=1,h=2,d=3,p=0,f=1,m=2,g=100,_=101,v=102,y=200,x=201,b=202,T=203,S=204,M=205,w=206,E=207,A=208,R=209,C=210,N=211,P=212,L=213,D=214,I=0,U=1,O=2,F=3,B=4,k=5,z=6,V=7,G=301,H=302,j=303,W=304,X=306,q=1e3,$=1001,Y=1002,K=1003,Q=1004,Z=1005,J=1006,ee=1007,te=1008,ne=1009,re=1010,ie=1011,se=1012,ae=1013,oe=1014,le=1015,ue=1016,ce=1017,he=1018,de=1020,pe=35902,fe=1021,me=1022,ge=1023,_e=1026,ve=1027,ye=1028,xe=1029,be=1030,Te=1031,Se=1033,Me=33776,we=33777,Ee=33778,Ae=33779,Re=35840,Ce=35841,Ne=35842,Pe=35843,Le=36196,De=37492,Ie=37496,Ue=37808,Oe=37809,Fe=37810,Be=37811,ke=37812,ze=37813,Ve=37814,Ge=37815,He=37816,je=37817,We=37818,Xe=37819,qe=37820,$e=37821,Ye=36492,Ke=36494,Qe=36495,Ze=36283,Je=36284,et=36285,tt=36286,nt="",rt="srgb",it="srgb-linear",st="linear",at="srgb",ot=7680,lt=512,ut=513,ct=514,ht=515,dt=516,pt=517,ft=518,mt=519,gt=35044,_t=35048,vt="300 es",yt=2e3,xt=2001;class bt{addEventListener(e,t){void 0===this._listeners&&(this._listeners={});const n=this._listeners;void 0===n[e]&&(n[e]=[]),-1===n[e].indexOf(t)&&n[e].push(t)}hasEventListener(e,t){const n=this._listeners;return void 0!==n&&(void 0!==n[e]&&-1!==n[e].indexOf(t))}removeEventListener(e,t){const n=this._listeners;if(void 0===n)return;const r=n[e];if(void 0!==r){const e=r.indexOf(t);-1!==e&&r.splice(e,1)}}dispatchEvent(e){const t=this._listeners;if(void 0===t)return;const n=t[e.type];if(void 0!==n){e.target=this;const t=n.slice(0);for(let n=0,r=t.length;n<r;n++)t[n].call(this,e);e.target=null}}}const Tt=["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 St=1234567;const Mt=Math.PI/180,wt=180/Math.PI;function Et(){const e=4294967295*Math.random()|0,t=4294967295*Math.random()|0,n=4294967295*Math.random()|0,r=4294967295*Math.random()|0;return(Tt[255&e]+Tt[e>>8&255]+Tt[e>>16&255]+Tt[e>>24&255]+"-"+Tt[255&t]+Tt[t>>8&255]+"-"+Tt[t>>16&15|64]+Tt[t>>24&255]+"-"+Tt[63&n|128]+Tt[n>>8&255]+"-"+Tt[n>>16&255]+Tt[n>>24&255]+Tt[255&r]+Tt[r>>8&255]+Tt[r>>16&255]+Tt[r>>24&255]).toLowerCase()}function At(e,t,n){return Math.max(t,Math.min(n,e))}function Rt(e,t){return(e%t+t)%t}function Ct(e,t,n){return(1-n)*e+n*t}function Nt(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 Pt(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:Mt,RAD2DEG:wt,generateUUID:Et,clamp:At,euclideanModulo:Rt,mapLinear:function(e,t,n,r,i){return r+(e-t)*(i-r)/(n-t)},inverseLerp:function(e,t,n){return e!==t?(n-e)/(t-e):0},lerp:Ct,damp:function(e,t,n,r){return Ct(e,t,1-Math.exp(-n*r))},pingpong:function(e,t=1){return t-Math.abs(Rt(e,2*t)-t)},smoothstep:function(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t))*e*(3-2*e)},smootherstep:function(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-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&&(St=e);let t=St+=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*Mt},radToDeg:function(e){return e*wt},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,n,r,i){const s=Math.cos,a=Math.sin,o=s(n/2),l=a(n/2),u=s((t+r)/2),c=a((t+r)/2),h=s((t-r)/2),d=a((t-r)/2),p=s((r-t)/2),f=a((r-t)/2);switch(i){case"XYX":e.set(o*c,l*h,l*d,o*u);break;case"YZY":e.set(l*d,o*c,l*h,o*u);break;case"ZXZ":e.set(l*h,l*d,o*c,o*u);break;case"XZX":e.set(o*c,l*f,l*p,o*u);break;case"YXY":e.set(l*p,o*c,l*f,o*u);break;case"ZYZ":e.set(l*f,l*p,o*c,o*u);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+i)}},normalize:Pt,denormalize:Nt};class Dt{constructor(e=0,t=0){Dt.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,n=this.y,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6],this.y=r[1]*t+r[4]*n+r[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=At(this.x,e.x,t.x),this.y=At(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=At(this.x,e,t),this.y=At(this.y,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(At(n,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 n=this.dot(e)/t;return Math.acos(At(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y;return t*t+n*n}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,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,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 n=Math.cos(t),r=Math.sin(t),i=this.x-e.x,s=this.y-e.y;return this.x=i*n-s*r+e.x,this.y=i*r+s*n+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,n=0,r=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=r}static slerpFlat(e,t,n,r,i,s,a){let o=n[r+0],l=n[r+1],u=n[r+2],c=n[r+3];const h=i[s+0],d=i[s+1],p=i[s+2],f=i[s+3];if(0===a)return e[t+0]=o,e[t+1]=l,e[t+2]=u,void(e[t+3]=c);if(1===a)return e[t+0]=h,e[t+1]=d,e[t+2]=p,void(e[t+3]=f);if(c!==f||o!==h||l!==d||u!==p){let e=1-a;const t=o*h+l*d+u*p+c*f,n=t>=0?1:-1,r=1-t*t;if(r>Number.EPSILON){const i=Math.sqrt(r),s=Math.atan2(i,t*n);e=Math.sin(e*s)/i,a=Math.sin(a*s)/i}const i=a*n;if(o=o*e+h*i,l=l*e+d*i,u=u*e+p*i,c=c*e+f*i,e===1-a){const e=1/Math.sqrt(o*o+l*l+u*u+c*c);o*=e,l*=e,u*=e,c*=e}}e[t]=o,e[t+1]=l,e[t+2]=u,e[t+3]=c}static multiplyQuaternionsFlat(e,t,n,r,i,s){const a=n[r],o=n[r+1],l=n[r+2],u=n[r+3],c=i[s],h=i[s+1],d=i[s+2],p=i[s+3];return e[t]=a*p+u*c+o*d-l*h,e[t+1]=o*p+u*h+l*c-a*d,e[t+2]=l*p+u*d+a*h-o*c,e[t+3]=u*p-a*c-o*h-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,n,r){return this._x=e,this._y=t,this._z=n,this._w=r,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 n=e._x,r=e._y,i=e._z,s=e._order,a=Math.cos,o=Math.sin,l=a(n/2),u=a(r/2),c=a(i/2),h=o(n/2),d=o(r/2),p=o(i/2);switch(s){case"XYZ":this._x=h*u*c+l*d*p,this._y=l*d*c-h*u*p,this._z=l*u*p+h*d*c,this._w=l*u*c-h*d*p;break;case"YXZ":this._x=h*u*c+l*d*p,this._y=l*d*c-h*u*p,this._z=l*u*p-h*d*c,this._w=l*u*c+h*d*p;break;case"ZXY":this._x=h*u*c-l*d*p,this._y=l*d*c+h*u*p,this._z=l*u*p+h*d*c,this._w=l*u*c-h*d*p;break;case"ZYX":this._x=h*u*c-l*d*p,this._y=l*d*c+h*u*p,this._z=l*u*p-h*d*c,this._w=l*u*c+h*d*p;break;case"YZX":this._x=h*u*c+l*d*p,this._y=l*d*c+h*u*p,this._z=l*u*p-h*d*c,this._w=l*u*c-h*d*p;break;case"XZY":this._x=h*u*c-l*d*p,this._y=l*d*c-h*u*p,this._z=l*u*p+h*d*c,this._w=l*u*c+h*d*p;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+s)}return!0===t&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const n=t/2,r=Math.sin(n);return this._x=e.x*r,this._y=e.y*r,this._z=e.z*r,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,n=t[0],r=t[4],i=t[8],s=t[1],a=t[5],o=t[9],l=t[2],u=t[6],c=t[10],h=n+a+c;if(h>0){const e=.5/Math.sqrt(h+1);this._w=.25/e,this._x=(u-o)*e,this._y=(i-l)*e,this._z=(s-r)*e}else if(n>a&&n>c){const e=2*Math.sqrt(1+n-a-c);this._w=(u-o)/e,this._x=.25*e,this._y=(r+s)/e,this._z=(i+l)/e}else if(a>c){const e=2*Math.sqrt(1+a-n-c);this._w=(i-l)/e,this._x=(r+s)/e,this._y=.25*e,this._z=(o+u)/e}else{const e=2*Math.sqrt(1+c-n-a);this._w=(s-r)/e,this._x=(i+l)/e,this._y=(o+u)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<1e-8?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(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=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(At(this.dot(e),-1,1)))}rotateTowards(e,t){const n=this.angleTo(e);if(0===n)return this;const r=Math.min(1,t/n);return this.slerp(e,r),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 n=e._x,r=e._y,i=e._z,s=e._w,a=t._x,o=t._y,l=t._z,u=t._w;return this._x=n*u+s*a+r*l-i*o,this._y=r*u+s*o+i*a-n*l,this._z=i*u+s*l+n*o-r*a,this._w=s*u-n*a-r*o-i*l,this._onChangeCallback(),this}slerp(e,t){if(0===t)return this;if(1===t)return this.copy(e);const n=this._x,r=this._y,i=this._z,s=this._w;let a=s*e._w+n*e._x+r*e._y+i*e._z;if(a<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,a=-a):this.copy(e),a>=1)return this._w=s,this._x=n,this._y=r,this._z=i,this;const o=1-a*a;if(o<=Number.EPSILON){const e=1-t;return this._w=e*s+t*this._w,this._x=e*n+t*this._x,this._y=e*r+t*this._y,this._z=e*i+t*this._z,this.normalize(),this}const l=Math.sqrt(o),u=Math.atan2(l,a),c=Math.sin((1-t)*u)/l,h=Math.sin(t*u)/l;return this._w=s*c+this._w*h,this._x=n*c+this._x*h,this._y=r*c+this._y*h,this._z=i*c+this._z*h,this._onChangeCallback(),this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),r=Math.sqrt(1-n),i=Math.sqrt(n);return this.set(r*Math.sin(e),r*Math.cos(e),i*Math.sin(t),i*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 Ut{constructor(e=0,t=0,n=0){Ut.prototype.isVector3=!0,this.x=e,this.y=t,this.z=n}set(e,t,n){return void 0===n&&(n=this.z),this.x=e,this.y=t,this.z=n,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(Ft.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(Ft.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6]*r,this.y=i[1]*t+i[4]*n+i[7]*r,this.z=i[2]*t+i[5]*n+i[8]*r,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,n=this.y,r=this.z,i=e.elements,s=1/(i[3]*t+i[7]*n+i[11]*r+i[15]);return this.x=(i[0]*t+i[4]*n+i[8]*r+i[12])*s,this.y=(i[1]*t+i[5]*n+i[9]*r+i[13])*s,this.z=(i[2]*t+i[6]*n+i[10]*r+i[14])*s,this}applyQuaternion(e){const t=this.x,n=this.y,r=this.z,i=e.x,s=e.y,a=e.z,o=e.w,l=2*(s*r-a*n),u=2*(a*t-i*r),c=2*(i*n-s*t);return this.x=t+o*l+s*c-a*u,this.y=n+o*u+a*l-i*c,this.z=r+o*c+i*u-s*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,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[4]*n+i[8]*r,this.y=i[1]*t+i[5]*n+i[9]*r,this.z=i[2]*t+i[6]*n+i[10]*r,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=At(this.x,e.x,t.x),this.y=At(this.y,e.y,t.y),this.z=At(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=At(this.x,e,t),this.y=At(this.y,e,t),this.z=At(this.z,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(At(n,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,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const n=e.x,r=e.y,i=e.z,s=t.x,a=t.y,o=t.z;return this.x=r*o-i*a,this.y=i*s-n*o,this.z=n*a-r*s,this}projectOnVector(e){const t=e.lengthSq();if(0===t)return this.set(0,0,0);const n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return Ot.copy(this).projectOnVector(e),this.sub(Ot)}reflect(e){return this.sub(Ot.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 n=this.dot(e)/t;return Math.acos(At(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y,r=this.z-e.z;return t*t+n*n+r*r}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,n){const r=Math.sin(t)*e;return this.x=r*Math.sin(n),this.y=Math.cos(t)*e,this.z=r*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,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(),n=this.setFromMatrixColumn(e,1).length(),r=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=r,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,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const Ot=new Ut,Ft=new It;class Bt{constructor(e,t,n,r,i,s,a,o,l){Bt.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],void 0!==e&&this.set(e,t,n,r,i,s,a,o,l)}set(e,t,n,r,i,s,a,o,l){const u=this.elements;return u[0]=e,u[1]=r,u[2]=a,u[3]=t,u[4]=i,u[5]=o,u[6]=n,u[7]=s,u[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.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 n=e.elements,r=t.elements,i=this.elements,s=n[0],a=n[3],o=n[6],l=n[1],u=n[4],c=n[7],h=n[2],d=n[5],p=n[8],f=r[0],m=r[3],g=r[6],_=r[1],v=r[4],y=r[7],x=r[2],b=r[5],T=r[8];return i[0]=s*f+a*_+o*x,i[3]=s*m+a*v+o*b,i[6]=s*g+a*y+o*T,i[1]=l*f+u*_+c*x,i[4]=l*m+u*v+c*b,i[7]=l*g+u*y+c*T,i[2]=h*f+d*_+p*x,i[5]=h*m+d*v+p*b,i[8]=h*g+d*y+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],n=e[1],r=e[2],i=e[3],s=e[4],a=e[5],o=e[6],l=e[7],u=e[8];return t*s*u-t*a*l-n*i*u+n*a*o+r*i*l-r*s*o}invert(){const e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],s=e[4],a=e[5],o=e[6],l=e[7],u=e[8],c=u*s-a*l,h=a*o-u*i,d=l*i-s*o,p=t*c+n*h+r*d;if(0===p)return this.set(0,0,0,0,0,0,0,0,0);const f=1/p;return e[0]=c*f,e[1]=(r*l-u*n)*f,e[2]=(a*n-r*s)*f,e[3]=h*f,e[4]=(u*t-r*o)*f,e[5]=(r*i-a*t)*f,e[6]=d*f,e[7]=(n*o-l*t)*f,e[8]=(s*t-n*i)*f,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,n,r,i,s,a){const o=Math.cos(i),l=Math.sin(i);return this.set(n*o,n*l,-n*(o*s+l*a)+s+e,-r*l,r*o,-r*(-l*s+o*a)+a+t,0,0,1),this}scale(e,t){return this.premultiply(kt.makeScale(e,t)),this}rotate(e){return this.premultiply(kt.makeRotation(-e)),this}translate(e,t){return this.premultiply(kt.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),n=Math.sin(e);return this.set(t,-n,0,n,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,n=e.elements;for(let e=0;e<9;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return(new this.constructor).fromArray(this.elements)}}const kt=new Bt;function zt(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}function Vt(e){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}function Gt(){const e=Vt("canvas");return e.style.display="block",e}const Ht={};function jt(e){e in Ht||(Ht[e]=!0,console.warn(e))}const Wt=(new Bt).set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),Xt=(new Bt).set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function qt(){const e={enabled:!0,workingColorSpace:it,spaces:{},convert:function(e,t,n){return!1!==this.enabled&&t!==n&&t&&n?(this.spaces[t].transfer===at&&(e.r=Yt(e.r),e.g=Yt(e.g),e.b=Yt(e.b)),this.spaces[t].primaries!==this.spaces[n].primaries&&(e.applyMatrix3(this.spaces[t].toXYZ),e.applyMatrix3(this.spaces[n].fromXYZ)),this.spaces[n].transfer===at&&(e.r=Kt(e.r),e.g=Kt(e.g),e.b=Kt(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===nt?st:this.spaces[e].transfer},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,n){return e.copy(this.spaces[t].toXYZ).multiply(this.spaces[n].fromXYZ)},_getDrawingBufferColorSpace:function(e){return this.spaces[e].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(e=this.workingColorSpace){return this.spaces[e].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(t,n){return jt("THREE.ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),e.workingToColorSpace(t,n)},toWorkingColorSpace:function(t,n){return jt("THREE.ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),e.colorSpaceToWorking(t,n)}},t=[.64,.33,.3,.6,.15,.06],n=[.2126,.7152,.0722],r=[.3127,.329];return e.define({[it]:{primaries:t,whitePoint:r,transfer:st,toXYZ:Wt,fromXYZ:Xt,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:rt},outputColorSpaceConfig:{drawingBufferColorSpace:rt}},[rt]:{primaries:t,whitePoint:r,transfer:at,toXYZ:Wt,fromXYZ:Xt,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:rt}}}),e}const $t=qt();function Yt(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}function Kt(e){return e<.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}let Qt;class Zt{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src))return e.src;if("undefined"==typeof HTMLCanvasElement)return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{void 0===Qt&&(Qt=Vt("canvas")),Qt.width=e.width,Qt.height=e.height;const t=Qt.getContext("2d");e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),n=Qt}return n.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=Vt("canvas");t.width=e.width,t.height=e.height;const n=t.getContext("2d");n.drawImage(e,0,0,e.width,e.height);const r=n.getImageData(0,0,e.width,e.height),i=r.data;for(let e=0;e<i.length;e++)i[e]=255*Yt(i[e]/255);return n.putImageData(r,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*Yt(t[e]/255)):t[e]=Yt(t[e]);return{data:t,width:e.width,height:e.height}}return console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let Jt=0;class en{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:Jt++}),this.uuid=Et(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){const t=this.data;return t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight):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 n={uuid:this.uuid,url:""},r=this.data;if(null!==r){let e;if(Array.isArray(r)){e=[];for(let t=0,n=r.length;t<n;t++)r[t].isDataTexture?e.push(tn(r[t].image)):e.push(tn(r[t]))}else e=tn(r);n.url=e}return t||(e.images[this.uuid]=n),n}}function tn(e){return"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?Zt.getDataURL(e):e.data?{data:Array.from(e.data),width:e.width,height:e.height,type:e.data.constructor.name}:(console.warn("THREE.Texture: Unable to serialize Texture."),{})}let nn=0;const rn=new Ut;class sn extends bt{constructor(e=sn.DEFAULT_IMAGE,t=sn.DEFAULT_MAPPING,n=1001,r=1001,i=1006,s=1008,a=1023,o=1009,l=sn.DEFAULT_ANISOTROPY,u=""){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:nn++}),this.uuid=Et(),this.name="",this.source=new en(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=n,this.wrapT=r,this.magFilter=i,this.minFilter=s,this.anisotropy=l,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 Bt,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=u,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(e&&e.depth&&e.depth>1),this.pmremVersion=0}get width(){return this.source.getSize(rn).x}get height(){return this.source.getSize(rn).y}get depth(){return this.source.getSize(rn).z}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return(new this.constructor).copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(const t in e){const n=e[t];if(void 0===n){console.warn(`THREE.Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const r=this[t];void 0!==r?r&&n&&r.isVector2&&n.isVector2||r&&n&&r.isVector3&&n.isVector3||r&&n&&r.isMatrix3&&n.isMatrix3?r.copy(n):this[t]=n:console.warn(`THREE.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 n={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}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 q:e.x=e.x-Math.floor(e.x);break;case $:e.x=e.x<0?0:1;break;case Y: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 q:e.y=e.y-Math.floor(e.y);break;case $:e.y=e.y<0?0:1;break;case Y: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++}}sn.DEFAULT_IMAGE=null,sn.DEFAULT_MAPPING=300,sn.DEFAULT_ANISOTROPY=1;class an{constructor(e=0,t=0,n=0,r=1){an.prototype.isVector4=!0,this.x=e,this.y=t,this.z=n,this.w=r}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,n,r){return this.x=e,this.y=t,this.z=n,this.w=r,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,n=this.y,r=this.z,i=this.w,s=e.elements;return this.x=s[0]*t+s[4]*n+s[8]*r+s[12]*i,this.y=s[1]*t+s[5]*n+s[9]*r+s[13]*i,this.z=s[2]*t+s[6]*n+s[10]*r+s[14]*i,this.w=s[3]*t+s[7]*n+s[11]*r+s[15]*i,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,n,r,i;const s=.01,a=.1,o=e.elements,l=o[0],u=o[4],c=o[8],h=o[1],d=o[5],p=o[9],f=o[2],m=o[6],g=o[10];if(Math.abs(u-h)<s&&Math.abs(c-f)<s&&Math.abs(p-m)<s){if(Math.abs(u+h)<a&&Math.abs(c+f)<a&&Math.abs(p+m)<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,_=(g+1)/2,v=(u+h)/4,y=(c+f)/4,x=(p+m)/4;return e>o&&e>_?e<s?(n=0,r=.707106781,i=.707106781):(n=Math.sqrt(e),r=v/n,i=y/n):o>_?o<s?(n=.707106781,r=0,i=.707106781):(r=Math.sqrt(o),n=v/r,i=x/r):_<s?(n=.707106781,r=.707106781,i=0):(i=Math.sqrt(_),n=y/i,r=x/i),this.set(n,r,i,t),this}let _=Math.sqrt((m-p)*(m-p)+(c-f)*(c-f)+(h-u)*(h-u));return Math.abs(_)<.001&&(_=1),this.x=(m-p)/_,this.y=(c-f)/_,this.z=(h-u)/_,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=At(this.x,e.x,t.x),this.y=At(this.y,e.y,t.y),this.z=At(this.z,e.z,t.z),this.w=At(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=At(this.x,e,t),this.y=At(this.y,e,t),this.z=At(this.z,e,t),this.w=At(this.w,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(At(n,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,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this.w=e.w+(t.w-e.w)*n,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 on extends bt{constructor(e=1,t=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:J,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},n),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth,this.scissor=new an(0,0,e,t),this.scissorTest=!1,this.viewport=new an(0,0,e,t);const r={width:e,height:t,depth:n.depth},i=new sn(r);this.textures=[];const s=n.count;for(let e=0;e<s;e++)this.textures[e]=i.clone(),this.textures[e].isRenderTargetTexture=!0,this.textures[e].renderTarget=this;this._setTextureOptions(n),this.depthBuffer=n.depthBuffer,this.stencilBuffer=n.stencilBuffer,this.resolveDepthBuffer=n.resolveDepthBuffer,this.resolveStencilBuffer=n.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=n.depthTexture,this.samples=n.samples,this.multiview=n.multiview}_setTextureOptions(e={}){const t={minFilter:J,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,n=1){if(this.width!==e||this.height!==t||this.depth!==n){this.width=e,this.height=t,this.depth=n;for(let r=0,i=this.textures.length;r<i;r++)this.textures[r].image.width=e,this.textures[r].image.height=t,this.textures[r].image.depth=n,this.textures[r].isArrayTexture=this.textures[r].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,n=e.textures.length;t<n;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;const n=Object.assign({},e.textures[t].image);this.textures[t].source=new en(n)}return this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,null!==e.depthTexture&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this}dispose(){this.dispatchEvent({type:"dispose"})}}class ln extends on{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}}class un extends sn{constructor(e=null,t=1,n=1,r=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:n,depth:r},this.magFilter=K,this.minFilter=K,this.wrapR=$,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class cn extends sn{constructor(e=null,t=1,n=1,r=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:n,depth:r},this.magFilter=K,this.minFilter=K,this.wrapR=$,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class hn{constructor(e=new Ut(1/0,1/0,1/0),t=new Ut(-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,n=e.length;t<n;t+=3)this.expandByPoint(pn.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(pn.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){const n=pn.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(n),this.max.copy(e).add(n),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 n=e.geometry;if(void 0!==n){const r=n.getAttribute("position");if(!0===t&&void 0!==r&&!0!==e.isInstancedMesh)for(let t=0,n=r.count;t<n;t++)!0===e.isMesh?e.getVertexPosition(t,pn):pn.fromBufferAttribute(r,t),pn.applyMatrix4(e.matrixWorld),this.expandByPoint(pn);else void 0!==e.boundingBox?(null===e.boundingBox&&e.computeBoundingBox(),fn.copy(e.boundingBox)):(null===n.boundingBox&&n.computeBoundingBox(),fn.copy(n.boundingBox)),fn.applyMatrix4(e.matrixWorld),this.union(fn)}const r=e.children;for(let e=0,n=r.length;e<n;e++)this.expandByObject(r[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,pn),pn.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(bn),Tn.subVectors(this.max,bn),mn.subVectors(e.a,bn),gn.subVectors(e.b,bn),_n.subVectors(e.c,bn),vn.subVectors(gn,mn),yn.subVectors(_n,gn),xn.subVectors(mn,_n);let t=[0,-vn.z,vn.y,0,-yn.z,yn.y,0,-xn.z,xn.y,vn.z,0,-vn.x,yn.z,0,-yn.x,xn.z,0,-xn.x,-vn.y,vn.x,0,-yn.y,yn.x,0,-xn.y,xn.x,0];return!!wn(t,mn,gn,_n,Tn)&&(t=[1,0,0,0,1,0,0,0,1],!!wn(t,mn,gn,_n,Tn)&&(Sn.crossVectors(vn,yn),t=[Sn.x,Sn.y,Sn.z],wn(t,mn,gn,_n,Tn)))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,pn).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=.5*this.getSize(pn).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()||(dn[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),dn[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),dn[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),dn[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),dn[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),dn[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),dn[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),dn[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(dn)),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 dn=[new Ut,new Ut,new Ut,new Ut,new Ut,new Ut,new Ut,new Ut],pn=new Ut,fn=new hn,mn=new Ut,gn=new Ut,_n=new Ut,vn=new Ut,yn=new Ut,xn=new Ut,bn=new Ut,Tn=new Ut,Sn=new Ut,Mn=new Ut;function wn(e,t,n,r,i){for(let s=0,a=e.length-3;s<=a;s+=3){Mn.fromArray(e,s);const a=i.x*Math.abs(Mn.x)+i.y*Math.abs(Mn.y)+i.z*Math.abs(Mn.z),o=t.dot(Mn),l=n.dot(Mn),u=r.dot(Mn);if(Math.max(-Math.max(o,l,u),Math.min(o,l,u))>a)return!1}return!0}const En=new hn,An=new Ut,Rn=new Ut;class Cn{constructor(e=new Ut,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 n=this.center;void 0!==t?n.copy(t):En.setFromPoints(e).getCenter(n);let r=0;for(let t=0,i=e.length;t<i;t++)r=Math.max(r,n.distanceToSquared(e[t]));return this.radius=Math.sqrt(r),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 n=this.center.distanceToSquared(e);return t.copy(e),n>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;An.subVectors(e,this.center);const t=An.lengthSq();if(t>this.radius*this.radius){const e=Math.sqrt(t),n=.5*(e-this.radius);this.center.addScaledVector(An,n/e),this.radius+=n}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):(Rn.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(An.copy(e.center).add(Rn)),this.expandByPoint(An.copy(e.center).sub(Rn))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return(new this.constructor).copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}}const Nn=new Ut,Pn=new Ut,Ln=new Ut,Dn=new Ut,In=new Ut,Un=new Ut,On=new Ut;class Fn{constructor(e=new Ut,t=new Ut(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,Nn)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=Nn.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Nn.copy(this.origin).addScaledVector(this.direction,t),Nn.distanceToSquared(e))}distanceSqToSegment(e,t,n,r){Pn.copy(e).add(t).multiplyScalar(.5),Ln.copy(t).sub(e).normalize(),Dn.copy(this.origin).sub(Pn);const i=.5*e.distanceTo(t),s=-this.direction.dot(Ln),a=Dn.dot(this.direction),o=-Dn.dot(Ln),l=Dn.lengthSq(),u=Math.abs(1-s*s);let c,h,d,p;if(u>0)if(c=s*o-a,h=s*a-o,p=i*u,c>=0)if(h>=-p)if(h<=p){const e=1/u;c*=e,h*=e,d=c*(c+s*h+2*a)+h*(s*c+h+2*o)+l}else h=i,c=Math.max(0,-(s*h+a)),d=-c*c+h*(h+2*o)+l;else h=-i,c=Math.max(0,-(s*h+a)),d=-c*c+h*(h+2*o)+l;else h<=-p?(c=Math.max(0,-(-s*i+a)),h=c>0?-i:Math.min(Math.max(-i,-o),i),d=-c*c+h*(h+2*o)+l):h<=p?(c=0,h=Math.min(Math.max(-i,-o),i),d=h*(h+2*o)+l):(c=Math.max(0,-(s*i+a)),h=c>0?i:Math.min(Math.max(-i,-o),i),d=-c*c+h*(h+2*o)+l);else h=s>0?-i:i,c=Math.max(0,-(s*h+a)),d=-c*c+h*(h+2*o)+l;return n&&n.copy(this.origin).addScaledVector(this.direction,c),r&&r.copy(Pn).addScaledVector(Ln,h),d}intersectSphere(e,t){Nn.subVectors(e.center,this.origin);const n=Nn.dot(this.direction),r=Nn.dot(Nn)-n*n,i=e.radius*e.radius;if(r>i)return null;const s=Math.sqrt(i-r),a=n-s,o=n+s;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 n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){const n=this.distanceToPlane(e);return null===n?null:this.at(n,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 n,r,i,s,a,o;const l=1/this.direction.x,u=1/this.direction.y,c=1/this.direction.z,h=this.origin;return l>=0?(n=(e.min.x-h.x)*l,r=(e.max.x-h.x)*l):(n=(e.max.x-h.x)*l,r=(e.min.x-h.x)*l),u>=0?(i=(e.min.y-h.y)*u,s=(e.max.y-h.y)*u):(i=(e.max.y-h.y)*u,s=(e.min.y-h.y)*u),n>s||i>r?null:((i>n||isNaN(n))&&(n=i),(s<r||isNaN(r))&&(r=s),c>=0?(a=(e.min.z-h.z)*c,o=(e.max.z-h.z)*c):(a=(e.max.z-h.z)*c,o=(e.min.z-h.z)*c),n>o||a>r?null:((a>n||n!=n)&&(n=a),(o<r||r!=r)&&(r=o),r<0?null:this.at(n>=0?n:r,t)))}intersectsBox(e){return null!==this.intersectBox(e,Nn)}intersectTriangle(e,t,n,r,i){In.subVectors(t,e),Un.subVectors(n,e),On.crossVectors(In,Un);let s,a=this.direction.dot(On);if(a>0){if(r)return null;s=1}else{if(!(a<0))return null;s=-1,a=-a}Dn.subVectors(this.origin,e);const o=s*this.direction.dot(Un.crossVectors(Dn,Un));if(o<0)return null;const l=s*this.direction.dot(In.cross(Dn));if(l<0)return null;if(o+l>a)return null;const u=-s*Dn.dot(On);return u<0?null:this.at(u/a,i)}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 Bn{constructor(e,t,n,r,i,s,a,o,l,u,c,h,d,p,f,m){Bn.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],void 0!==e&&this.set(e,t,n,r,i,s,a,o,l,u,c,h,d,p,f,m)}set(e,t,n,r,i,s,a,o,l,u,c,h,d,p,f,m){const g=this.elements;return g[0]=e,g[4]=t,g[8]=n,g[12]=r,g[1]=i,g[5]=s,g[9]=a,g[13]=o,g[2]=l,g[6]=u,g[10]=c,g[14]=h,g[3]=d,g[7]=p,g[11]=f,g[15]=m,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 Bn).fromArray(this.elements)}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){const t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[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,n){return e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){const t=this.elements,n=e.elements,r=1/kn.setFromMatrixColumn(e,0).length(),i=1/kn.setFromMatrixColumn(e,1).length(),s=1/kn.setFromMatrixColumn(e,2).length();return t[0]=n[0]*r,t[1]=n[1]*r,t[2]=n[2]*r,t[3]=0,t[4]=n[4]*i,t[5]=n[5]*i,t[6]=n[6]*i,t[7]=0,t[8]=n[8]*s,t[9]=n[9]*s,t[10]=n[10]*s,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,n=e.x,r=e.y,i=e.z,s=Math.cos(n),a=Math.sin(n),o=Math.cos(r),l=Math.sin(r),u=Math.cos(i),c=Math.sin(i);if("XYZ"===e.order){const e=s*u,n=s*c,r=a*u,i=a*c;t[0]=o*u,t[4]=-o*c,t[8]=l,t[1]=n+r*l,t[5]=e-i*l,t[9]=-a*o,t[2]=i-e*l,t[6]=r+n*l,t[10]=s*o}else if("YXZ"===e.order){const e=o*u,n=o*c,r=l*u,i=l*c;t[0]=e+i*a,t[4]=r*a-n,t[8]=s*l,t[1]=s*c,t[5]=s*u,t[9]=-a,t[2]=n*a-r,t[6]=i+e*a,t[10]=s*o}else if("ZXY"===e.order){const e=o*u,n=o*c,r=l*u,i=l*c;t[0]=e-i*a,t[4]=-s*c,t[8]=r+n*a,t[1]=n+r*a,t[5]=s*u,t[9]=i-e*a,t[2]=-s*l,t[6]=a,t[10]=s*o}else if("ZYX"===e.order){const e=s*u,n=s*c,r=a*u,i=a*c;t[0]=o*u,t[4]=r*l-n,t[8]=e*l+i,t[1]=o*c,t[5]=i*l+e,t[9]=n*l-r,t[2]=-l,t[6]=a*o,t[10]=s*o}else if("YZX"===e.order){const e=s*o,n=s*l,r=a*o,i=a*l;t[0]=o*u,t[4]=i-e*c,t[8]=r*c+n,t[1]=c,t[5]=s*u,t[9]=-a*u,t[2]=-l*u,t[6]=n*c+r,t[10]=e-i*c}else if("XZY"===e.order){const e=s*o,n=s*l,r=a*o,i=a*l;t[0]=o*u,t[4]=-c,t[8]=l*u,t[1]=e*c+i,t[5]=s*u,t[9]=n*c-r,t[2]=r*c-n,t[6]=a*u,t[10]=i*c+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(Vn,e,Gn)}lookAt(e,t,n){const r=this.elements;return Wn.subVectors(e,t),0===Wn.lengthSq()&&(Wn.z=1),Wn.normalize(),Hn.crossVectors(n,Wn),0===Hn.lengthSq()&&(1===Math.abs(n.z)?Wn.x+=1e-4:Wn.z+=1e-4,Wn.normalize(),Hn.crossVectors(n,Wn)),Hn.normalize(),jn.crossVectors(Wn,Hn),r[0]=Hn.x,r[4]=jn.x,r[8]=Wn.x,r[1]=Hn.y,r[5]=jn.y,r[9]=Wn.y,r[2]=Hn.z,r[6]=jn.z,r[10]=Wn.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,r=t.elements,i=this.elements,s=n[0],a=n[4],o=n[8],l=n[12],u=n[1],c=n[5],h=n[9],d=n[13],p=n[2],f=n[6],m=n[10],g=n[14],_=n[3],v=n[7],y=n[11],x=n[15],b=r[0],T=r[4],S=r[8],M=r[12],w=r[1],E=r[5],A=r[9],R=r[13],C=r[2],N=r[6],P=r[10],L=r[14],D=r[3],I=r[7],U=r[11],O=r[15];return i[0]=s*b+a*w+o*C+l*D,i[4]=s*T+a*E+o*N+l*I,i[8]=s*S+a*A+o*P+l*U,i[12]=s*M+a*R+o*L+l*O,i[1]=u*b+c*w+h*C+d*D,i[5]=u*T+c*E+h*N+d*I,i[9]=u*S+c*A+h*P+d*U,i[13]=u*M+c*R+h*L+d*O,i[2]=p*b+f*w+m*C+g*D,i[6]=p*T+f*E+m*N+g*I,i[10]=p*S+f*A+m*P+g*U,i[14]=p*M+f*R+m*L+g*O,i[3]=_*b+v*w+y*C+x*D,i[7]=_*T+v*E+y*N+x*I,i[11]=_*S+v*A+y*P+x*U,i[15]=_*M+v*R+y*L+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],n=e[4],r=e[8],i=e[12],s=e[1],a=e[5],o=e[9],l=e[13],u=e[2],c=e[6],h=e[10],d=e[14];return e[3]*(+i*o*c-r*l*c-i*a*h+n*l*h+r*a*d-n*o*d)+e[7]*(+t*o*d-t*l*h+i*s*h-r*s*d+r*l*u-i*o*u)+e[11]*(+t*l*c-t*a*d-i*s*c+n*s*d+i*a*u-n*l*u)+e[15]*(-r*a*u-t*o*c+t*a*h+r*s*c-n*s*h+n*o*u)}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,n){const r=this.elements;return e.isVector3?(r[12]=e.x,r[13]=e.y,r[14]=e.z):(r[12]=e,r[13]=t,r[14]=n),this}invert(){const e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],s=e[4],a=e[5],o=e[6],l=e[7],u=e[8],c=e[9],h=e[10],d=e[11],p=e[12],f=e[13],m=e[14],g=e[15],_=c*m*l-f*h*l+f*o*d-a*m*d-c*o*g+a*h*g,v=p*h*l-u*m*l-p*o*d+s*m*d+u*o*g-s*h*g,y=u*f*l-p*c*l+p*a*d-s*f*d-u*a*g+s*c*g,x=p*c*o-u*f*o-p*a*h+s*f*h+u*a*m-s*c*m,b=t*_+n*v+r*y+i*x;if(0===b)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const T=1/b;return e[0]=_*T,e[1]=(f*h*i-c*m*i-f*r*d+n*m*d+c*r*g-n*h*g)*T,e[2]=(a*m*i-f*o*i+f*r*l-n*m*l-a*r*g+n*o*g)*T,e[3]=(c*o*i-a*h*i-c*r*l+n*h*l+a*r*d-n*o*d)*T,e[4]=v*T,e[5]=(u*m*i-p*h*i+p*r*d-t*m*d-u*r*g+t*h*g)*T,e[6]=(p*o*i-s*m*i-p*r*l+t*m*l+s*r*g-t*o*g)*T,e[7]=(s*h*i-u*o*i+u*r*l-t*h*l-s*r*d+t*o*d)*T,e[8]=y*T,e[9]=(p*c*i-u*f*i-p*n*d+t*f*d+u*n*g-t*c*g)*T,e[10]=(s*f*i-p*a*i+p*n*l-t*f*l-s*n*g+t*a*g)*T,e[11]=(u*a*i-s*c*i-u*n*l+t*c*l+s*n*d-t*a*d)*T,e[12]=x*T,e[13]=(u*f*r-p*c*r+p*n*h-t*f*h-u*n*m+t*c*m)*T,e[14]=(p*a*r-s*f*r-p*n*o+t*f*o+s*n*m-t*a*m)*T,e[15]=(s*c*r-u*a*r+u*n*o-t*c*o-s*n*h+t*a*h)*T,this}scale(e){const t=this.elements,n=e.x,r=e.y,i=e.z;return t[0]*=n,t[4]*=r,t[8]*=i,t[1]*=n,t[5]*=r,t[9]*=i,t[2]*=n,t[6]*=r,t[10]*=i,t[3]*=n,t[7]*=r,t[11]*=i,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],r=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,r))}makeTranslation(e,t,n){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,n,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const n=Math.cos(t),r=Math.sin(t),i=1-n,s=e.x,a=e.y,o=e.z,l=i*s,u=i*a;return this.set(l*s+n,l*a-r*o,l*o+r*a,0,l*a+r*o,u*a+n,u*o-r*s,0,l*o-r*a,u*o+r*s,i*o*o+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,r,i,s){return this.set(1,n,i,0,e,1,s,0,t,r,1,0,0,0,0,1),this}compose(e,t,n){const r=this.elements,i=t._x,s=t._y,a=t._z,o=t._w,l=i+i,u=s+s,c=a+a,h=i*l,d=i*u,p=i*c,f=s*u,m=s*c,g=a*c,_=o*l,v=o*u,y=o*c,x=n.x,b=n.y,T=n.z;return r[0]=(1-(f+g))*x,r[1]=(d+y)*x,r[2]=(p-v)*x,r[3]=0,r[4]=(d-y)*b,r[5]=(1-(h+g))*b,r[6]=(m+_)*b,r[7]=0,r[8]=(p+v)*T,r[9]=(m-_)*T,r[10]=(1-(h+f))*T,r[11]=0,r[12]=e.x,r[13]=e.y,r[14]=e.z,r[15]=1,this}decompose(e,t,n){const r=this.elements;let i=kn.set(r[0],r[1],r[2]).length();const s=kn.set(r[4],r[5],r[6]).length(),a=kn.set(r[8],r[9],r[10]).length();this.determinant()<0&&(i=-i),e.x=r[12],e.y=r[13],e.z=r[14],zn.copy(this);const o=1/i,l=1/s,u=1/a;return zn.elements[0]*=o,zn.elements[1]*=o,zn.elements[2]*=o,zn.elements[4]*=l,zn.elements[5]*=l,zn.elements[6]*=l,zn.elements[8]*=u,zn.elements[9]*=u,zn.elements[10]*=u,t.setFromRotationMatrix(zn),n.x=i,n.y=s,n.z=a,this}makePerspective(e,t,n,r,i,s,a=2e3){const o=this.elements,l=2*i/(t-e),u=2*i/(n-r),c=(t+e)/(t-e),h=(n+r)/(n-r);let d,p;if(a===yt)d=-(s+i)/(s-i),p=-2*s*i/(s-i);else{if(a!==xt)throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);d=-s/(s-i),p=-s*i/(s-i)}return o[0]=l,o[4]=0,o[8]=c,o[12]=0,o[1]=0,o[5]=u,o[9]=h,o[13]=0,o[2]=0,o[6]=0,o[10]=d,o[14]=p,o[3]=0,o[7]=0,o[11]=-1,o[15]=0,this}makeOrthographic(e,t,n,r,i,s,a=2e3){const o=this.elements,l=1/(t-e),u=1/(n-r),c=1/(s-i),h=(t+e)*l,d=(n+r)*u;let p,f;if(a===yt)p=(s+i)*c,f=-2*c;else{if(a!==xt)throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);p=i*c,f=-1*c}return o[0]=2*l,o[4]=0,o[8]=0,o[12]=-h,o[1]=0,o[5]=2*u,o[9]=0,o[13]=-d,o[2]=0,o[6]=0,o[10]=f,o[14]=-p,o[3]=0,o[7]=0,o[11]=0,o[15]=1,this}equals(e){const t=this.elements,n=e.elements;for(let e=0;e<16;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}}const kn=new Ut,zn=new Bn,Vn=new Ut(0,0,0),Gn=new Ut(1,1,1),Hn=new Ut,jn=new Ut,Wn=new Ut,Xn=new Bn,qn=new It;class $n{constructor(e=0,t=0,n=0,r=$n.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=n,this._order=r}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,n,r=this._order){return this._x=e,this._y=t,this._z=n,this._order=r,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,n=!0){const r=e.elements,i=r[0],s=r[4],a=r[8],o=r[1],l=r[5],u=r[9],c=r[2],h=r[6],d=r[10];switch(t){case"XYZ":this._y=Math.asin(At(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-u,d),this._z=Math.atan2(-s,i)):(this._x=Math.atan2(h,l),this._z=0);break;case"YXZ":this._x=Math.asin(-At(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(a,d),this._z=Math.atan2(o,l)):(this._y=Math.atan2(-c,i),this._z=0);break;case"ZXY":this._x=Math.asin(At(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(-c,d),this._z=Math.atan2(-s,l)):(this._y=0,this._z=Math.atan2(o,i));break;case"ZYX":this._y=Math.asin(-At(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(h,d),this._z=Math.atan2(o,i)):(this._x=0,this._z=Math.atan2(-s,l));break;case"YZX":this._z=Math.asin(At(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-u,l),this._y=Math.atan2(-c,i)):(this._x=0,this._y=Math.atan2(a,d));break;case"XZY":this._z=Math.asin(-At(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(h,l),this._y=Math.atan2(a,i)):(this._x=Math.atan2(-u,d),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,!0===n&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return Xn.makeRotationFromQuaternion(e),this.setFromRotationMatrix(Xn,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return qn.setFromEuler(this),this.setFromQuaternion(qn,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}}$n.DEFAULT_ORDER="XYZ";class Yn{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 Kn=0;const Qn=new Ut,Zn=new It,Jn=new Bn,er=new Ut,tr=new Ut,nr=new Ut,rr=new It,ir=new Ut(1,0,0),sr=new Ut(0,1,0),ar=new Ut(0,0,1),or={type:"added"},lr={type:"removed"},ur={type:"childadded",child:null},cr={type:"childremoved",child:null};class hr extends bt{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:Kn++}),this.uuid=Et(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=hr.DEFAULT_UP.clone();const e=new Ut,t=new $n,n=new It,r=new Ut(1,1,1);t._onChange(function(){n.setFromEuler(t,!1)}),n._onChange(function(){t.setFromQuaternion(n,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:n},scale:{configurable:!0,enumerable:!0,value:r},modelViewMatrix:{value:new Bn},normalMatrix:{value:new Bt}}),this.matrix=new Bn,this.matrixWorld=new Bn,this.matrixAutoUpdate=hr.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=hr.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new Yn,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.userData={}}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return Zn.setFromAxisAngle(e,t),this.quaternion.multiply(Zn),this}rotateOnWorldAxis(e,t){return Zn.setFromAxisAngle(e,t),this.quaternion.premultiply(Zn),this}rotateX(e){return this.rotateOnAxis(ir,e)}rotateY(e){return this.rotateOnAxis(sr,e)}rotateZ(e){return this.rotateOnAxis(ar,e)}translateOnAxis(e,t){return Qn.copy(e).applyQuaternion(this.quaternion),this.position.add(Qn.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(ir,e)}translateY(e){return this.translateOnAxis(sr,e)}translateZ(e){return this.translateOnAxis(ar,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(Jn.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?er.copy(e):er.set(e,t,n);const r=this.parent;this.updateWorldMatrix(!0,!1),tr.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Jn.lookAt(tr,er,this.up):Jn.lookAt(er,tr,this.up),this.quaternion.setFromRotationMatrix(Jn),r&&(Jn.extractRotation(r.matrixWorld),Zn.setFromRotationMatrix(Jn),this.quaternion.premultiply(Zn.invert()))}add(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return e===this?(console.error("THREE.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(or),ur.child=e,this.dispatchEvent(ur),ur.child=null):console.error("THREE.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(lr),cr.child=e,this.dispatchEvent(cr),cr.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),Jn.copy(this.matrixWorld).invert(),null!==e.parent&&(e.parent.updateWorldMatrix(!0,!1),Jn.multiply(e.parent.matrixWorld)),e.applyMatrix4(Jn),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(or),ur.child=e,this.dispatchEvent(ur),ur.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 n=0,r=this.children.length;n<r;n++){const r=this.children[n].getObjectByProperty(e,t);if(void 0!==r)return r}}getObjectsByProperty(e,t,n=[]){this[e]===t&&n.push(this);const r=this.children;for(let i=0,s=r.length;i<s;i++)r[i].getObjectsByProperty(e,t,n);return n}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(tr,e,nr),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(tr,rr,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 n=0,r=t.length;n<r;n++)t[n].traverse(e)}traverseVisible(e){if(!1===this.visible)return;e(this);const t=this.children;for(let n=0,r=t.length;n<r;n++)t[n].traverseVisible(e)}traverseAncestors(e){const t=this.parent;null!==t&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(!0===this.matrixWorldAutoUpdate&&(null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);const t=this.children;for(let n=0,r=t.length;n<r;n++){t[n].updateMatrixWorld(e)}}updateWorldMatrix(e,t){const n=this.parent;if(!0===e&&null!==n&&n.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,n=e.length;t<n;t++){e[t].updateWorldMatrix(!1,!0)}}}toJSON(e){const t=void 0===e||"string"==typeof e,n={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});const r={};function i(t,n){return void 0===t[n.uuid]&&(t[n.uuid]=n.toJSON(e)),n.uuid}if(r.uuid=this.uuid,r.type=this.type,""!==this.name&&(r.name=this.name),!0===this.castShadow&&(r.castShadow=!0),!0===this.receiveShadow&&(r.receiveShadow=!0),!1===this.visible&&(r.visible=!1),!1===this.frustumCulled&&(r.frustumCulled=!1),0!==this.renderOrder&&(r.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(r.userData=this.userData),r.layers=this.layers.mask,r.matrix=this.matrix.toArray(),r.up=this.up.toArray(),!1===this.matrixAutoUpdate&&(r.matrixAutoUpdate=!1),this.isInstancedMesh&&(r.type="InstancedMesh",r.count=this.count,r.instanceMatrix=this.instanceMatrix.toJSON(),null!==this.instanceColor&&(r.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(r.type="BatchedMesh",r.perObjectFrustumCulled=this.perObjectFrustumCulled,r.sortObjects=this.sortObjects,r.drawRanges=this._drawRanges,r.reservedRanges=this._reservedRanges,r.geometryInfo=this._geometryInfo.map(e=>({...e,boundingBox:e.boundingBox?e.boundingBox.toJSON():void 0,boundingSphere:e.boundingSphere?e.boundingSphere.toJSON():void 0})),r.instanceInfo=this._instanceInfo.map(e=>({...e})),r.availableInstanceIds=this._availableInstanceIds.slice(),r.availableGeometryIds=this._availableGeometryIds.slice(),r.nextIndexStart=this._nextIndexStart,r.nextVertexStart=this._nextVertexStart,r.geometryCount=this._geometryCount,r.maxInstanceCount=this._maxInstanceCount,r.maxVertexCount=this._maxVertexCount,r.maxIndexCount=this._maxIndexCount,r.geometryInitialized=this._geometryInitialized,r.matricesTexture=this._matricesTexture.toJSON(e),r.indirectTexture=this._indirectTexture.toJSON(e),null!==this._colorsTexture&&(r.colorsTexture=this._colorsTexture.toJSON(e)),null!==this.boundingSphere&&(r.boundingSphere=this.boundingSphere.toJSON()),null!==this.boundingBox&&(r.boundingBox=this.boundingBox.toJSON())),this.isScene)this.background&&(this.background.isColor?r.background=this.background.toJSON():this.background.isTexture&&(r.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&!0!==this.environment.isRenderTargetTexture&&(r.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){r.geometry=i(e.geometries,this.geometry);const t=this.geometry.parameters;if(void 0!==t&&void 0!==t.shapes){const n=t.shapes;if(Array.isArray(n))for(let t=0,r=n.length;t<r;t++){const r=n[t];i(e.shapes,r)}else i(e.shapes,n)}}if(this.isSkinnedMesh&&(r.bindMode=this.bindMode,r.bindMatrix=this.bindMatrix.toArray(),void 0!==this.skeleton&&(i(e.skeletons,this.skeleton),r.skeleton=this.skeleton.uuid)),void 0!==this.material)if(Array.isArray(this.material)){const t=[];for(let n=0,r=this.material.length;n<r;n++)t.push(i(e.materials,this.material[n]));r.material=t}else r.material=i(e.materials,this.material);if(this.children.length>0){r.children=[];for(let t=0;t<this.children.length;t++)r.children.push(this.children[t].toJSON(e).object)}if(this.animations.length>0){r.animations=[];for(let t=0;t<this.animations.length;t++){const n=this.animations[t];r.animations.push(i(e.animations,n))}}if(t){const t=s(e.geometries),r=s(e.materials),i=s(e.textures),a=s(e.images),o=s(e.shapes),l=s(e.skeletons),u=s(e.animations),c=s(e.nodes);t.length>0&&(n.geometries=t),r.length>0&&(n.materials=r),i.length>0&&(n.textures=i),a.length>0&&(n.images=a),o.length>0&&(n.shapes=o),l.length>0&&(n.skeletons=l),u.length>0&&(n.animations=u),c.length>0&&(n.nodes=c)}return n.object=r,n;function s(e){const t=[];for(const n in e){const r=e[n];delete r.metadata,t.push(r)}return t}}clone(e){return(new this.constructor).copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),!0===t)for(let t=0;t<e.children.length;t++){const n=e.children[t];this.add(n.clone())}return this}}hr.DEFAULT_UP=new Ut(0,1,0),hr.DEFAULT_MATRIX_AUTO_UPDATE=!0,hr.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const dr=new Ut,pr=new Ut,fr=new Ut,mr=new Ut,gr=new Ut,_r=new Ut,vr=new Ut,yr=new Ut,xr=new Ut,br=new Ut,Tr=new an,Sr=new an,Mr=new an;class wr{constructor(e=new Ut,t=new Ut,n=new Ut){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,r){r.subVectors(n,t),dr.subVectors(e,t),r.cross(dr);const i=r.lengthSq();return i>0?r.multiplyScalar(1/Math.sqrt(i)):r.set(0,0,0)}static getBarycoord(e,t,n,r,i){dr.subVectors(r,t),pr.subVectors(n,t),fr.subVectors(e,t);const s=dr.dot(dr),a=dr.dot(pr),o=dr.dot(fr),l=pr.dot(pr),u=pr.dot(fr),c=s*l-a*a;if(0===c)return i.set(0,0,0),null;const h=1/c,d=(l*o-a*u)*h,p=(s*u-a*o)*h;return i.set(1-d-p,p,d)}static containsPoint(e,t,n,r){return null!==this.getBarycoord(e,t,n,r,mr)&&(mr.x>=0&&mr.y>=0&&mr.x+mr.y<=1)}static getInterpolation(e,t,n,r,i,s,a,o){return null===this.getBarycoord(e,t,n,r,mr)?(o.x=0,o.y=0,"z"in o&&(o.z=0),"w"in o&&(o.w=0),null):(o.setScalar(0),o.addScaledVector(i,mr.x),o.addScaledVector(s,mr.y),o.addScaledVector(a,mr.z),o)}static getInterpolatedAttribute(e,t,n,r,i,s){return Tr.setScalar(0),Sr.setScalar(0),Mr.setScalar(0),Tr.fromBufferAttribute(e,t),Sr.fromBufferAttribute(e,n),Mr.fromBufferAttribute(e,r),s.setScalar(0),s.addScaledVector(Tr,i.x),s.addScaledVector(Sr,i.y),s.addScaledVector(Mr,i.z),s}static isFrontFacing(e,t,n,r){return dr.subVectors(n,t),pr.subVectors(e,t),dr.cross(pr).dot(r)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,r){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[r]),this}setFromAttributeAndIndices(e,t,n,r){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,r),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 dr.subVectors(this.c,this.b),pr.subVectors(this.a,this.b),.5*dr.cross(pr).length()}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return wr.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return wr.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,r,i){return wr.getInterpolation(e,this.a,this.b,this.c,t,n,r,i)}containsPoint(e){return wr.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return wr.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const n=this.a,r=this.b,i=this.c;let s,a;gr.subVectors(r,n),_r.subVectors(i,n),yr.subVectors(e,n);const o=gr.dot(yr),l=_r.dot(yr);if(o<=0&&l<=0)return t.copy(n);xr.subVectors(e,r);const u=gr.dot(xr),c=_r.dot(xr);if(u>=0&&c<=u)return t.copy(r);const h=o*c-u*l;if(h<=0&&o>=0&&u<=0)return s=o/(o-u),t.copy(n).addScaledVector(gr,s);br.subVectors(e,i);const d=gr.dot(br),p=_r.dot(br);if(p>=0&&d<=p)return t.copy(i);const f=d*l-o*p;if(f<=0&&l>=0&&p<=0)return a=l/(l-p),t.copy(n).addScaledVector(_r,a);const m=u*p-d*c;if(m<=0&&c-u>=0&&d-p>=0)return vr.subVectors(i,r),a=(c-u)/(c-u+(d-p)),t.copy(r).addScaledVector(vr,a);const g=1/(m+f+h);return s=f*g,a=h*g,t.copy(n).addScaledVector(gr,s).addScaledVector(_r,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const Er={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},Ar={h:0,s:0,l:0},Rr={h:0,s:0,l:0};function Cr(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+6*(t-e)*(2/3-n):e}class Nr{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(void 0===t&&void 0===n){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,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=rt){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(255&e)/255,$t.colorSpaceToWorking(this,t),this}setRGB(e,t,n,r=$t.workingColorSpace){return this.r=e,this.g=t,this.b=n,$t.colorSpaceToWorking(this,r),this}setHSL(e,t,n,r=$t.workingColorSpace){if(e=Rt(e,1),t=At(t,0,1),n=At(n,0,1),0===t)this.r=this.g=this.b=n;else{const r=n<=.5?n*(1+t):n+t-n*t,i=2*n-r;this.r=Cr(i,r,e+1/3),this.g=Cr(i,r,e),this.b=Cr(i,r,e-1/3)}return $t.colorSpaceToWorking(this,r),this}setStyle(e,t=rt){function n(t){void 0!==t&&parseFloat(t)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let r;if(r=/^(\w+)\(([^\)]*)\)/.exec(e)){let i;const s=r[1],a=r[2];switch(s){case"rgb":case"rgba":if(i=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(i[4]),this.setRGB(Math.min(255,parseInt(i[1],10))/255,Math.min(255,parseInt(i[2],10))/255,Math.min(255,parseInt(i[3],10))/255,t);if(i=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(i[4]),this.setRGB(Math.min(100,parseInt(i[1],10))/100,Math.min(100,parseInt(i[2],10))/100,Math.min(100,parseInt(i[3],10))/100,t);break;case"hsl":case"hsla":if(i=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(i[4]),this.setHSL(parseFloat(i[1])/360,parseFloat(i[2])/100,parseFloat(i[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(r=/^\#([A-Fa-f\d]+)$/.exec(e)){const n=r[1],i=n.length;if(3===i)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,t);if(6===i)return this.setHex(parseInt(n,16),t);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=rt){const n=Er[e.toLowerCase()];return void 0!==n?this.setHex(n,t):console.warn("THREE.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=Yt(e.r),this.g=Yt(e.g),this.b=Yt(e.b),this}copyLinearToSRGB(e){return this.r=Kt(e.r),this.g=Kt(e.g),this.b=Kt(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=rt){return $t.workingToColorSpace(Pr.copy(this),e),65536*Math.round(At(255*Pr.r,0,255))+256*Math.round(At(255*Pr.g,0,255))+Math.round(At(255*Pr.b,0,255))}getHexString(e=rt){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=$t.workingColorSpace){$t.workingToColorSpace(Pr.copy(this),t);const n=Pr.r,r=Pr.g,i=Pr.b,s=Math.max(n,r,i),a=Math.min(n,r,i);let o,l;const u=(a+s)/2;if(a===s)o=0,l=0;else{const e=s-a;switch(l=u<=.5?e/(s+a):e/(2-s-a),s){case n:o=(r-i)/e+(r<i?6:0);break;case r:o=(i-n)/e+2;break;case i:o=(n-r)/e+4}o/=6}return e.h=o,e.s=l,e.l=u,e}getRGB(e,t=$t.workingColorSpace){return $t.workingToColorSpace(Pr.copy(this),t),e.r=Pr.r,e.g=Pr.g,e.b=Pr.b,e}getStyle(e=rt){$t.workingToColorSpace(Pr.copy(this),e);const t=Pr.r,n=Pr.g,r=Pr.b;return e!==rt?`color(${e} ${t.toFixed(3)} ${n.toFixed(3)} ${r.toFixed(3)})`:`rgb(${Math.round(255*t)},${Math.round(255*n)},${Math.round(255*r)})`}offsetHSL(e,t,n){return this.getHSL(Ar),this.setHSL(Ar.h+e,Ar.s+t,Ar.l+n)}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,n){return this.r=e.r+(t.r-e.r)*n,this.g=e.g+(t.g-e.g)*n,this.b=e.b+(t.b-e.b)*n,this}lerpHSL(e,t){this.getHSL(Ar),e.getHSL(Rr);const n=Ct(Ar.h,Rr.h,t),r=Ct(Ar.s,Rr.s,t),i=Ct(Ar.l,Rr.l,t);return this.setHSL(n,r,i),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const t=this.r,n=this.g,r=this.b,i=e.elements;return this.r=i[0]*t+i[3]*n+i[6]*r,this.g=i[1]*t+i[4]*n+i[7]*r,this.b=i[2]*t+i[5]*n+i[8]*r,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 Pr=new Nr;Nr.NAMES=Er;let Lr=0;class Dr extends bt{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:Lr++}),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=S,this.blendDst=M,this.blendEquation=g,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new Nr(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=ot,this.stencilZFail=ot,this.stencilZPass=ot,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 n=e[t];if(void 0===n){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}const r=this[t];void 0!==r?r&&r.isColor?r.set(n):r&&r.isVector3&&n&&n.isVector3?r.copy(n):this[t]=n:console.warn(`THREE.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 n={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};function r(e){const t=[];for(const n in e){const r=e[n];delete r.metadata,t.push(r)}return t}if(n.uuid=this.uuid,n.type=this.type,""!==this.name&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),void 0!==this.roughness&&(n.roughness=this.roughness),void 0!==this.metalness&&(n.metalness=this.metalness),void 0!==this.sheen&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),void 0!==this.sheenRoughness&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),void 0!==this.emissiveIntensity&&1!==this.emissiveIntensity&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),void 0!==this.specularIntensity&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),void 0!==this.shininess&&(n.shininess=this.shininess),void 0!==this.clearcoat&&(n.clearcoat=this.clearcoat),void 0!==this.clearcoatRoughness&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),void 0!==this.dispersion&&(n.dispersion=this.dispersion),void 0!==this.iridescence&&(n.iridescence=this.iridescence),void 0!==this.iridescenceIOR&&(n.iridescenceIOR=this.iridescenceIOR),void 0!==this.iridescenceThicknessRange&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),void 0!==this.anisotropy&&(n.anisotropy=this.anisotropy),void 0!==this.anisotropyRotation&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,void 0!==this.combine&&(n.combine=this.combine)),void 0!==this.envMapRotation&&(n.envMapRotation=this.envMapRotation.toArray()),void 0!==this.envMapIntensity&&(n.envMapIntensity=this.envMapIntensity),void 0!==this.reflectivity&&(n.reflectivity=this.reflectivity),void 0!==this.refractionRatio&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),void 0!==this.transmission&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),void 0!==this.thickness&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),void 0!==this.attenuationDistance&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),void 0!==this.attenuationColor&&(n.attenuationColor=this.attenuationColor.getHex()),void 0!==this.size&&(n.size=this.size),null!==this.shadowSide&&(n.shadowSide=this.shadowSide),void 0!==this.sizeAttenuation&&(n.sizeAttenuation=this.sizeAttenuation),1!==this.blending&&(n.blending=this.blending),0!==this.side&&(n.side=this.side),!0===this.vertexColors&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),!0===this.transparent&&(n.transparent=!0),this.blendSrc!==S&&(n.blendSrc=this.blendSrc),this.blendDst!==M&&(n.blendDst=this.blendDst),this.blendEquation!==g&&(n.blendEquation=this.blendEquation),null!==this.blendSrcAlpha&&(n.blendSrcAlpha=this.blendSrcAlpha),null!==this.blendDstAlpha&&(n.blendDstAlpha=this.blendDstAlpha),null!==this.blendEquationAlpha&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),0!==this.blendAlpha&&(n.blendAlpha=this.blendAlpha),3!==this.depthFunc&&(n.depthFunc=this.depthFunc),!1===this.depthTest&&(n.depthTest=this.depthTest),!1===this.depthWrite&&(n.depthWrite=this.depthWrite),!1===this.colorWrite&&(n.colorWrite=this.colorWrite),255!==this.stencilWriteMask&&(n.stencilWriteMask=this.stencilWriteMask),519!==this.stencilFunc&&(n.stencilFunc=this.stencilFunc),0!==this.stencilRef&&(n.stencilRef=this.stencilRef),255!==this.stencilFuncMask&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==ot&&(n.stencilFail=this.stencilFail),this.stencilZFail!==ot&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==ot&&(n.stencilZPass=this.stencilZPass),!0===this.stencilWrite&&(n.stencilWrite=this.stencilWrite),void 0!==this.rotation&&0!==this.rotation&&(n.rotation=this.rotation),!0===this.polygonOffset&&(n.polygonOffset=!0),0!==this.polygonOffsetFactor&&(n.polygonOffsetFactor=this.polygonOffsetFactor),0!==this.polygonOffsetUnits&&(n.polygonOffsetUnits=this.polygonOffsetUnits),void 0!==this.linewidth&&1!==this.linewidth&&(n.linewidth=this.linewidth),void 0!==this.dashSize&&(n.dashSize=this.dashSize),void 0!==this.gapSize&&(n.gapSize=this.gapSize),void 0!==this.scale&&(n.scale=this.scale),!0===this.dithering&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),!0===this.alphaHash&&(n.alphaHash=!0),!0===this.alphaToCoverage&&(n.alphaToCoverage=!0),!0===this.premultipliedAlpha&&(n.premultipliedAlpha=!0),!0===this.forceSinglePass&&(n.forceSinglePass=!0),!0===this.wireframe&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),"round"!==this.wireframeLinecap&&(n.wireframeLinecap=this.wireframeLinecap),"round"!==this.wireframeLinejoin&&(n.wireframeLinejoin=this.wireframeLinejoin),!0===this.flatShading&&(n.flatShading=!0),!1===this.visible&&(n.visible=!1),!1===this.toneMapped&&(n.toneMapped=!1),!1===this.fog&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData),t){const t=r(e.textures),i=r(e.images);t.length>0&&(n.textures=t),i.length>0&&(n.images=i)}return n}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 n=null;if(null!==t){const e=t.length;n=new Array(e);for(let r=0;r!==e;++r)n[r]=t[r].clone()}return this.clippingPlanes=n,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.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 Ir extends Dr{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Nr(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 $n,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 Ur=Or();function Or(){const e=new ArrayBuffer(4),t=new Float32Array(e),n=new Uint32Array(e),r=new Uint32Array(512),i=new Uint32Array(512);for(let e=0;e<256;++e){const t=e-127;t<-27?(r[e]=0,r[256|e]=32768,i[e]=24,i[256|e]=24):t<-14?(r[e]=1024>>-t-14,r[256|e]=1024>>-t-14|32768,i[e]=-t-1,i[256|e]=-t-1):t<=15?(r[e]=t+15<<10,r[256|e]=t+15<<10|32768,i[e]=13,i[256|e]=13):t<128?(r[e]=31744,r[256|e]=64512,i[e]=24,i[256|e]=24):(r[e]=31744,r[256|e]=64512,i[e]=13,i[256|e]=13)}const s=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let e=1;e<1024;++e){let t=e<<13,n=0;for(;!(8388608&t);)t<<=1,n-=8388608;t&=-8388609,n+=947912704,s[e]=t|n}for(let e=1024;e<2048;++e)s[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:n,baseTable:r,shiftTable:i,mantissaTable:s,exponentTable:a,offsetTable:o}}function Fr(e){Math.abs(e)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),e=At(e,-65504,65504),Ur.floatView[0]=e;const t=Ur.uint32View[0],n=t>>23&511;return Ur.baseTable[n]+((8388607&t)>>Ur.shiftTable[n])}function Br(e){const t=e>>10;return Ur.uint32View[0]=Ur.mantissaTable[Ur.offsetTable[t]+(1023&e)]+Ur.exponentTable[t],Ur.floatView[0]}const kr=new Ut,zr=new Dt;let Vr=0;class Gr{constructor(e,t,n=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:Vr++}),this.name="",this.array=e,this.itemSize=t,this.count=void 0!==e?e.length/t:0,this.normalized=n,this.usage=gt,this.updateRanges=[],this.gpuType=le,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,n){e*=this.itemSize,n*=t.itemSize;for(let r=0,i=this.itemSize;r<i;r++)this.array[e+r]=t.array[n+r];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(2===this.itemSize)for(let t=0,n=this.count;t<n;t++)zr.fromBufferAttribute(this,t),zr.applyMatrix3(e),this.setXY(t,zr.x,zr.y);else if(3===this.itemSize)for(let t=0,n=this.count;t<n;t++)kr.fromBufferAttribute(this,t),kr.applyMatrix3(e),this.setXYZ(t,kr.x,kr.y,kr.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)kr.fromBufferAttribute(this,t),kr.applyMatrix4(e),this.setXYZ(t,kr.x,kr.y,kr.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)kr.fromBufferAttribute(this,t),kr.applyNormalMatrix(e),this.setXYZ(t,kr.x,kr.y,kr.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)kr.fromBufferAttribute(this,t),kr.transformDirection(e),this.setXYZ(t,kr.x,kr.y,kr.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let n=this.array[e*this.itemSize+t];return this.normalized&&(n=Nt(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=Pt(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=Nt(t,this.array)),t}setX(e,t){return this.normalized&&(t=Pt(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=Nt(t,this.array)),t}setY(e,t){return this.normalized&&(t=Pt(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=Nt(t,this.array)),t}setZ(e,t){return this.normalized&&(t=Pt(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=Nt(t,this.array)),t}setW(e,t){return this.normalized&&(t=Pt(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=Pt(t,this.array),n=Pt(n,this.array)),this.array[e+0]=t,this.array[e+1]=n,this}setXYZ(e,t,n,r){return e*=this.itemSize,this.normalized&&(t=Pt(t,this.array),n=Pt(n,this.array),r=Pt(r,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=r,this}setXYZW(e,t,n,r,i){return e*=this.itemSize,this.normalized&&(t=Pt(t,this.array),n=Pt(n,this.array),r=Pt(r,this.array),i=Pt(i,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=r,this.array[e+3]=i,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!==gt&&(e.usage=this.usage),e}}class Hr extends Gr{constructor(e,t,n){super(new Uint16Array(e),t,n)}}class jr extends Gr{constructor(e,t,n){super(new Uint32Array(e),t,n)}}class Wr extends Gr{constructor(e,t,n){super(new Uint16Array(e),t,n),this.isFloat16BufferAttribute=!0}getX(e){let t=Br(this.array[e*this.itemSize]);return this.normalized&&(t=Nt(t,this.array)),t}setX(e,t){return this.normalized&&(t=Pt(t,this.array)),this.array[e*this.itemSize]=Fr(t),this}getY(e){let t=Br(this.array[e*this.itemSize+1]);return this.normalized&&(t=Nt(t,this.array)),t}setY(e,t){return this.normalized&&(t=Pt(t,this.array)),this.array[e*this.itemSize+1]=Fr(t),this}getZ(e){let t=Br(this.array[e*this.itemSize+2]);return this.normalized&&(t=Nt(t,this.array)),t}setZ(e,t){return this.normalized&&(t=Pt(t,this.array)),this.array[e*this.itemSize+2]=Fr(t),this}getW(e){let t=Br(this.array[e*this.itemSize+3]);return this.normalized&&(t=Nt(t,this.array)),t}setW(e,t){return this.normalized&&(t=Pt(t,this.array)),this.array[e*this.itemSize+3]=Fr(t),this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=Pt(t,this.array),n=Pt(n,this.array)),this.array[e+0]=Fr(t),this.array[e+1]=Fr(n),this}setXYZ(e,t,n,r){return e*=this.itemSize,this.normalized&&(t=Pt(t,this.array),n=Pt(n,this.array),r=Pt(r,this.array)),this.array[e+0]=Fr(t),this.array[e+1]=Fr(n),this.array[e+2]=Fr(r),this}setXYZW(e,t,n,r,i){return e*=this.itemSize,this.normalized&&(t=Pt(t,this.array),n=Pt(n,this.array),r=Pt(r,this.array),i=Pt(i,this.array)),this.array[e+0]=Fr(t),this.array[e+1]=Fr(n),this.array[e+2]=Fr(r),this.array[e+3]=Fr(i),this}}class Xr extends Gr{constructor(e,t,n){super(new Float32Array(e),t,n)}}let qr=0;const $r=new Bn,Yr=new hr,Kr=new Ut,Qr=new hn,Zr=new hn,Jr=new Ut;class ei extends bt{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:qr++}),this.uuid=Et(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,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(zt(e)?jr:Hr)(e,1):this.index=e,this}setIndirect(e){return this.indirect=e,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,n=0){this.groups.push({start:e,count:t,materialIndex:n})}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 n=this.attributes.normal;if(void 0!==n){const t=(new Bt).getNormalMatrix(e);n.applyNormalMatrix(t),n.needsUpdate=!0}const r=this.attributes.tangent;return void 0!==r&&(r.transformDirection(e),r.needsUpdate=!0),null!==this.boundingBox&&this.computeBoundingBox(),null!==this.boundingSphere&&this.computeBoundingSphere(),this}applyQuaternion(e){return $r.makeRotationFromQuaternion(e),this.applyMatrix4($r),this}rotateX(e){return $r.makeRotationX(e),this.applyMatrix4($r),this}rotateY(e){return $r.makeRotationY(e),this.applyMatrix4($r),this}rotateZ(e){return $r.makeRotationZ(e),this.applyMatrix4($r),this}translate(e,t,n){return $r.makeTranslation(e,t,n),this.applyMatrix4($r),this}scale(e,t,n){return $r.makeScale(e,t,n),this.applyMatrix4($r),this}lookAt(e){return Yr.lookAt(e),Yr.updateMatrix(),this.applyMatrix4(Yr.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Kr).negate(),this.translate(Kr.x,Kr.y,Kr.z),this}setFromPoints(e){const t=this.getAttribute("position");if(void 0===t){const t=[];for(let n=0,r=e.length;n<r;n++){const r=e[n];t.push(r.x,r.y,r.z||0)}this.setAttribute("position",new Xr(t,3))}else{const n=Math.min(e.length,t.count);for(let r=0;r<n;r++){const n=e[r];t.setXYZ(r,n.x,n.y,n.z||0)}e.length>t.count&&console.warn("THREE.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 hn);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),void this.boundingBox.set(new Ut(-1/0,-1/0,-1/0),new Ut(1/0,1/0,1/0));if(void 0!==e){if(this.boundingBox.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e<n;e++){const n=t[e];Qr.setFromBufferAttribute(n),this.morphTargetsRelative?(Jr.addVectors(this.boundingBox.min,Qr.min),this.boundingBox.expandByPoint(Jr),Jr.addVectors(this.boundingBox.max,Qr.max),this.boundingBox.expandByPoint(Jr)):(this.boundingBox.expandByPoint(Qr.min),this.boundingBox.expandByPoint(Qr.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error('THREE.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 Cn);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return console.error("THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),void this.boundingSphere.set(new Ut,1/0);if(e){const n=this.boundingSphere.center;if(Qr.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e<n;e++){const n=t[e];Zr.setFromBufferAttribute(n),this.morphTargetsRelative?(Jr.addVectors(Qr.min,Zr.min),Qr.expandByPoint(Jr),Jr.addVectors(Qr.max,Zr.max),Qr.expandByPoint(Jr)):(Qr.expandByPoint(Zr.min),Qr.expandByPoint(Zr.max))}Qr.getCenter(n);let r=0;for(let t=0,i=e.count;t<i;t++)Jr.fromBufferAttribute(e,t),r=Math.max(r,n.distanceToSquared(Jr));if(t)for(let i=0,s=t.length;i<s;i++){const s=t[i],a=this.morphTargetsRelative;for(let t=0,i=s.count;t<i;t++)Jr.fromBufferAttribute(s,t),a&&(Kr.fromBufferAttribute(e,t),Jr.add(Kr)),r=Math.max(r,n.distanceToSquared(Jr))}this.boundingSphere.radius=Math.sqrt(r),isNaN(this.boundingSphere.radius)&&console.error('THREE.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 console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");const n=t.position,r=t.normal,i=t.uv;!1===this.hasAttribute("tangent")&&this.setAttribute("tangent",new Gr(new Float32Array(4*n.count),4));const s=this.getAttribute("tangent"),a=[],o=[];for(let e=0;e<n.count;e++)a[e]=new Ut,o[e]=new Ut;const l=new Ut,u=new Ut,c=new Ut,h=new Dt,d=new Dt,p=new Dt,f=new Ut,m=new Ut;function g(e,t,r){l.fromBufferAttribute(n,e),u.fromBufferAttribute(n,t),c.fromBufferAttribute(n,r),h.fromBufferAttribute(i,e),d.fromBufferAttribute(i,t),p.fromBufferAttribute(i,r),u.sub(l),c.sub(l),d.sub(h),p.sub(h);const s=1/(d.x*p.y-p.x*d.y);isFinite(s)&&(f.copy(u).multiplyScalar(p.y).addScaledVector(c,-d.y).multiplyScalar(s),m.copy(c).multiplyScalar(d.x).addScaledVector(u,-p.x).multiplyScalar(s),a[e].add(f),a[t].add(f),a[r].add(f),o[e].add(m),o[t].add(m),o[r].add(m))}let _=this.groups;0===_.length&&(_=[{start:0,count:e.count}]);for(let t=0,n=_.length;t<n;++t){const n=_[t],r=n.start;for(let t=r,i=r+n.count;t<i;t+=3)g(e.getX(t+0),e.getX(t+1),e.getX(t+2))}const v=new Ut,y=new Ut,x=new Ut,b=new Ut;function T(e){x.fromBufferAttribute(r,e),b.copy(x);const t=a[e];v.copy(t),v.sub(x.multiplyScalar(x.dot(t))).normalize(),y.crossVectors(b,t);const n=y.dot(o[e])<0?-1:1;s.setXYZW(e,v.x,v.y,v.z,n)}for(let t=0,n=_.length;t<n;++t){const n=_[t],r=n.start;for(let t=r,i=r+n.count;t<i;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 n=this.getAttribute("normal");if(void 0===n)n=new Gr(new Float32Array(3*t.count),3),this.setAttribute("normal",n);else for(let e=0,t=n.count;e<t;e++)n.setXYZ(e,0,0,0);const r=new Ut,i=new Ut,s=new Ut,a=new Ut,o=new Ut,l=new Ut,u=new Ut,c=new Ut;if(e)for(let h=0,d=e.count;h<d;h+=3){const d=e.getX(h+0),p=e.getX(h+1),f=e.getX(h+2);r.fromBufferAttribute(t,d),i.fromBufferAttribute(t,p),s.fromBufferAttribute(t,f),u.subVectors(s,i),c.subVectors(r,i),u.cross(c),a.fromBufferAttribute(n,d),o.fromBufferAttribute(n,p),l.fromBufferAttribute(n,f),a.add(u),o.add(u),l.add(u),n.setXYZ(d,a.x,a.y,a.z),n.setXYZ(p,o.x,o.y,o.z),n.setXYZ(f,l.x,l.y,l.z)}else for(let e=0,a=t.count;e<a;e+=3)r.fromBufferAttribute(t,e+0),i.fromBufferAttribute(t,e+1),s.fromBufferAttribute(t,e+2),u.subVectors(s,i),c.subVectors(r,i),u.cross(c),n.setXYZ(e+0,u.x,u.y,u.z),n.setXYZ(e+1,u.x,u.y,u.z),n.setXYZ(e+2,u.x,u.y,u.z);this.normalizeNormals(),n.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let t=0,n=e.count;t<n;t++)Jr.fromBufferAttribute(e,t),Jr.normalize(),e.setXYZ(t,Jr.x,Jr.y,Jr.z)}toNonIndexed(){function e(e,t){const n=e.array,r=e.itemSize,i=e.normalized,s=new n.constructor(t.length*r);let a=0,o=0;for(let i=0,l=t.length;i<l;i++){a=e.isInterleavedBufferAttribute?t[i]*e.data.stride+e.offset:t[i]*r;for(let e=0;e<r;e++)s[o++]=n[a++]}return new Gr(s,r,i)}if(null===this.index)return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new ei,n=this.index.array,r=this.attributes;for(const i in r){const s=e(r[i],n);t.setAttribute(i,s)}const i=this.morphAttributes;for(const r in i){const s=[],a=i[r];for(let t=0,r=a.length;t<r;t++){const r=e(a[t],n);s.push(r)}t.morphAttributes[r]=s}t.morphTargetsRelative=this.morphTargetsRelative;const s=this.groups;for(let e=0,n=s.length;e<n;e++){const n=s[e];t.addGroup(n.start,n.count,n.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 n in t)void 0!==t[n]&&(e[n]=t[n]);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 n=this.attributes;for(const t in n){const r=n[t];e.data.attributes[t]=r.toJSON(e.data)}const r={};let i=!1;for(const t in this.morphAttributes){const n=this.morphAttributes[t],s=[];for(let t=0,r=n.length;t<r;t++){const r=n[t];s.push(r.toJSON(e.data))}s.length>0&&(r[t]=s,i=!0)}i&&(e.data.morphAttributes=r,e.data.morphTargetsRelative=this.morphTargetsRelative);const s=this.groups;s.length>0&&(e.data.groups=JSON.parse(JSON.stringify(s)));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 n=e.index;null!==n&&this.setIndex(n.clone());const r=e.attributes;for(const e in r){const n=r[e];this.setAttribute(e,n.clone(t))}const i=e.morphAttributes;for(const e in i){const n=[],r=i[e];for(let e=0,i=r.length;e<i;e++)n.push(r[e].clone(t));this.morphAttributes[e]=n}this.morphTargetsRelative=e.morphTargetsRelative;const s=e.groups;for(let e=0,t=s.length;e<t;e++){const t=s[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"})}}const ti=new Bn,ni=new Fn,ri=new Cn,ii=new Ut,si=new Ut,ai=new Ut,oi=new Ut,li=new Ut,ui=new Ut,ci=new Ut,hi=new Ut;class di extends hr{constructor(e=new ei,t=new Ir){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 n=e[t[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e<t;e++){const t=n[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}getVertexPosition(e,t){const n=this.geometry,r=n.attributes.position,i=n.morphAttributes.position,s=n.morphTargetsRelative;t.fromBufferAttribute(r,e);const a=this.morphTargetInfluences;if(i&&a){ui.set(0,0,0);for(let n=0,r=i.length;n<r;n++){const r=a[n],o=i[n];0!==r&&(li.fromBufferAttribute(o,e),s?ui.addScaledVector(li,r):ui.addScaledVector(li.sub(t),r))}t.add(ui)}return t}raycast(e,t){const n=this.geometry,r=this.material,i=this.matrixWorld;if(void 0!==r){if(null===n.boundingSphere&&n.computeBoundingSphere(),ri.copy(n.boundingSphere),ri.applyMatrix4(i),ni.copy(e.ray).recast(e.near),!1===ri.containsPoint(ni.origin)){if(null===ni.intersectSphere(ri,ii))return;if(ni.origin.distanceToSquared(ii)>(e.far-e.near)**2)return}ti.copy(i).invert(),ni.copy(e.ray).applyMatrix4(ti),null!==n.boundingBox&&!1===ni.intersectsBox(n.boundingBox)||this._computeIntersections(e,t,ni)}}_computeIntersections(e,t,n){let r;const i=this.geometry,s=this.material,a=i.index,o=i.attributes.position,l=i.attributes.uv,u=i.attributes.uv1,c=i.attributes.normal,h=i.groups,d=i.drawRange;if(null!==a)if(Array.isArray(s))for(let i=0,o=h.length;i<o;i++){const o=h[i],p=s[o.materialIndex];for(let i=Math.max(o.start,d.start),s=Math.min(a.count,Math.min(o.start+o.count,d.start+d.count));i<s;i+=3){r=pi(this,p,e,n,l,u,c,a.getX(i),a.getX(i+1),a.getX(i+2)),r&&(r.faceIndex=Math.floor(i/3),r.face.materialIndex=o.materialIndex,t.push(r))}}else{for(let i=Math.max(0,d.start),o=Math.min(a.count,d.start+d.count);i<o;i+=3){r=pi(this,s,e,n,l,u,c,a.getX(i),a.getX(i+1),a.getX(i+2)),r&&(r.faceIndex=Math.floor(i/3),t.push(r))}}else if(void 0!==o)if(Array.isArray(s))for(let i=0,a=h.length;i<a;i++){const a=h[i],p=s[a.materialIndex];for(let i=Math.max(a.start,d.start),s=Math.min(o.count,Math.min(a.start+a.count,d.start+d.count));i<s;i+=3){r=pi(this,p,e,n,l,u,c,i,i+1,i+2),r&&(r.faceIndex=Math.floor(i/3),r.face.materialIndex=a.materialIndex,t.push(r))}}else{for(let i=Math.max(0,d.start),a=Math.min(o.count,d.start+d.count);i<a;i+=3){r=pi(this,s,e,n,l,u,c,i,i+1,i+2),r&&(r.faceIndex=Math.floor(i/3),t.push(r))}}}}function pi(e,t,n,r,i,s,a,o,l,u){e.getVertexPosition(o,si),e.getVertexPosition(l,ai),e.getVertexPosition(u,oi);const c=function(e,t,n,r,i,s,a,o){let l;if(l=1===t.side?r.intersectTriangle(a,s,i,!0,o):r.intersectTriangle(i,s,a,0===t.side,o),null===l)return null;hi.copy(o),hi.applyMatrix4(e.matrixWorld);const u=n.ray.origin.distanceTo(hi);return u<n.near||u>n.far?null:{distance:u,point:hi.clone(),object:e}}(e,t,n,r,si,ai,oi,ci);if(c){const e=new Ut;wr.getBarycoord(ci,si,ai,oi,e),i&&(c.uv=wr.getInterpolatedAttribute(i,o,l,u,e,new Dt)),s&&(c.uv1=wr.getInterpolatedAttribute(s,o,l,u,e,new Dt)),a&&(c.normal=wr.getInterpolatedAttribute(a,o,l,u,e,new Ut),c.normal.dot(r.direction)>0&&c.normal.multiplyScalar(-1));const t={a:o,b:l,c:u,normal:new Ut,materialIndex:0};wr.getNormal(si,ai,oi,t.normal),c.face=t,c.barycoord=e}return c}class fi extends ei{constructor(e=1,t=1,n=1,r=1,i=1,s=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:n,widthSegments:r,heightSegments:i,depthSegments:s};const a=this;r=Math.floor(r),i=Math.floor(i),s=Math.floor(s);const o=[],l=[],u=[],c=[];let h=0,d=0;function p(e,t,n,r,i,s,p,f,m,g,_){const v=s/m,y=p/g,x=s/2,b=p/2,T=f/2,S=m+1,M=g+1;let w=0,E=0;const A=new Ut;for(let s=0;s<M;s++){const a=s*y-b;for(let o=0;o<S;o++){const h=o*v-x;A[e]=h*r,A[t]=a*i,A[n]=T,l.push(A.x,A.y,A.z),A[e]=0,A[t]=0,A[n]=f>0?1:-1,u.push(A.x,A.y,A.z),c.push(o/m),c.push(1-s/g),w+=1}}for(let e=0;e<g;e++)for(let t=0;t<m;t++){const n=h+t+S*e,r=h+t+S*(e+1),i=h+(t+1)+S*(e+1),s=h+(t+1)+S*e;o.push(n,r,s),o.push(r,i,s),E+=6}a.addGroup(d,E,_),d+=E,h+=w}p("z","y","x",-1,-1,n,t,e,s,i,0),p("z","y","x",1,-1,n,t,-e,s,i,1),p("x","z","y",1,1,e,n,t,r,s,2),p("x","z","y",1,-1,e,n,-t,r,s,3),p("x","y","z",1,-1,e,t,n,r,i,4),p("x","y","z",-1,-1,e,t,-n,r,i,5),this.setIndex(o),this.setAttribute("position",new Xr(l,3)),this.setAttribute("normal",new Xr(u,3)),this.setAttribute("uv",new Xr(c,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new fi(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}function mi(e){const t={};for(const n in e){t[n]={};for(const r in e[n]){const i=e[n][r];i&&(i.isColor||i.isMatrix3||i.isMatrix4||i.isVector2||i.isVector3||i.isVector4||i.isTexture||i.isQuaternion)?i.isRenderTargetTexture?(console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),t[n][r]=null):t[n][r]=i.clone():Array.isArray(i)?t[n][r]=i.slice():t[n][r]=i}}return t}function gi(e){const t={};for(let n=0;n<e.length;n++){const r=mi(e[n]);for(const e in r)t[e]=r[e]}return t}function _i(e){const t=e.getRenderTarget();return null===t?e.outputColorSpace:!0===t.isXRRenderTarget?t.texture.colorSpace:$t.workingColorSpace}const vi={clone:mi,merge:gi};class yi extends Dr{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader="void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}",this.fragmentShader="void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}",this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,void 0!==e&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=mi(e.uniforms),this.uniformsGroups=function(e){const t=[];for(let n=0;n<e.length;n++)t.push(e[n].clone());return t}(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this}toJSON(e){const t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(const n in this.uniforms){const r=this.uniforms[n].value;r&&r.isTexture?t.uniforms[n]={type:"t",value:r.toJSON(e).uuid}:r&&r.isColor?t.uniforms[n]={type:"c",value:r.getHex()}:r&&r.isVector2?t.uniforms[n]={type:"v2",value:r.toArray()}:r&&r.isVector3?t.uniforms[n]={type:"v3",value:r.toArray()}:r&&r.isVector4?t.uniforms[n]={type:"v4",value:r.toArray()}:r&&r.isMatrix3?t.uniforms[n]={type:"m3",value:r.toArray()}:r&&r.isMatrix4?t.uniforms[n]={type:"m4",value:r.toArray()}:t.uniforms[n]={value:r}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const n={};for(const e in this.extensions)!0===this.extensions[e]&&(n[e]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}}class xi extends hr{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Bn,this.projectionMatrix=new Bn,this.projectionMatrixInverse=new Bn,this.coordinateSystem=yt}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return(new this.constructor).copy(this)}}const bi=new Ut,Ti=new Dt,Si=new Dt;class Mi extends xi{constructor(e=50,t=1,n=.1,r=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=n,this.far=r,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*wt*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(.5*Mt*this.fov);return.5*this.getFilmHeight()/e}getEffectiveFOV(){return 2*wt*Math.atan(Math.tan(.5*Mt*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,n){bi.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(bi.x,bi.y).multiplyScalar(-e/bi.z),bi.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(bi.x,bi.y).multiplyScalar(-e/bi.z)}getViewSize(e,t){return this.getViewBounds(e,Ti,Si),t.subVectors(Si,Ti)}setViewOffset(e,t,n,r,i,s){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=n,this.view.offsetY=r,this.view.width=i,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(.5*Mt*this.fov)/this.zoom,n=2*t,r=this.aspect*n,i=-.5*r;const s=this.view;if(null!==this.view&&this.view.enabled){const e=s.fullWidth,a=s.fullHeight;i+=s.offsetX*r/e,t-=s.offsetY*n/a,r*=s.width/e,n*=s.height/a}const a=this.filmOffset;0!==a&&(i+=e*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(i,i+r,t,t-n,e,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,null!==this.view&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const wi=-90;class Ei extends hr{constructor(e,t,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;const r=new Mi(wi,1,e,t);r.layers=this.layers,this.add(r);const i=new Mi(wi,1,e,t);i.layers=this.layers,this.add(i);const s=new Mi(wi,1,e,t);s.layers=this.layers,this.add(s);const a=new Mi(wi,1,e,t);a.layers=this.layers,this.add(a);const o=new Mi(wi,1,e,t);o.layers=this.layers,this.add(o);const l=new Mi(wi,1,e,t);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[n,r,i,s,a,o]=t;for(const e of t)this.remove(e);if(e===yt)n.up.set(0,1,0),n.lookAt(1,0,0),r.up.set(0,1,0),r.lookAt(-1,0,0),i.up.set(0,0,-1),i.lookAt(0,1,0),s.up.set(0,0,1),s.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!==xt)throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);n.up.set(0,-1,0),n.lookAt(-1,0,0),r.up.set(0,-1,0),r.lookAt(1,0,0),i.up.set(0,0,1),i.lookAt(0,1,0),s.up.set(0,0,-1),s.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:n,activeMipmapLevel:r}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[i,s,a,o,l,u]=this.children,c=e.getRenderTarget(),h=e.getActiveCubeFace(),d=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;const f=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,e.setRenderTarget(n,0,r),e.render(t,i),e.setRenderTarget(n,1,r),e.render(t,s),e.setRenderTarget(n,2,r),e.render(t,a),e.setRenderTarget(n,3,r),e.render(t,o),e.setRenderTarget(n,4,r),e.render(t,l),n.texture.generateMipmaps=f,e.setRenderTarget(n,5,r),e.render(t,u),e.setRenderTarget(c,h,d),e.xr.enabled=p,n.texture.needsPMREMUpdate=!0}}class Ai extends sn{constructor(e=[],t=301,n,r,i,s,a,o,l,u){super(e,t,n,r,i,s,a,o,l,u),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class Ri extends ln{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const n={width:e,height:e,depth:1},r=[n,n,n,n,n,n];this.texture=new Ai(r),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const n={uniforms:{tEquirect:{value:null}},vertexShader:"\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t\t}\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t\t#include <begin_vertex>\n\t\t\t\t\t#include <project_vertex>\n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include <common>\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t"},r=new fi(5,5,5),i=new yi({name:"CubemapFromEquirect",uniforms:mi(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:1,blending:0});i.uniforms.tEquirect.value=t;const s=new di(r,i),a=t.minFilter;t.minFilter===te&&(t.minFilter=J);return new Ei(1,10,this).update(e,s),t.minFilter=a,s.geometry.dispose(),s.material.dispose(),this}clear(e,t=!0,n=!0,r=!0){const i=e.getRenderTarget();for(let i=0;i<6;i++)e.setRenderTarget(this,i),e.clear(t,n,r);e.setRenderTarget(i)}}let Ci=class extends hr{constructor(){super(),this.isGroup=!0,this.type="Group"}};const Ni={type:"move"};class Pi{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return null===this._hand&&(this._hand=new Ci,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 Ci,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new Ut,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new Ut),this._targetRay}getGripSpace(){return null===this._grip&&(this._grip=new Ci,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new Ut,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new Ut),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 n of e.hand.values())this._getHandJoint(t,n)}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,n){let r=null,i=null,s=null;const a=this._targetRay,o=this._grip,l=this._hand;if(e&&"visible-blurred"!==t.session.visibilityState){if(l&&e.hand){s=!0;for(const r of e.hand.values()){const e=t.getJointPose(r,n),i=this._getHandJoint(l,r);null!==e&&(i.matrix.fromArray(e.transform.matrix),i.matrix.decompose(i.position,i.rotation,i.scale),i.matrixWorldNeedsUpdate=!0,i.jointRadius=e.radius),i.visible=null!==e}const r=l.joints["index-finger-tip"],i=l.joints["thumb-tip"],a=r.position.distanceTo(i.position),o=.02,u=.005;l.inputState.pinching&&a>o+u?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!l.inputState.pinching&&a<=o-u&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else null!==o&&e.gripSpace&&(i=t.getPose(e.gripSpace,n),null!==i&&(o.matrix.fromArray(i.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,i.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(i.linearVelocity)):o.hasLinearVelocity=!1,i.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(i.angularVelocity)):o.hasAngularVelocity=!1));null!==a&&(r=t.getPose(e.targetRaySpace,n),null===r&&null!==i&&(r=i),null!==r&&(a.matrix.fromArray(r.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,r.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(r.linearVelocity)):a.hasLinearVelocity=!1,r.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(r.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(Ni)))}return null!==a&&(a.visible=null!==r),null!==o&&(o.visible=null!==i),null!==l&&(l.visible=null!==s),this}_getHandJoint(e,t){if(void 0===e.joints[t.jointName]){const n=new Ci;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}}class Li extends hr{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 $n,this.environmentIntensity=1,this.environmentRotation=new $n,this.overrideMaterial=null,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),null!==e.background&&(this.background=e.background.clone()),null!==e.environment&&(this.environment=e.environment.clone()),null!==e.fog&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),null!==e.overrideMaterial&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return null!==this.fog&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),1!==this.backgroundIntensity&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),1!==this.environmentIntensity&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}class Di{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=void 0!==e?e.length/t:0,this.usage=gt,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,n){e*=this.stride,n*=t.stride;for(let r=0,i=this.stride;r<i;r++)this.array[e+r]=t.array[n+r];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]),n=new this.constructor(t,this.stride);return n.setUsage(this.usage),n}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 Ii=new Ut;class Ui{constructor(e,t,n,r=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=e,this.itemSize=t,this.offset=n,this.normalized=r}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,n=this.data.count;t<n;t++)Ii.fromBufferAttribute(this,t),Ii.applyMatrix4(e),this.setXYZ(t,Ii.x,Ii.y,Ii.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)Ii.fromBufferAttribute(this,t),Ii.applyNormalMatrix(e),this.setXYZ(t,Ii.x,Ii.y,Ii.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)Ii.fromBufferAttribute(this,t),Ii.transformDirection(e),this.setXYZ(t,Ii.x,Ii.y,Ii.z);return this}getComponent(e,t){let n=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(n=Nt(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=Pt(n,this.array)),this.data.array[e*this.data.stride+this.offset+t]=n,this}setX(e,t){return this.normalized&&(t=Pt(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=Pt(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=Pt(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=Pt(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=Nt(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=Nt(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=Nt(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=Nt(t,this.array)),t}setXY(e,t,n){return e=e*this.data.stride+this.offset,this.normalized&&(t=Pt(t,this.array),n=Pt(n,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this}setXYZ(e,t,n,r){return e=e*this.data.stride+this.offset,this.normalized&&(t=Pt(t,this.array),n=Pt(n,this.array),r=Pt(r,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=r,this}setXYZW(e,t,n,r,i){return e=e*this.data.stride+this.offset,this.normalized&&(t=Pt(t,this.array),n=Pt(n,this.array),r=Pt(r,this.array),i=Pt(i,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=r,this.data.array[e+3]=i,this}clone(e){if(void 0===e){console.log("THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");const e=[];for(let t=0;t<this.count;t++){const n=t*this.data.stride+this.offset;for(let t=0;t<this.itemSize;t++)e.push(this.data.array[n+t])}return new Gr(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 Ui(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(void 0===e){console.log("THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");const e=[];for(let t=0;t<this.count;t++){const n=t*this.data.stride+this.offset;for(let t=0;t<this.itemSize;t++)e.push(this.data.array[n+t])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:e,normalized:this.normalized}}return void 0===e.interleavedBuffers&&(e.interleavedBuffers={}),void 0===e.interleavedBuffers[this.data.uuid]&&(e.interleavedBuffers[this.data.uuid]=this.data.toJSON(e)),{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}}class Oi extends Dr{constructor(e){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new Nr(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.rotation=e.rotation,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}class Fi extends sn{constructor(e=null,t=1,n=1,r,i,s,a,o,l=1003,u=1003,c,h){super(null,s,a,o,l,u,r,i,c,h),this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class Bi extends Gr{constructor(e,t,n,r=1){super(e,t,n),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=r}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 ki=new Ut,zi=new Ut,Vi=new Bt;class Gi{constructor(e=new Ut(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,n,r){return this.normal.set(e,t,n),this.constant=r,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){const r=ki.subVectors(n,t).cross(zi.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(r,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t){const n=e.delta(ki),r=this.normal.dot(n);if(0===r)return 0===this.distanceToPoint(e.start)?t.copy(e.start):null;const i=-(e.start.dot(this.normal)+this.constant)/r;return i<0||i>1?null:t.copy(e.start).addScaledVector(n,i)}intersectsLine(e){const t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<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 n=t||Vi.getNormalMatrix(e),r=this.coplanarPoint(ki).applyMatrix4(e),i=this.normal.applyMatrix3(n).normalize();return this.constant=-r.dot(i),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 Hi=new Cn,ji=new Dt(.5,.5),Wi=new Ut;class Xi{constructor(e=new Gi,t=new Gi,n=new Gi,r=new Gi,i=new Gi,s=new Gi){this.planes=[e,t,n,r,i,s]}set(e,t,n,r,i,s){const a=this.planes;return a[0].copy(e),a[1].copy(t),a[2].copy(n),a[3].copy(r),a[4].copy(i),a[5].copy(s),this}copy(e){const t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=2e3){const n=this.planes,r=e.elements,i=r[0],s=r[1],a=r[2],o=r[3],l=r[4],u=r[5],c=r[6],h=r[7],d=r[8],p=r[9],f=r[10],m=r[11],g=r[12],_=r[13],v=r[14],y=r[15];if(n[0].setComponents(o-i,h-l,m-d,y-g).normalize(),n[1].setComponents(o+i,h+l,m+d,y+g).normalize(),n[2].setComponents(o+s,h+u,m+p,y+_).normalize(),n[3].setComponents(o-s,h-u,m-p,y-_).normalize(),n[4].setComponents(o-a,h-c,m-f,y-v).normalize(),t===yt)n[5].setComponents(o+a,h+c,m+f,y+v).normalize();else{if(t!==xt)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);n[5].setComponents(a,c,f,v).normalize()}return this}intersectsObject(e){if(void 0!==e.boundingSphere)null===e.boundingSphere&&e.computeBoundingSphere(),Hi.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;null===t.boundingSphere&&t.computeBoundingSphere(),Hi.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Hi)}intersectsSprite(e){Hi.center.set(0,0,0);const t=ji.distanceTo(e.center);return Hi.radius=.7071067811865476+t,Hi.applyMatrix4(e.matrixWorld),this.intersectsSphere(Hi)}intersectsSphere(e){const t=this.planes,n=e.center,r=-e.radius;for(let e=0;e<6;e++){if(t[e].distanceToPoint(n)<r)return!1}return!0}intersectsBox(e){const t=this.planes;for(let n=0;n<6;n++){const r=t[n];if(Wi.x=r.normal.x>0?e.max.x:e.min.x,Wi.y=r.normal.y>0?e.max.y:e.min.y,Wi.z=r.normal.z>0?e.max.z:e.min.z,r.distanceToPoint(Wi)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return(new this.constructor).copy(this)}}const qi=new Bn,$i=new Xi;class Yi{constructor(){this.coordinateSystem=yt}intersectsObject(e,t){if(!t.isArrayCamera||0===t.cameras.length)return!1;for(let n=0;n<t.cameras.length;n++){const r=t.cameras[n];if(qi.multiplyMatrices(r.projectionMatrix,r.matrixWorldInverse),$i.setFromProjectionMatrix(qi,this.coordinateSystem),$i.intersectsObject(e))return!0}return!1}intersectsSprite(e,t){if(!t||!t.cameras||0===t.cameras.length)return!1;for(let n=0;n<t.cameras.length;n++){const r=t.cameras[n];if(qi.multiplyMatrices(r.projectionMatrix,r.matrixWorldInverse),$i.setFromProjectionMatrix(qi,this.coordinateSystem),$i.intersectsSprite(e))return!0}return!1}intersectsSphere(e,t){if(!t||!t.cameras||0===t.cameras.length)return!1;for(let n=0;n<t.cameras.length;n++){const r=t.cameras[n];if(qi.multiplyMatrices(r.projectionMatrix,r.matrixWorldInverse),$i.setFromProjectionMatrix(qi,this.coordinateSystem),$i.intersectsSphere(e))return!0}return!1}intersectsBox(e,t){if(!t||!t.cameras||0===t.cameras.length)return!1;for(let n=0;n<t.cameras.length;n++){const r=t.cameras[n];if(qi.multiplyMatrices(r.projectionMatrix,r.matrixWorldInverse),$i.setFromProjectionMatrix(qi,this.coordinateSystem),$i.intersectsBox(e))return!0}return!1}containsPoint(e,t){if(!t||!t.cameras||0===t.cameras.length)return!1;for(let n=0;n<t.cameras.length;n++){const r=t.cameras[n];if(qi.multiplyMatrices(r.projectionMatrix,r.matrixWorldInverse),$i.setFromProjectionMatrix(qi,this.coordinateSystem),$i.containsPoint(e))return!0}return!1}clone(){return new Yi}}class Ki extends Dr{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new Nr(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}}const Qi=new Ut,Zi=new Ut,Ji=new Bn,es=new Fn,ts=new Cn,ns=new Ut,rs=new Ut;function is(e,t,n,r,i,s,a){const o=e.geometry.attributes.position;Qi.fromBufferAttribute(o,i),Zi.fromBufferAttribute(o,s);if(n.distanceSqToSegment(Qi,Zi,ns,rs)>r)return;ns.applyMatrix4(e.matrixWorld);const l=t.ray.origin.distanceTo(ns);return l<t.near||l>t.far?void 0:{distance:l,point:rs.clone().applyMatrix4(e.matrixWorld),index:a,face:null,faceIndex:null,barycoord:null,object:e}}class ss extends Dr{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new Nr(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 as extends sn{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=K,this.minFilter=K,this.generateMipmaps=!1,this.needsUpdate=!0}}class os extends sn{constructor(e,t,n=1014,r,i,s,a=1003,o=1003,l,u=1026,c=1){if(u!==_e&&u!==ve)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");super({width:e,height:t,depth:c},r,i,s,a,o,u,n,l),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new en(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 ls extends ei{constructor(e=1,t=1,n=1,r=32,i=1,s=!1,a=0,o=2*Math.PI){super(),this.type="CylinderGeometry",this.parameters={radiusTop:e,radiusBottom:t,height:n,radialSegments:r,heightSegments:i,openEnded:s,thetaStart:a,thetaLength:o};const l=this;r=Math.floor(r),i=Math.floor(i);const u=[],c=[],h=[],d=[];let p=0;const f=[],m=n/2;let g=0;function _(n){const i=p,s=new Dt,f=new Ut;let _=0;const v=!0===n?e:t,y=!0===n?1:-1;for(let e=1;e<=r;e++)c.push(0,m*y,0),h.push(0,y,0),d.push(.5,.5),p++;const x=p;for(let e=0;e<=r;e++){const t=e/r*o+a,n=Math.cos(t),i=Math.sin(t);f.x=v*i,f.y=m*y,f.z=v*n,c.push(f.x,f.y,f.z),h.push(0,y,0),s.x=.5*n+.5,s.y=.5*i*y+.5,d.push(s.x,s.y),p++}for(let e=0;e<r;e++){const t=i+e,r=x+e;!0===n?u.push(r,r+1,t):u.push(r+1,r,t),_+=3}l.addGroup(g,_,!0===n?1:2),g+=_}!function(){const s=new Ut,_=new Ut;let v=0;const y=(t-e)/n;for(let l=0;l<=i;l++){const u=[],g=l/i,v=g*(t-e)+e;for(let e=0;e<=r;e++){const t=e/r,i=t*o+a,l=Math.sin(i),f=Math.cos(i);_.x=v*l,_.y=-g*n+m,_.z=v*f,c.push(_.x,_.y,_.z),s.set(l,y,f).normalize(),h.push(s.x,s.y,s.z),d.push(t,1-g),u.push(p++)}f.push(u)}for(let n=0;n<r;n++)for(let r=0;r<i;r++){const s=f[r][n],a=f[r+1][n],o=f[r+1][n+1],l=f[r][n+1];(e>0||0!==r)&&(u.push(s,a,l),v+=3),(t>0||r!==i-1)&&(u.push(a,o,l),v+=3)}l.addGroup(g,v,0),g+=v}(),!1===s&&(e>0&&_(!0),t>0&&_(!1)),this.setIndex(u),this.setAttribute("position",new Xr(c,3)),this.setAttribute("normal",new Xr(h,3)),this.setAttribute("uv",new Xr(d,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new ls(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class us extends ls{constructor(e=1,t=1,n=32,r=1,i=!1,s=0,a=2*Math.PI){super(0,e,t,n,r,i,s,a),this.type="ConeGeometry",this.parameters={radius:e,height:t,radialSegments:n,heightSegments:r,openEnded:i,thetaStart:s,thetaLength:a}}static fromJSON(e){return new us(e.radius,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class cs{constructor(){this.type="Curve",this.arcLengthDivisions=200,this.needsUpdate=!1,this.cacheArcLengths=null}getPoint(){console.warn("THREE.Curve: .getPoint() not implemented.")}getPointAt(e,t){const n=this.getUtoTmapping(e);return this.getPoint(n,t)}getPoints(e=5){const t=[];for(let n=0;n<=e;n++)t.push(this.getPoint(n/e));return t}getSpacedPoints(e=5){const t=[];for(let n=0;n<=e;n++)t.push(this.getPointAt(n/e));return t}getLength(){const e=this.getLengths();return e[e.length-1]}getLengths(e=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;const t=[];let n,r=this.getPoint(0),i=0;t.push(0);for(let s=1;s<=e;s++)n=this.getPoint(s/e),i+=n.distanceTo(r),t.push(i),r=n;return this.cacheArcLengths=t,t}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(e,t=null){const n=this.getLengths();let r=0;const i=n.length;let s;s=t||e*n[i-1];let a,o=0,l=i-1;for(;o<=l;)if(r=Math.floor(o+(l-o)/2),a=n[r]-s,a<0)o=r+1;else{if(!(a>0)){l=r;break}l=r-1}if(r=l,n[r]===s)return r/(i-1);const u=n[r];return(r+(s-u)/(n[r+1]-u))/(i-1)}getTangent(e,t){const n=1e-4;let r=e-n,i=e+n;r<0&&(r=0),i>1&&(i=1);const s=this.getPoint(r),a=this.getPoint(i),o=t||(s.isVector2?new Dt:new Ut);return o.copy(a).sub(s).normalize(),o}getTangentAt(e,t){const n=this.getUtoTmapping(e);return this.getTangent(n,t)}computeFrenetFrames(e,t=!1){const n=new Ut,r=[],i=[],s=[],a=new Ut,o=new Bn;for(let t=0;t<=e;t++){const n=t/e;r[t]=this.getTangentAt(n,new Ut)}i[0]=new Ut,s[0]=new Ut;let l=Number.MAX_VALUE;const u=Math.abs(r[0].x),c=Math.abs(r[0].y),h=Math.abs(r[0].z);u<=l&&(l=u,n.set(1,0,0)),c<=l&&(l=c,n.set(0,1,0)),h<=l&&n.set(0,0,1),a.crossVectors(r[0],n).normalize(),i[0].crossVectors(r[0],a),s[0].crossVectors(r[0],i[0]);for(let t=1;t<=e;t++){if(i[t]=i[t-1].clone(),s[t]=s[t-1].clone(),a.crossVectors(r[t-1],r[t]),a.length()>Number.EPSILON){a.normalize();const e=Math.acos(At(r[t-1].dot(r[t]),-1,1));i[t].applyMatrix4(o.makeRotationAxis(a,e))}s[t].crossVectors(r[t],i[t])}if(!0===t){let t=Math.acos(At(i[0].dot(i[e]),-1,1));t/=e,r[0].dot(a.crossVectors(i[0],i[e]))>0&&(t=-t);for(let n=1;n<=e;n++)i[n].applyMatrix4(o.makeRotationAxis(r[n],t*n)),s[n].crossVectors(r[n],i[n])}return{tangents:r,normals:i,binormals:s}}clone(){return(new this.constructor).copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}toJSON(){const e={metadata:{version:4.7,type:"Curve",generator:"Curve.toJSON"}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e}fromJSON(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}}class hs extends cs{constructor(e=0,t=0,n=1,r=1,i=0,s=2*Math.PI,a=!1,o=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=e,this.aY=t,this.xRadius=n,this.yRadius=r,this.aStartAngle=i,this.aEndAngle=s,this.aClockwise=a,this.aRotation=o}getPoint(e,t=new Dt){const n=t,r=2*Math.PI;let i=this.aEndAngle-this.aStartAngle;const s=Math.abs(i)<Number.EPSILON;for(;i<0;)i+=r;for(;i>r;)i-=r;i<Number.EPSILON&&(i=s?0:r),!0!==this.aClockwise||s||(i===r?i=-r:i-=r);const a=this.aStartAngle+e*i;let o=this.aX+this.xRadius*Math.cos(a),l=this.aY+this.yRadius*Math.sin(a);if(0!==this.aRotation){const e=Math.cos(this.aRotation),t=Math.sin(this.aRotation),n=o-this.aX,r=l-this.aY;o=n*e-r*t+this.aX,l=n*t+r*e+this.aY}return n.set(o,l)}copy(e){return super.copy(e),this.aX=e.aX,this.aY=e.aY,this.xRadius=e.xRadius,this.yRadius=e.yRadius,this.aStartAngle=e.aStartAngle,this.aEndAngle=e.aEndAngle,this.aClockwise=e.aClockwise,this.aRotation=e.aRotation,this}toJSON(){const e=super.toJSON();return e.aX=this.aX,e.aY=this.aY,e.xRadius=this.xRadius,e.yRadius=this.yRadius,e.aStartAngle=this.aStartAngle,e.aEndAngle=this.aEndAngle,e.aClockwise=this.aClockwise,e.aRotation=this.aRotation,e}fromJSON(e){return super.fromJSON(e),this.aX=e.aX,this.aY=e.aY,this.xRadius=e.xRadius,this.yRadius=e.yRadius,this.aStartAngle=e.aStartAngle,this.aEndAngle=e.aEndAngle,this.aClockwise=e.aClockwise,this.aRotation=e.aRotation,this}}function ds(){let e=0,t=0,n=0,r=0;function i(i,s,a,o){e=i,t=a,n=-3*i+3*s-2*a-o,r=2*i-2*s+a+o}return{initCatmullRom:function(e,t,n,r,s){i(t,n,s*(n-e),s*(r-t))},initNonuniformCatmullRom:function(e,t,n,r,s,a,o){let l=(t-e)/s-(n-e)/(s+a)+(n-t)/a,u=(n-t)/a-(r-t)/(a+o)+(r-n)/o;l*=a,u*=a,i(t,n,l,u)},calc:function(i){const s=i*i;return e+t*i+n*s+r*(s*i)}}}const ps=new Ut,fs=new ds,ms=new ds,gs=new ds;function _s(e,t,n,r,i){const s=.5*(r-t),a=.5*(i-n),o=e*e;return(2*n-2*r+s+a)*(e*o)+(-3*n+3*r-2*s-a)*o+s*e+n}function vs(e,t,n,r){return function(e,t){const n=1-e;return n*n*t}(e,t)+function(e,t){return 2*(1-e)*e*t}(e,n)+function(e,t){return e*e*t}(e,r)}function ys(e,t,n,r,i){return function(e,t){const n=1-e;return n*n*n*t}(e,t)+function(e,t){const n=1-e;return 3*n*n*e*t}(e,n)+function(e,t){return 3*(1-e)*e*e*t}(e,r)+function(e,t){return e*e*e*t}(e,i)}class xs extends cs{constructor(e=new Ut,t=new Ut,n=new Ut,r=new Ut){super(),this.isCubicBezierCurve3=!0,this.type="CubicBezierCurve3",this.v0=e,this.v1=t,this.v2=n,this.v3=r}getPoint(e,t=new Ut){const n=t,r=this.v0,i=this.v1,s=this.v2,a=this.v3;return n.set(ys(e,r.x,i.x,s.x,a.x),ys(e,r.y,i.y,s.y,a.y),ys(e,r.z,i.z,s.z,a.z)),n}copy(e){return super.copy(e),this.v0.copy(e.v0),this.v1.copy(e.v1),this.v2.copy(e.v2),this.v3.copy(e.v3),this}toJSON(){const e=super.toJSON();return e.v0=this.v0.toArray(),e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e.v3=this.v3.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v0.fromArray(e.v0),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this.v3.fromArray(e.v3),this}}class bs extends cs{constructor(e=new Ut,t=new Ut,n=new Ut){super(),this.isQuadraticBezierCurve3=!0,this.type="QuadraticBezierCurve3",this.v0=e,this.v1=t,this.v2=n}getPoint(e,t=new Ut){const n=t,r=this.v0,i=this.v1,s=this.v2;return n.set(vs(e,r.x,i.x,s.x),vs(e,r.y,i.y,s.y),vs(e,r.z,i.z,s.z)),n}copy(e){return super.copy(e),this.v0.copy(e.v0),this.v1.copy(e.v1),this.v2.copy(e.v2),this}toJSON(){const e=super.toJSON();return e.v0=this.v0.toArray(),e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v0.fromArray(e.v0),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this}}var Ts=Object.freeze({__proto__:null,ArcCurve:class extends hs{constructor(e,t,n,r,i,s){super(e,t,n,n,r,i,s),this.isArcCurve=!0,this.type="ArcCurve"}},CatmullRomCurve3:class extends cs{constructor(e=[],t=!1,n="centripetal",r=.5){super(),this.isCatmullRomCurve3=!0,this.type="CatmullRomCurve3",this.points=e,this.closed=t,this.curveType=n,this.tension=r}getPoint(e,t=new Ut){const n=t,r=this.points,i=r.length,s=(i-(this.closed?0:1))*e;let a,o,l=Math.floor(s),u=s-l;this.closed?l+=l>0?0:(Math.floor(Math.abs(l)/i)+1)*i:0===u&&l===i-1&&(l=i-2,u=1),this.closed||l>0?a=r[(l-1)%i]:(ps.subVectors(r[0],r[1]).add(r[0]),a=ps);const c=r[l%i],h=r[(l+1)%i];if(this.closed||l+2<i?o=r[(l+2)%i]:(ps.subVectors(r[i-1],r[i-2]).add(r[i-1]),o=ps),"centripetal"===this.curveType||"chordal"===this.curveType){const e="chordal"===this.curveType?.5:.25;let t=Math.pow(a.distanceToSquared(c),e),n=Math.pow(c.distanceToSquared(h),e),r=Math.pow(h.distanceToSquared(o),e);n<1e-4&&(n=1),t<1e-4&&(t=n),r<1e-4&&(r=n),fs.initNonuniformCatmullRom(a.x,c.x,h.x,o.x,t,n,r),ms.initNonuniformCatmullRom(a.y,c.y,h.y,o.y,t,n,r),gs.initNonuniformCatmullRom(a.z,c.z,h.z,o.z,t,n,r)}else"catmullrom"===this.curveType&&(fs.initCatmullRom(a.x,c.x,h.x,o.x,this.tension),ms.initCatmullRom(a.y,c.y,h.y,o.y,this.tension),gs.initCatmullRom(a.z,c.z,h.z,o.z,this.tension));return n.set(fs.calc(u),ms.calc(u),gs.calc(u)),n}copy(e){super.copy(e),this.points=[];for(let t=0,n=e.points.length;t<n;t++){const n=e.points[t];this.points.push(n.clone())}return this.closed=e.closed,this.curveType=e.curveType,this.tension=e.tension,this}toJSON(){const e=super.toJSON();e.points=[];for(let t=0,n=this.points.length;t<n;t++){const n=this.points[t];e.points.push(n.toArray())}return e.closed=this.closed,e.curveType=this.curveType,e.tension=this.tension,e}fromJSON(e){super.fromJSON(e),this.points=[];for(let t=0,n=e.points.length;t<n;t++){const n=e.points[t];this.points.push((new Ut).fromArray(n))}return this.closed=e.closed,this.curveType=e.curveType,this.tension=e.tension,this}},CubicBezierCurve:class extends cs{constructor(e=new Dt,t=new Dt,n=new Dt,r=new Dt){super(),this.isCubicBezierCurve=!0,this.type="CubicBezierCurve",this.v0=e,this.v1=t,this.v2=n,this.v3=r}getPoint(e,t=new Dt){const n=t,r=this.v0,i=this.v1,s=this.v2,a=this.v3;return n.set(ys(e,r.x,i.x,s.x,a.x),ys(e,r.y,i.y,s.y,a.y)),n}copy(e){return super.copy(e),this.v0.copy(e.v0),this.v1.copy(e.v1),this.v2.copy(e.v2),this.v3.copy(e.v3),this}toJSON(){const e=super.toJSON();return e.v0=this.v0.toArray(),e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e.v3=this.v3.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v0.fromArray(e.v0),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this.v3.fromArray(e.v3),this}},CubicBezierCurve3:xs,EllipseCurve:hs,LineCurve:class extends cs{constructor(e=new Dt,t=new Dt){super(),this.isLineCurve=!0,this.type="LineCurve",this.v1=e,this.v2=t}getPoint(e,t=new Dt){const n=t;return 1===e?n.copy(this.v2):(n.copy(this.v2).sub(this.v1),n.multiplyScalar(e).add(this.v1)),n}getPointAt(e,t){return this.getPoint(e,t)}getTangent(e,t=new Dt){return t.subVectors(this.v2,this.v1).normalize()}getTangentAt(e,t){return this.getTangent(e,t)}copy(e){return super.copy(e),this.v1.copy(e.v1),this.v2.copy(e.v2),this}toJSON(){const e=super.toJSON();return e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this}},LineCurve3:class extends cs{constructor(e=new Ut,t=new Ut){super(),this.isLineCurve3=!0,this.type="LineCurve3",this.v1=e,this.v2=t}getPoint(e,t=new Ut){const n=t;return 1===e?n.copy(this.v2):(n.copy(this.v2).sub(this.v1),n.multiplyScalar(e).add(this.v1)),n}getPointAt(e,t){return this.getPoint(e,t)}getTangent(e,t=new Ut){return t.subVectors(this.v2,this.v1).normalize()}getTangentAt(e,t){return this.getTangent(e,t)}copy(e){return super.copy(e),this.v1.copy(e.v1),this.v2.copy(e.v2),this}toJSON(){const e=super.toJSON();return e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this}},QuadraticBezierCurve:class extends cs{constructor(e=new Dt,t=new Dt,n=new Dt){super(),this.isQuadraticBezierCurve=!0,this.type="QuadraticBezierCurve",this.v0=e,this.v1=t,this.v2=n}getPoint(e,t=new Dt){const n=t,r=this.v0,i=this.v1,s=this.v2;return n.set(vs(e,r.x,i.x,s.x),vs(e,r.y,i.y,s.y)),n}copy(e){return super.copy(e),this.v0.copy(e.v0),this.v1.copy(e.v1),this.v2.copy(e.v2),this}toJSON(){const e=super.toJSON();return e.v0=this.v0.toArray(),e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v0.fromArray(e.v0),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this}},QuadraticBezierCurve3:bs,SplineCurve:class extends cs{constructor(e=[]){super(),this.isSplineCurve=!0,this.type="SplineCurve",this.points=e}getPoint(e,t=new Dt){const n=t,r=this.points,i=(r.length-1)*e,s=Math.floor(i),a=i-s,o=r[0===s?s:s-1],l=r[s],u=r[s>r.length-2?r.length-1:s+1],c=r[s>r.length-3?r.length-1:s+2];return n.set(_s(a,o.x,l.x,u.x,c.x),_s(a,o.y,l.y,u.y,c.y)),n}copy(e){super.copy(e),this.points=[];for(let t=0,n=e.points.length;t<n;t++){const n=e.points[t];this.points.push(n.clone())}return this}toJSON(){const e=super.toJSON();e.points=[];for(let t=0,n=this.points.length;t<n;t++){const n=this.points[t];e.points.push(n.toArray())}return e}fromJSON(e){super.fromJSON(e),this.points=[];for(let t=0,n=e.points.length;t<n;t++){const n=e.points[t];this.points.push((new Dt).fromArray(n))}return this}}});class Ss extends ei{constructor(e=1,t=1,n=1,r=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:n,heightSegments:r};const i=e/2,s=t/2,a=Math.floor(n),o=Math.floor(r),l=a+1,u=o+1,c=e/a,h=t/o,d=[],p=[],f=[],m=[];for(let e=0;e<u;e++){const t=e*h-s;for(let n=0;n<l;n++){const r=n*c-i;p.push(r,-t,0),f.push(0,0,1),m.push(n/a),m.push(1-e/o)}}for(let e=0;e<o;e++)for(let t=0;t<a;t++){const n=t+l*e,r=t+l*(e+1),i=t+1+l*(e+1),s=t+1+l*e;d.push(n,r,s),d.push(r,i,s)}this.setIndex(d),this.setAttribute("position",new Xr(p,3)),this.setAttribute("normal",new Xr(f,3)),this.setAttribute("uv",new Xr(m,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Ss(e.width,e.height,e.widthSegments,e.heightSegments)}}class Ms extends ei{constructor(e=1,t=32,n=16,r=0,i=2*Math.PI,s=0,a=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:e,widthSegments:t,heightSegments:n,phiStart:r,phiLength:i,thetaStart:s,thetaLength:a},t=Math.max(3,Math.floor(t)),n=Math.max(2,Math.floor(n));const o=Math.min(s+a,Math.PI);let l=0;const u=[],c=new Ut,h=new Ut,d=[],p=[],f=[],m=[];for(let d=0;d<=n;d++){const g=[],_=d/n;let v=0;0===d&&0===s?v=.5/t:d===n&&o===Math.PI&&(v=-.5/t);for(let n=0;n<=t;n++){const o=n/t;c.x=-e*Math.cos(r+o*i)*Math.sin(s+_*a),c.y=e*Math.cos(s+_*a),c.z=e*Math.sin(r+o*i)*Math.sin(s+_*a),p.push(c.x,c.y,c.z),h.copy(c).normalize(),f.push(h.x,h.y,h.z),m.push(o+v,1-_),g.push(l++)}u.push(g)}for(let e=0;e<n;e++)for(let r=0;r<t;r++){const t=u[e][r+1],i=u[e][r],a=u[e+1][r],l=u[e+1][r+1];(0!==e||s>0)&&d.push(t,i,l),(e!==n-1||o<Math.PI)&&d.push(i,a,l)}this.setIndex(d),this.setAttribute("position",new Xr(p,3)),this.setAttribute("normal",new Xr(f,3)),this.setAttribute("uv",new Xr(m,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Ms(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}}class ws extends ei{constructor(e=new bs(new Ut(-1,-1,0),new Ut(-1,1,0),new Ut(1,1,0)),t=64,n=1,r=8,i=!1){super(),this.type="TubeGeometry",this.parameters={path:e,tubularSegments:t,radius:n,radialSegments:r,closed:i};const s=e.computeFrenetFrames(t,i);this.tangents=s.tangents,this.normals=s.normals,this.binormals=s.binormals;const a=new Ut,o=new Ut,l=new Dt;let u=new Ut;const c=[],h=[],d=[],p=[];function f(i){u=e.getPointAt(i/t,u);const l=s.normals[i],d=s.binormals[i];for(let e=0;e<=r;e++){const t=e/r*Math.PI*2,i=Math.sin(t),s=-Math.cos(t);o.x=s*l.x+i*d.x,o.y=s*l.y+i*d.y,o.z=s*l.z+i*d.z,o.normalize(),h.push(o.x,o.y,o.z),a.x=u.x+n*o.x,a.y=u.y+n*o.y,a.z=u.z+n*o.z,c.push(a.x,a.y,a.z)}}!function(){for(let e=0;e<t;e++)f(e);f(!1===i?t:0),function(){for(let e=0;e<=t;e++)for(let n=0;n<=r;n++)l.x=e/t,l.y=n/r,d.push(l.x,l.y)}(),function(){for(let e=1;e<=t;e++)for(let t=1;t<=r;t++){const n=(r+1)*(e-1)+(t-1),i=(r+1)*e+(t-1),s=(r+1)*e+t,a=(r+1)*(e-1)+t;p.push(n,i,a),p.push(i,s,a)}}()}(),this.setIndex(p),this.setAttribute("position",new Xr(c,3)),this.setAttribute("normal",new Xr(h,3)),this.setAttribute("uv",new Xr(d,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}toJSON(){const e=super.toJSON();return e.path=this.parameters.path.toJSON(),e}static fromJSON(e){return new ws((new Ts[e.path.type]).fromJSON(e.path),e.tubularSegments,e.radius,e.radialSegments,e.closed)}}class Es extends Dr{constructor(e){super(),this.isShadowMaterial=!0,this.type="ShadowMaterial",this.color=new Nr(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 As extends Dr{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new Nr(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 Nr(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 $n,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 Rs extends As{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 At(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 Nr(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 Nr(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new Nr(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 Cs extends Dr{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new Nr(16777215),this.specular=new Nr(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Nr(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 $n,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Ns extends Dr{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new Nr(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Nr(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 Ps extends Dr{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 Ls extends Dr{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new Nr(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Nr(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 $n,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Ds extends Dr{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=3200,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class Is extends Dr{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}class Us extends Dr{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new Nr(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.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.flatShading=e.flatShading,this.fog=e.fog,this}}class Os extends Ki{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}}const Fs={enabled:!1,files:{},add:function(e,t){!1!==this.enabled&&(this.files[e]=t)},get:function(e){if(!1!==this.enabled)return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}};class Bs{constructor(e,t,n){const r=this;let i,s=!1,a=0,o=0;const l=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=n,this.itemStart=function(e){o++,!1===s&&void 0!==r.onStart&&r.onStart(e,a,o),s=!0},this.itemEnd=function(e){a++,void 0!==r.onProgress&&r.onProgress(e,a,o),a===o&&(s=!1,void 0!==r.onLoad&&r.onLoad())},this.itemError=function(e){void 0!==r.onError&&r.onError(e)},this.resolveURL=function(e){return i?i(e):e},this.setURLModifier=function(e){return i=e,this},this.addHandler=function(e,t){return l.push(e,t),this},this.removeHandler=function(e){const t=l.indexOf(e);return-1!==t&&l.splice(t,2),this},this.getHandler=function(e){for(let t=0,n=l.length;t<n;t+=2){const n=l[t],r=l[t+1];if(n.global&&(n.lastIndex=0),n.test(e))return r}return null}}}const ks=new Bs;class zs{constructor(e){this.manager=void 0!==e?e:ks,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={}}load(){}loadAsync(e,t){const n=this;return new Promise(function(r,i){n.load(e,r,t,i)})}parse(){}setCrossOrigin(e){return this.crossOrigin=e,this}setWithCredentials(e){return this.withCredentials=e,this}setPath(e){return this.path=e,this}setResourcePath(e){return this.resourcePath=e,this}setRequestHeader(e){return this.requestHeader=e,this}}zs.DEFAULT_MATERIAL_NAME="__DEFAULT";const Vs=new WeakMap;class Gs extends zs{constructor(e){super(e)}load(e,t,n,r){void 0!==this.path&&(e=this.path+e),e=this.manager.resolveURL(e);const i=this,s=Fs.get(`image:${e}`);if(void 0!==s){if(!0===s.complete)i.manager.itemStart(e),setTimeout(function(){t&&t(s),i.manager.itemEnd(e)},0);else{let e=Vs.get(s);void 0===e&&(e=[],Vs.set(s,e)),e.push({onLoad:t,onError:r})}return s}const a=Vt("img");function o(){u(),t&&t(this);const n=Vs.get(this)||[];for(let e=0;e<n.length;e++){const t=n[e];t.onLoad&&t.onLoad(this)}Vs.delete(this),i.manager.itemEnd(e)}function l(t){u(),r&&r(t),Fs.remove(`image:${e}`);const n=Vs.get(this)||[];for(let e=0;e<n.length;e++){const r=n[e];r.onError&&r.onError(t)}Vs.delete(this),i.manager.itemError(e),i.manager.itemEnd(e)}function u(){a.removeEventListener("load",o,!1),a.removeEventListener("error",l,!1)}return a.addEventListener("load",o,!1),a.addEventListener("error",l,!1),"data:"!==e.slice(0,5)&&void 0!==this.crossOrigin&&(a.crossOrigin=this.crossOrigin),Fs.add(`image:${e}`,a),i.manager.itemStart(e),a.src=e,a}}class Hs extends hr{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new Nr(e),this.intensity=t}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,void 0!==this.groundColor&&(t.object.groundColor=this.groundColor.getHex()),void 0!==this.distance&&(t.object.distance=this.distance),void 0!==this.angle&&(t.object.angle=this.angle),void 0!==this.decay&&(t.object.decay=this.decay),void 0!==this.penumbra&&(t.object.penumbra=this.penumbra),void 0!==this.shadow&&(t.object.shadow=this.shadow.toJSON()),void 0!==this.target&&(t.object.target=this.target.uuid),t}}class js extends Hs{constructor(e,t,n){super(e,n),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(hr.DEFAULT_UP),this.updateMatrix(),this.groundColor=new Nr(t)}copy(e,t){return super.copy(e,t),this.groundColor.copy(e.groundColor),this}}const Ws=new Bn,Xs=new Ut,qs=new Ut;class $s{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new Dt(512,512),this.mapType=ne,this.map=null,this.mapPass=null,this.matrix=new Bn,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new Xi,this._frameExtents=new Dt(1,1),this._viewportCount=1,this._viewports=[new an(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const t=this.camera,n=this.matrix;Xs.setFromMatrixPosition(e.matrixWorld),t.position.copy(Xs),qs.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(qs),t.updateMatrixWorld(),Ws.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(Ws),n.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),n.multiply(Ws)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(e){return this.camera=e.camera.clone(),this.intensity=e.intensity,this.bias=e.bias,this.radius=e.radius,this.autoUpdate=e.autoUpdate,this.needsUpdate=e.needsUpdate,this.normalBias=e.normalBias,this.blurSamples=e.blurSamples,this.mapSize.copy(e.mapSize),this}clone(){return(new this.constructor).copy(this)}toJSON(){const e={};return 1!==this.intensity&&(e.intensity=this.intensity),0!==this.bias&&(e.bias=this.bias),0!==this.normalBias&&(e.normalBias=this.normalBias),1!==this.radius&&(e.radius=this.radius),512===this.mapSize.x&&512===this.mapSize.y||(e.mapSize=this.mapSize.toArray()),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}}class Ys extends $s{constructor(){super(new Mi(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1,this.aspect=1}updateMatrices(e){const t=this.camera,n=2*wt*e.angle*this.focus,r=this.mapSize.width/this.mapSize.height*this.aspect,i=e.distance||t.far;n===t.fov&&r===t.aspect&&i===t.far||(t.fov=n,t.aspect=r,t.far=i,t.updateProjectionMatrix()),super.updateMatrices(e)}copy(e){return super.copy(e),this.focus=e.focus,this}}class Ks extends Hs{constructor(e,t,n=0,r=Math.PI/3,i=0,s=2){super(e,t),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(hr.DEFAULT_UP),this.updateMatrix(),this.target=new hr,this.distance=n,this.angle=r,this.penumbra=i,this.decay=s,this.map=null,this.shadow=new Ys}get power(){return this.intensity*Math.PI}set power(e){this.intensity=e/Math.PI}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.shadow=e.shadow.clone(),this}}const Qs=new Bn,Zs=new Ut,Js=new Ut;class ea extends $s{constructor(){super(new Mi(90,1,.5,500)),this.isPointLightShadow=!0,this._frameExtents=new Dt(4,2),this._viewportCount=6,this._viewports=[new an(2,1,1,1),new an(0,1,1,1),new an(3,1,1,1),new an(1,1,1,1),new an(3,0,1,1),new an(1,0,1,1)],this._cubeDirections=[new Ut(1,0,0),new Ut(-1,0,0),new Ut(0,0,1),new Ut(0,0,-1),new Ut(0,1,0),new Ut(0,-1,0)],this._cubeUps=[new Ut(0,1,0),new Ut(0,1,0),new Ut(0,1,0),new Ut(0,1,0),new Ut(0,0,1),new Ut(0,0,-1)]}updateMatrices(e,t=0){const n=this.camera,r=this.matrix,i=e.distance||n.far;i!==n.far&&(n.far=i,n.updateProjectionMatrix()),Zs.setFromMatrixPosition(e.matrixWorld),n.position.copy(Zs),Js.copy(n.position),Js.add(this._cubeDirections[t]),n.up.copy(this._cubeUps[t]),n.lookAt(Js),n.updateMatrixWorld(),r.makeTranslation(-Zs.x,-Zs.y,-Zs.z),Qs.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse),this._frustum.setFromProjectionMatrix(Qs)}}class ta extends Hs{constructor(e,t,n=0,r=2){super(e,t),this.isPointLight=!0,this.type="PointLight",this.distance=n,this.decay=r,this.shadow=new ea}get power(){return 4*this.intensity*Math.PI}set power(e){this.intensity=e/(4*Math.PI)}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}}class na extends xi{constructor(e=-1,t=1,n=1,r=-1,i=.1,s=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=n,this.bottom=r,this.near=i,this.far=s,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,n,r,i,s){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=n,this.view.offsetY=r,this.view.width=i,this.view.height=s,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),n=(this.right+this.left)/2,r=(this.top+this.bottom)/2;let i=n-e,s=n+e,a=r+t,o=r-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;i+=e*this.view.offsetX,s=i+e*this.view.width,a-=t*this.view.offsetY,o=a-t*this.view.height}this.projectionMatrix.makeOrthographic(i,s,a,o,this.near,this.far,this.coordinateSystem),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 ra extends $s{constructor(){super(new na(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class ia extends Hs{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(hr.DEFAULT_UP),this.updateMatrix(),this.target=new hr,this.shadow=new ra}dispose(){this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}}class sa extends Hs{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type="AmbientLight"}}class aa extends Hs{constructor(e,t,n=10,r=10){super(e,t),this.isRectAreaLight=!0,this.type="RectAreaLight",this.width=n,this.height=r}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 oa{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let e=0;e<9;e++)this.coefficients.push(new Ut)}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 n=e.x,r=e.y,i=e.z,s=this.coefficients;return t.copy(s[0]).multiplyScalar(.282095),t.addScaledVector(s[1],.488603*r),t.addScaledVector(s[2],.488603*i),t.addScaledVector(s[3],.488603*n),t.addScaledVector(s[4],n*r*1.092548),t.addScaledVector(s[5],r*i*1.092548),t.addScaledVector(s[6],.315392*(3*i*i-1)),t.addScaledVector(s[7],n*i*1.092548),t.addScaledVector(s[8],.546274*(n*n-r*r)),t}getIrradianceAt(e,t){const n=e.x,r=e.y,i=e.z,s=this.coefficients;return t.copy(s[0]).multiplyScalar(.886227),t.addScaledVector(s[1],1.023328*r),t.addScaledVector(s[2],1.023328*i),t.addScaledVector(s[3],1.023328*n),t.addScaledVector(s[4],.858086*n*r),t.addScaledVector(s[5],.858086*r*i),t.addScaledVector(s[6],.743125*i*i-.247708),t.addScaledVector(s[7],.858086*n*i),t.addScaledVector(s[8],.429043*(n*n-r*r)),t}add(e){for(let t=0;t<9;t++)this.coefficients[t].add(e.coefficients[t]);return this}addScaledSH(e,t){for(let n=0;n<9;n++)this.coefficients[n].addScaledVector(e.coefficients[n],t);return this}scale(e){for(let t=0;t<9;t++)this.coefficients[t].multiplyScalar(e);return this}lerp(e,t){for(let n=0;n<9;n++)this.coefficients[n].lerp(e.coefficients[n],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 n=this.coefficients;for(let r=0;r<9;r++)n[r].fromArray(e,t+3*r);return this}toArray(e=[],t=0){const n=this.coefficients;for(let r=0;r<9;r++)n[r].toArray(e,t+3*r);return e}static getBasisAt(e,t){const n=e.x,r=e.y,i=e.z;t[0]=.282095,t[1]=.488603*r,t[2]=.488603*i,t[3]=.488603*n,t[4]=1.092548*n*r,t[5]=1.092548*r*i,t[6]=.315392*(3*i*i-1),t[7]=1.092548*n*i,t[8]=.546274*(n*n-r*r)}}class la extends Hs{constructor(e=new oa,t=1){super(void 0,t),this.isLightProbe=!0,this.sh=e}copy(e){return super.copy(e),this.sh.copy(e.sh),this}fromJSON(e){return this.intensity=e.intensity,this.sh.fromArray(e.sh),this}toJSON(e){const t=super.toJSON(e);return t.object.sh=this.sh.toArray(),t}}class ua extends Mi{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class ca{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=performance.now(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){const t=performance.now();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}}class ha extends Di{constructor(e,t,n=1){super(e,t),this.isInstancedInterleavedBuffer=!0,this.meshPerAttribute=n}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}}const da=new Bn;class pa{constructor(e,t,n=0,r=1/0){this.ray=new Fn(e,t),this.near=n,this.far=r,this.camera=null,this.layers=new Yn,this.params={Mesh:{},Line:{threshold:1},LOD:{},Points:{threshold:1},Sprite:{}}}set(e,t){this.ray.set(e,t)}setFromCamera(e,t){t.isPerspectiveCamera?(this.ray.origin.setFromMatrixPosition(t.matrixWorld),this.ray.direction.set(e.x,e.y,.5).unproject(t).sub(this.ray.origin).normalize(),this.camera=t):t.isOrthographicCamera?(this.ray.origin.set(e.x,e.y,(t.near+t.far)/(t.near-t.far)).unproject(t),this.ray.direction.set(0,0,-1).transformDirection(t.matrixWorld),this.camera=t):console.error("THREE.Raycaster: Unsupported camera type: "+t.type)}setFromXRController(e){return da.identity().extractRotation(e.matrixWorld),this.ray.origin.setFromMatrixPosition(e.matrixWorld),this.ray.direction.set(0,0,-1).applyMatrix4(da),this}intersectObject(e,t=!0,n=[]){return ma(e,this,n,t),n.sort(fa),n}intersectObjects(e,t=!0,n=[]){for(let r=0,i=e.length;r<i;r++)ma(e[r],this,n,t);return n.sort(fa),n}}function fa(e,t){return e.distance-t.distance}function ma(e,t,n,r){let i=!0;if(e.layers.test(t.layers)){!1===e.raycast(t,n)&&(i=!1)}if(!0===i&&!0===r){const r=e.children;for(let e=0,i=r.length;e<i;e++)ma(r[e],t,n,!0)}}class ga{constructor(e=1,t=0,n=0){this.radius=e,this.phi=t,this.theta=n}set(e,t,n){return this.radius=e,this.phi=t,this.theta=n,this}copy(e){return this.radius=e.radius,this.phi=e.phi,this.theta=e.theta,this}makeSafe(){const e=1e-6;return this.phi=At(this.phi,e,Math.PI-e),this}setFromVector3(e){return this.setFromCartesianCoords(e.x,e.y,e.z)}setFromCartesianCoords(e,t,n){return this.radius=Math.sqrt(e*e+t*t+n*n),0===this.radius?(this.theta=0,this.phi=0):(this.theta=Math.atan2(e,n),this.phi=Math.acos(At(t/this.radius,-1,1))),this}clone(){return(new this.constructor).copy(this)}}class _a{constructor(e,t,n,r){_a.prototype.isMatrix2=!0,this.elements=[1,0,0,1],void 0!==e&&this.set(e,t,n,r)}identity(){return this.set(1,0,0,1),this}fromArray(e,t=0){for(let n=0;n<4;n++)this.elements[n]=e[n+t];return this}set(e,t,n,r){const i=this.elements;return i[0]=e,i[2]=t,i[1]=n,i[3]=r,this}}class va extends bt{constructor(e,t=null){super(),this.object=e,this.domElement=t,this.enabled=!0,this.state=-1,this.keys={},this.mouseButtons={LEFT:null,MIDDLE:null,RIGHT:null},this.touches={ONE:null,TWO:null}}connect(e){void 0!==e?(null!==this.domElement&&this.disconnect(),this.domElement=e):console.warn("THREE.Controls: connect() now requires an element.")}disconnect(){}dispose(){}update(){}}function ya(e,t,n,r){const i=function(e){switch(e){case ne:case re:return{byteLength:1,components:1};case se:case ie:case ue:return{byteLength:2,components:1};case ce:case he:return{byteLength:2,components:4};case oe:case ae:case le:return{byteLength:4,components:1};case pe:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${e}.`)}(r);switch(n){case fe:return e*t;case ye:case xe:return e*t/i.components*i.byteLength;case be:case Te:return e*t*2/i.components*i.byteLength;case me:return e*t*3/i.components*i.byteLength;case ge:case Se:return e*t*4/i.components*i.byteLength;case Me:case we:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case Ee:case Ae:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case Ce:case Pe:return Math.max(e,16)*Math.max(t,8)/4;case Re:case Ne:return Math.max(e,8)*Math.max(t,8)/2;case Le:case De:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case Ie:case Ue:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case Oe:return Math.floor((e+4)/5)*Math.floor((t+3)/4)*16;case Fe:return Math.floor((e+4)/5)*Math.floor((t+4)/5)*16;case Be:return Math.floor((e+5)/6)*Math.floor((t+4)/5)*16;case ke:return Math.floor((e+5)/6)*Math.floor((t+5)/6)*16;case ze:return Math.floor((e+7)/8)*Math.floor((t+4)/5)*16;case Ve:return Math.floor((e+7)/8)*Math.floor((t+5)/6)*16;case Ge:return Math.floor((e+7)/8)*Math.floor((t+7)/8)*16;case He:return Math.floor((e+9)/10)*Math.floor((t+4)/5)*16;case je:return Math.floor((e+9)/10)*Math.floor((t+5)/6)*16;case We:return Math.floor((e+9)/10)*Math.floor((t+7)/8)*16;case Xe:return Math.floor((e+9)/10)*Math.floor((t+9)/10)*16;case qe: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 Ye:case Ke:case Qe:return Math.ceil(e/4)*Math.ceil(t/4)*16;case Ze:case Je:return Math.ceil(e/4)*Math.ceil(t/4)*8;case et:case tt:return Math.ceil(e/4)*Math.ceil(t/4)*16}throw new Error(`Unable to determine texture byte length for ${n} format.`)}function xa(){let e=null,t=!1,n=null,r=null;function i(t,s){n(t,s),r=e.requestAnimationFrame(i)}return{start:function(){!0!==t&&null!==n&&(r=e.requestAnimationFrame(i),t=!0)},stop:function(){e.cancelAnimationFrame(r),t=!1},setAnimationLoop:function(e){n=e},setContext:function(t){e=t}}}function ba(e){const t=new WeakMap;return{get:function(e){return e.isInterleavedBufferAttribute&&(e=e.data),t.get(e)},remove:function(n){n.isInterleavedBufferAttribute&&(n=n.data);const r=t.get(n);r&&(e.deleteBuffer(r.buffer),t.delete(n))},update:function(n,r){if(n.isInterleavedBufferAttribute&&(n=n.data),n.isGLBufferAttribute){const e=t.get(n);return void((!e||e.version<n.version)&&t.set(n,{buffer:n.buffer,type:n.type,bytesPerElement:n.elementSize,version:n.version}))}const i=t.get(n);if(void 0===i)t.set(n,function(t,n){const r=t.array,i=t.usage,s=r.byteLength,a=e.createBuffer();let o;if(e.bindBuffer(n,a),e.bufferData(n,r,i),t.onUploadCallback(),r instanceof Float32Array)o=e.FLOAT;else if("undefined"!=typeof Float16Array&&r instanceof Float16Array)o=e.HALF_FLOAT;else if(r instanceof Uint16Array)o=t.isFloat16BufferAttribute?e.HALF_FLOAT:e.UNSIGNED_SHORT;else if(r instanceof Int16Array)o=e.SHORT;else if(r instanceof Uint32Array)o=e.UNSIGNED_INT;else if(r instanceof Int32Array)o=e.INT;else if(r instanceof Int8Array)o=e.BYTE;else if(r instanceof Uint8Array)o=e.UNSIGNED_BYTE;else{if(!(r instanceof Uint8ClampedArray))throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+r);o=e.UNSIGNED_BYTE}return{buffer:a,type:o,bytesPerElement:r.BYTES_PER_ELEMENT,version:t.version,size:s}}(n,r));else if(i.version<n.version){if(i.size!==n.array.byteLength)throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.");!function(t,n,r){const i=n.array,s=n.updateRanges;if(e.bindBuffer(r,t),0===s.length)e.bufferSubData(r,0,i);else{s.sort((e,t)=>e.start-t.start);let t=0;for(let e=1;e<s.length;e++){const n=s[t],r=s[e];r.start<=n.start+n.count+1?n.count=Math.max(n.count,r.start+r.count-n.start):(++t,s[t]=r)}s.length=t+1;for(let t=0,n=s.length;t<n;t++){const n=s[t];e.bufferSubData(r,n.start*i.BYTES_PER_ELEMENT,i,n.start,n.count)}n.clearUpdateRanges()}n.onUploadCallback()}(i.buffer,n,r),i.version=n.version}}}}"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:s}})),"undefined"!=typeof window&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=s);const Ta={alphahash_fragment:"#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif",alphahash_pars_fragment:"#ifdef USE_ALPHAHASH\n\tconst float ALPHA_HASH_SCALE = 0.05;\n\tfloat hash2D( vec2 value ) {\n\t\treturn fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );\n\t}\n\tfloat hash3D( vec3 value ) {\n\t\treturn hash2D( vec2( hash2D( value.xy ), value.z ) );\n\t}\n\tfloat getAlphaHashThreshold( vec3 position ) {\n\t\tfloat maxDeriv = max(\n\t\t\tlength( dFdx( position.xyz ) ),\n\t\t\tlength( dFdy( position.xyz ) )\n\t\t);\n\t\tfloat pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );\n\t\tvec2 pixScales = vec2(\n\t\t\texp2( floor( log2( pixScale ) ) ),\n\t\t\texp2( ceil( log2( pixScale ) ) )\n\t\t);\n\t\tvec2 alpha = vec2(\n\t\t\thash3D( floor( pixScales.x * position.xyz ) ),\n\t\t\thash3D( floor( pixScales.y * position.xyz ) )\n\t\t);\n\t\tfloat lerpFactor = fract( log2( pixScale ) );\n\t\tfloat x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;\n\t\tfloat a = min( lerpFactor, 1.0 - lerpFactor );\n\t\tvec3 cases = vec3(\n\t\t\tx * x / ( 2.0 * a * ( 1.0 - a ) ),\n\t\t\t( x - 0.5 * a ) / ( 1.0 - a ),\n\t\t\t1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )\n\t\t);\n\t\tfloat threshold = ( x < ( 1.0 - a ) )\n\t\t\t? ( ( x < a ) ? cases.x : cases.y )\n\t\t\t: cases.z;\n\t\treturn clamp( threshold , 1.0e-6, 1.0 );\n\t}\n#endif",alphamap_fragment:"#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif",alphamap_pars_fragment:"#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif",alphatest_fragment:"#ifdef USE_ALPHATEST\n\t#ifdef ALPHA_TO_COVERAGE\n\tdiffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );\n\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\tif ( diffuseColor.a < alphaTest ) discard;\n\t#endif\n#endif",alphatest_pars_fragment:"#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif",aomap_fragment:"#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_CLEARCOAT ) \n\t\tclearcoatSpecularIndirect *= ambientOcclusion;\n\t#endif\n\t#if defined( USE_SHEEN ) \n\t\tsheenSpecularIndirect *= ambientOcclusion;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometryNormal, geometryViewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif",aomap_pars_fragment:"#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif",batching_pars_vertex:"#ifdef USE_BATCHING\n\t#if ! defined( GL_ANGLE_multi_draw )\n\t#define gl_DrawID _gl_DrawID\n\tuniform int _gl_DrawID;\n\t#endif\n\tuniform highp sampler2D batchingTexture;\n\tuniform highp usampler2D batchingIdTexture;\n\tmat4 getBatchingMatrix( const in float i ) {\n\t\tint size = textureSize( batchingTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n\tfloat getIndirectIndex( const in int i ) {\n\t\tint size = textureSize( batchingIdTexture, 0 ).x;\n\t\tint x = i % size;\n\t\tint y = i / size;\n\t\treturn float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r );\n\t}\n#endif\n#ifdef USE_BATCHING_COLOR\n\tuniform sampler2D batchingColorTexture;\n\tvec3 getBatchingColor( const in float i ) {\n\t\tint size = textureSize( batchingColorTexture, 0 ).x;\n\t\tint j = int( i );\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\treturn texelFetch( batchingColorTexture, ivec2( x, y ), 0 ).rgb;\n\t}\n#endif",batching_vertex:"#ifdef USE_BATCHING\n\tmat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );\n#endif",begin_vertex:"vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif",beginnormal_vertex:"vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif",bsdfs:"float G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n} // validated",iridescence_fragment:"#ifdef USE_IRIDESCENCE\n\tconst mat3 XYZ_TO_REC709 = mat3(\n\t\t 3.2404542, -0.9692660, 0.0556434,\n\t\t-1.5371385, 1.8760108, -0.2040259,\n\t\t-0.4985314, 0.0415560, 1.0572252\n\t);\n\tvec3 Fresnel0ToIor( vec3 fresnel0 ) {\n\t\tvec3 sqrtF0 = sqrt( fresnel0 );\n\t\treturn ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\n\t}\n\tvec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\n\t}\n\tfloat IorToFresnel0( float transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\n\t}\n\tvec3 evalSensitivity( float OPD, vec3 shift ) {\n\t\tfloat phase = 2.0 * PI * OPD * 1.0e-9;\n\t\tvec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\n\t\tvec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\n\t\tvec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\n\t\tvec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );\n\t\txyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );\n\t\txyz /= 1.0685e-7;\n\t\tvec3 rgb = XYZ_TO_REC709 * xyz;\n\t\treturn rgb;\n\t}\n\tvec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\n\t\tvec3 I;\n\t\tfloat iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\n\t\tfloat sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\n\t\tfloat cosTheta2Sq = 1.0 - sinTheta2Sq;\n\t\tif ( cosTheta2Sq < 0.0 ) {\n\t\t\treturn vec3( 1.0 );\n\t\t}\n\t\tfloat cosTheta2 = sqrt( cosTheta2Sq );\n\t\tfloat R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\n\t\tfloat R12 = F_Schlick( R0, 1.0, cosTheta1 );\n\t\tfloat T121 = 1.0 - R12;\n\t\tfloat phi12 = 0.0;\n\t\tif ( iridescenceIOR < outsideIOR ) phi12 = PI;\n\t\tfloat phi21 = PI - phi12;\n\t\tvec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );\t\tvec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\n\t\tvec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\n\t\tvec3 phi23 = vec3( 0.0 );\n\t\tif ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;\n\t\tif ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;\n\t\tif ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;\n\t\tfloat OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\n\t\tvec3 phi = vec3( phi21 ) + phi23;\n\t\tvec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\n\t\tvec3 r123 = sqrt( R123 );\n\t\tvec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\n\t\tvec3 C0 = R12 + Rs;\n\t\tI = C0;\n\t\tvec3 Cm = Rs - T121;\n\t\tfor ( int m = 1; m <= 2; ++ m ) {\n\t\t\tCm *= r123;\n\t\t\tvec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\n\t\t\tI += Cm * Sm;\n\t\t}\n\t\treturn max( I, vec3( 0.0 ) );\n\t}\n#endif",bumpmap_pars_fragment:"#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vBumpMapUv );\n\t\tvec2 dSTdy = dFdy( vBumpMapUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );\n\t\tvec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif",clipping_planes_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#ifdef ALPHA_TO_COVERAGE\n\t\tfloat distanceToPlane, distanceGradient;\n\t\tfloat clipOpacity = 1.0;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\tclipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\tif ( clipOpacity == 0.0 ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tfloat unionClipOpacity = 1.0;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\t\tunionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tclipOpacity *= 1.0 - unionClipOpacity;\n\t\t#endif\n\t\tdiffuseColor.a *= clipOpacity;\n\t\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tbool clipped = true;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tif ( clipped ) discard;\n\t\t#endif\n\t#endif\n#endif",clipping_planes_pars_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif",clipping_planes_pars_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif",clipping_planes_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif",color_fragment:"#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif",color_pars_fragment:"#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif",color_pars_vertex:"#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvarying vec3 vColor;\n#endif",color_vertex:"#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif\n#ifdef USE_BATCHING_COLOR\n\tvec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) );\n\tvColor.xyz *= batchingColor.xyz;\n#endif",common:"#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\n#ifdef USE_ALPHAHASH\n\tvarying vec3 vPosition;\n#endif\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}\nvec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n} // validated",cube_uv_reflection_fragment:"#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\thighp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define cubeUV_r0 1.0\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif",defaultnormal_vertex:"vec3 transformedNormal = objectNormal;\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = objectTangent;\n#endif\n#ifdef USE_BATCHING\n\tmat3 bm = mat3( batchingMatrix );\n\ttransformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );\n\ttransformedNormal = bm * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = bm * transformedTangent;\n\t#endif\n#endif\n#ifdef USE_INSTANCING\n\tmat3 im = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );\n\ttransformedNormal = im * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = im * transformedTangent;\n\t#endif\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\ttransformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif",displacementmap_pars_vertex:"#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif",displacementmap_vertex:"#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif",emissivemap_fragment:"#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE_EMISSIVE\n\t\temissiveColor = sRGBTransferEOTF( emissiveColor );\n\t#endif\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif",emissivemap_pars_fragment:"#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif",colorspace_fragment:"gl_FragColor = linearToOutputTexel( gl_FragColor );",colorspace_pars_fragment:"vec4 LinearTransferOETF( in vec4 value ) {\n\treturn value;\n}\nvec4 sRGBTransferEOTF( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 sRGBTransferOETF( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}",envmap_fragment:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif",envmap_common_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform mat3 envMapRotation;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif",envmap_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif",envmap_pars_vertex:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif",envmap_physical_pars_fragment:"#ifdef USE_ENVMAP\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\t#ifdef USE_ANISOTROPY\n\t\tvec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n\t\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\t\tvec3 bentNormal = cross( bitangent, viewDir );\n\t\t\t\tbentNormal = normalize( cross( bentNormal, bitangent ) );\n\t\t\t\tbentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n\t\t\t\treturn getIBLRadiance( viewDir, bentNormal, roughness );\n\t\t\t#else\n\t\t\t\treturn vec3( 0.0 );\n\t\t\t#endif\n\t\t}\n\t#endif\n#endif",envmap_vertex:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif",fog_vertex:"#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif",fog_pars_vertex:"#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif",fog_fragment:"#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif",fog_pars_fragment:"#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif",gradientmap_pars_fragment:"#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\tvec2 fw = fwidth( coord ) * 0.5;\n\t\treturn mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n\t#endif\n}",lightmap_pars_fragment:"#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif",lights_lambert_fragment:"LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;",lights_lambert_pars_fragment:"varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert",lights_pars_begin:"uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\n#if defined( USE_LIGHT_PROBES )\n\tuniform vec3 lightProbe[ 9 ];\n#endif\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif ( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif",lights_toon_fragment:"ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;",lights_toon_pars_fragment:"varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon",lights_phong_fragment:"BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;",lights_phong_pars_fragment:"varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong",lights_physical_fragment:"PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef USE_SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULAR_COLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;\n\t\t#endif\n\t\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_DISPERSION\n\tmaterial.dispersion = dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\t#ifdef USE_ANISOTROPYMAP\n\t\tmat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );\n\t\tvec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;\n\t\tvec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;\n\t#else\n\t\tvec2 anisotropyV = anisotropyVector;\n\t#endif\n\tmaterial.anisotropy = length( anisotropyV );\n\tif( material.anisotropy == 0.0 ) {\n\t\tanisotropyV = vec2( 1.0, 0.0 );\n\t} else {\n\t\tanisotropyV /= material.anisotropy;\n\t\tmaterial.anisotropy = saturate( material.anisotropy );\n\t}\n\tmaterial.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );\n\tmaterial.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;\n\tmaterial.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;\n#endif",lights_physical_pars_fragment:"struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\tfloat dispersion;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat anisotropy;\n\t\tfloat alphaT;\n\t\tvec3 anisotropyT;\n\t\tvec3 anisotropyB;\n\t#endif\n};\nvec3 clearcoatSpecularDirect = vec3( 0.0 );\nvec3 clearcoatSpecularIndirect = vec3( 0.0 );\nvec3 sheenSpecularDirect = vec3( 0.0 );\nvec3 sheenSpecularIndirect = vec3(0.0 );\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\n#ifdef USE_ANISOTROPY\n\tfloat V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {\n\t\tfloat gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );\n\t\tfloat gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );\n\t\tfloat v = 0.5 / ( gv + gl );\n\t\treturn saturate(v);\n\t}\n\tfloat D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {\n\t\tfloat a2 = alphaT * alphaB;\n\t\thighp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );\n\t\thighp float v2 = dot( v, v );\n\t\tfloat w2 = a2 / v2;\n\t\treturn RECIPROCAL_PI * a2 * pow2 ( w2 );\n\t}\n#endif\n#ifdef USE_CLEARCOAT\n\tvec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {\n\t\tvec3 f0 = material.clearcoatF0;\n\t\tfloat f90 = material.clearcoatF90;\n\t\tfloat roughness = material.clearcoatRoughness;\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 f0 = material.specularColor;\n\tfloat f90 = material.specularF90;\n\tfloat roughness = material.roughness;\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t#ifdef USE_IRIDESCENCE\n\t\tF = mix( F, material.iridescenceFresnel, material.iridescence );\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat dotTL = dot( material.anisotropyT, lightDir );\n\t\tfloat dotTV = dot( material.anisotropyT, viewDir );\n\t\tfloat dotTH = dot( material.anisotropyT, halfDir );\n\t\tfloat dotBL = dot( material.anisotropyB, lightDir );\n\t\tfloat dotBV = dot( material.anisotropyB, viewDir );\n\t\tfloat dotBH = dot( material.anisotropyB, halfDir );\n\t\tfloat V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );\n\t\tfloat D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );\n\t#else\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t#endif\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometryNormal;\n\t\tvec3 viewDir = geometryViewDir;\n\t\tvec3 position = geometryPosition;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\t#endif\n\tvec3 totalScattering = singleScattering + multiScattering;\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}",lights_fragment_begin:"\nvec3 geometryPosition = - vViewPosition;\nvec3 geometryNormal = normal;\nvec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\nvec3 geometryClearcoatNormal = vec3( 0.0 );\n#ifdef USE_CLEARCOAT\n\tgeometryClearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometryViewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometryPosition, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometryPosition, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#if defined( USE_LIGHT_PROBES )\n\t\tirradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif",lights_fragment_maps:"#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometryNormal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\t#ifdef USE_ANISOTROPY\n\t\tradiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );\n\t#else\n\t\tradiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif",lights_fragment_end:"#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif",logdepthbuf_fragment:"#if defined( USE_LOGDEPTHBUF )\n\tgl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#if defined( USE_LOGDEPTHBUF )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_pars_vertex:"#ifdef USE_LOGDEPTHBUF\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGDEPTHBUF\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif",map_fragment:"#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif",map_pars_fragment:"#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif",map_particle_fragment:"#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t#if defined( USE_POINTS_UV )\n\t\tvec2 uv = vUv;\n\t#else\n\t\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif",map_particle_pars_fragment:"#if defined( USE_POINTS_UV )\n\tvarying vec2 vUv;\n#else\n\t#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t\tuniform mat3 uvTransform;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif",metalnessmap_fragment:"float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif",metalnessmap_pars_fragment:"#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif",morphinstance_vertex:"#ifdef USE_INSTANCING_MORPH\n\tfloat morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\tfloat morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tmorphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;\n\t}\n#endif",morphcolor_vertex:"#if defined( USE_MORPHCOLORS )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif",morphnormal_vertex:"#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif",morphtarget_pars_vertex:"#ifdef USE_MORPHTARGETS\n\t#ifndef USE_INSTANCING_MORPH\n\t\tuniform float morphTargetBaseInfluence;\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t#endif\n\tuniform sampler2DArray morphTargetsTexture;\n\tuniform ivec2 morphTargetsTextureSize;\n\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t}\n#endif",morphtarget_vertex:"#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif",normal_fragment_begin:"float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = dFdx( vViewPosition );\n\tvec3 fdy = dFdy( vViewPosition );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal *= faceDirection;\n\t#endif\n#endif\n#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn = getTangentFrame( - vViewPosition, normal,\n\t\t#if defined( USE_NORMALMAP )\n\t\t\tvNormalMapUv\n\t\t#elif defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tvClearcoatNormalMapUv\n\t\t#else\n\t\t\tvUv\n\t\t#endif\n\t\t);\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn[0] *= faceDirection;\n\t\ttbn[1] *= faceDirection;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn2[0] *= faceDirection;\n\t\ttbn2[1] *= faceDirection;\n\t#endif\n#endif\nvec3 nonPerturbedNormal = normal;",normal_fragment_maps:"#ifdef USE_NORMALMAP_OBJECTSPACE\n\tnormal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( USE_NORMALMAP_TANGENTSPACE )\n\tvec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\tnormal = normalize( tbn * mapN );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif",normal_pars_fragment:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_pars_vertex:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_vertex:"#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif",normalmap_pars_fragment:"#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef USE_NORMALMAP_OBJECTSPACE\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )\n\tmat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( uv.st );\n\t\tvec2 st1 = dFdy( uv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );\n\t\treturn mat3( T * scale, B * scale, N );\n\t}\n#endif",clearcoat_normal_fragment_begin:"#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif",clearcoat_normal_fragment_maps:"#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\tclearcoatNormal = normalize( tbn2 * clearcoatMapN );\n#endif",clearcoat_pars_fragment:"#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif",iridescence_pars_fragment:"#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif",opaque_fragment:"#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );",packing:"vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;\nconst float Inv255 = 1. / 255.;\nconst vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );\nconst vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );\nconst vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );\nconst vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );\nvec4 packDepthToRGBA( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec4( 0., 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec4( 1., 1., 1., 1. );\n\tfloat vuf;\n\tfloat af = modf( v * PackFactors.a, vuf );\n\tfloat bf = modf( vuf * ShiftRight8, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );\n}\nvec3 packDepthToRGB( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec3( 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec3( 1., 1., 1. );\n\tfloat vuf;\n\tfloat bf = modf( v * PackFactors.b, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec3( vuf * Inv255, gf * PackUpscale, bf );\n}\nvec2 packDepthToRG( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec2( 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec2( 1., 1. );\n\tfloat vuf;\n\tfloat gf = modf( v * 256., vuf );\n\treturn vec2( vuf * Inv255, gf );\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors4 );\n}\nfloat unpackRGBToDepth( const in vec3 v ) {\n\treturn dot( v, UnpackFactors3 );\n}\nfloat unpackRGToDepth( const in vec2 v ) {\n\treturn v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;\n}\nvec4 pack2HalfToRGBA( const in vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( const in vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn depth * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * depth - far );\n}",premultiplied_alpha_fragment:"#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif",project_vertex:"vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_BATCHING\n\tmvPosition = batchingMatrix * mvPosition;\n#endif\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;",dithering_fragment:"#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif",dithering_pars_fragment:"#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif",roughnessmap_fragment:"float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif",roughnessmap_pars_fragment:"#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif",shadowmap_pars_fragment:"#if NUM_SPOT_LIGHT_COORDS > 0\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n\tuniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\t\n\t\tfloat lightToPositionLength = length( lightToPosition );\n\t\tif ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\t\tdp += shadowBias;\n\t\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\t\tshadow = (\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t\t) * ( 1.0 / 9.0 );\n\t\t\t#else\n\t\t\t\tshadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n#endif",shadowmap_pars_vertex:"#if NUM_SPOT_LIGHT_COORDS > 0\n\tuniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif",shadowmap_vertex:"#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\tvec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n#endif",shadowmask_pars_fragment:"float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}",skinbase_vertex:"#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif",skinning_pars_vertex:"#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tint size = textureSize( boneTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n#endif",skinning_vertex:"#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif",skinnormal_vertex:"#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif",specularmap_fragment:"float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif",specularmap_pars_fragment:"#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif",tonemapping_fragment:"#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif",tonemapping_pars_fragment:"#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn saturate( toneMappingExposure * color );\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 CineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.6605, - 0.1246, - 0.0182 ),\n\tvec3( - 0.5876, 1.1329, - 0.1006 ),\n\tvec3( - 0.0728, - 0.0083, 1.1187 )\n);\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n\tvec3( 0.6274, 0.0691, 0.0164 ),\n\tvec3( 0.3293, 0.9195, 0.0880 ),\n\tvec3( 0.0433, 0.0113, 0.8956 )\n);\nvec3 agxDefaultContrastApprox( vec3 x ) {\n\tvec3 x2 = x * x;\n\tvec3 x4 = x2 * x2;\n\treturn + 15.5 * x4 * x2\n\t\t- 40.14 * x4 * x\n\t\t+ 31.96 * x4\n\t\t- 6.868 * x2 * x\n\t\t+ 0.4298 * x2\n\t\t+ 0.1191 * x\n\t\t- 0.00232;\n}\nvec3 AgXToneMapping( vec3 color ) {\n\tconst mat3 AgXInsetMatrix = mat3(\n\t\tvec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n\t\tvec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n\t\tvec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n\t);\n\tconst mat3 AgXOutsetMatrix = mat3(\n\t\tvec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n\t\tvec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n\t\tvec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n\t);\n\tconst float AgxMinEv = - 12.47393;\tconst float AgxMaxEv = 4.026069;\n\tcolor *= toneMappingExposure;\n\tcolor = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\tcolor = AgXInsetMatrix * color;\n\tcolor = max( color, 1e-10 );\tcolor = log2( color );\n\tcolor = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\tcolor = clamp( color, 0.0, 1.0 );\n\tcolor = agxDefaultContrastApprox( color );\n\tcolor = AgXOutsetMatrix * color;\n\tcolor = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\tcolor = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\tcolor = clamp( color, 0.0, 1.0 );\n\treturn color;\n}\nvec3 NeutralToneMapping( vec3 color ) {\n\tconst float StartCompression = 0.8 - 0.04;\n\tconst float Desaturation = 0.15;\n\tcolor *= toneMappingExposure;\n\tfloat x = min( color.r, min( color.g, color.b ) );\n\tfloat offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n\tcolor -= offset;\n\tfloat peak = max( color.r, max( color.g, color.b ) );\n\tif ( peak < StartCompression ) return color;\n\tfloat d = 1. - StartCompression;\n\tfloat newPeak = 1. - d * d / ( peak + d - StartCompression );\n\tcolor *= newPeak / peak;\n\tfloat g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n\treturn mix( color, vec3( newPeak ), g );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }",transmission_fragment:"#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmitted = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );\n#endif",transmission_pars_fragment:"#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tfloat w0( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n\t}\n\tfloat w1( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );\n\t}\n\tfloat w2( float a ){\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n\t}\n\tfloat w3( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * a );\n\t}\n\tfloat g0( float a ) {\n\t\treturn w0( a ) + w1( a );\n\t}\n\tfloat g1( float a ) {\n\t\treturn w2( a ) + w3( a );\n\t}\n\tfloat h0( float a ) {\n\t\treturn - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n\t}\n\tfloat h1( float a ) {\n\t\treturn 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n\t}\n\tvec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {\n\t\tuv = uv * texelSize.zw + 0.5;\n\t\tvec2 iuv = floor( uv );\n\t\tvec2 fuv = fract( uv );\n\t\tfloat g0x = g0( fuv.x );\n\t\tfloat g1x = g1( fuv.x );\n\t\tfloat h0x = h0( fuv.x );\n\t\tfloat h1x = h1( fuv.x );\n\t\tfloat h0y = h0( fuv.y );\n\t\tfloat h1y = h1( fuv.y );\n\t\tvec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\treturn g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\n\t\t\tg1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\n\t}\n\tvec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\n\t\tvec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\n\t\tvec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\n\t\tvec2 fLodSizeInv = 1.0 / fLodSize;\n\t\tvec2 cLodSizeInv = 1.0 / cLodSize;\n\t\tvec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );\n\t\tvec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );\n\t\treturn mix( fSample, cSample, fract( lod ) );\n\t}\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\treturn textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );\n\t}\n\tvec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn vec3( 1.0 );\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec4 transmittedLight;\n\t\tvec3 transmittance;\n\t\t#ifdef USE_DISPERSION\n\t\t\tfloat halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;\n\t\t\tvec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );\n\t\t\tfor ( int i = 0; i < 3; i ++ ) {\n\t\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );\n\t\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\t\trefractionCoords += 1.0;\n\t\t\t\trefractionCoords /= 2.0;\n\t\t\t\tvec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );\n\t\t\t\ttransmittedLight[ i ] = transmissionSample[ i ];\n\t\t\t\ttransmittedLight.a += transmissionSample.a;\n\t\t\t\ttransmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];\n\t\t\t}\n\t\t\ttransmittedLight.a /= 3.0;\n\t\t#else\n\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\trefractionCoords += 1.0;\n\t\t\trefractionCoords /= 2.0;\n\t\t\ttransmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\t\ttransmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\t#endif\n\t\tvec3 attenuatedColor = transmittance * transmittedLight.rgb;\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\tfloat transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );\n\t}\n#endif",uv_pars_fragment:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif",uv_pars_vertex:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tuniform mat3 mapTransform;\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform mat3 alphaMapTransform;\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tuniform mat3 lightMapTransform;\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tuniform mat3 aoMapTransform;\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tuniform mat3 bumpMapTransform;\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tuniform mat3 normalMapTransform;\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tuniform mat3 displacementMapTransform;\n\tvarying vec2 vDisplacementMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tuniform mat3 emissiveMapTransform;\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tuniform mat3 metalnessMapTransform;\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tuniform mat3 roughnessMapTransform;\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tuniform mat3 anisotropyMapTransform;\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tuniform mat3 clearcoatMapTransform;\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform mat3 clearcoatNormalMapTransform;\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform mat3 clearcoatRoughnessMapTransform;\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tuniform mat3 sheenColorMapTransform;\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tuniform mat3 sheenRoughnessMapTransform;\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tuniform mat3 iridescenceMapTransform;\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform mat3 iridescenceThicknessMapTransform;\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tuniform mat3 specularMapTransform;\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tuniform mat3 specularColorMapTransform;\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tuniform mat3 specularIntensityMapTransform;\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif",uv_vertex:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvUv = vec3( uv, 1 ).xy;\n#endif\n#ifdef USE_MAP\n\tvMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ALPHAMAP\n\tvAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_LIGHTMAP\n\tvLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_AOMAP\n\tvAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_BUMPMAP\n\tvBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_NORMALMAP\n\tvNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tvDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_METALNESSMAP\n\tvMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULARMAP\n\tvSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tvTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_THICKNESSMAP\n\tvThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;\n#endif",worldpos_vertex:"#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_BATCHING\n\t\tworldPosition = batchingMatrix * worldPosition;\n\t#endif\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif",background_vert:"varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}",background_frag:"uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\ttexColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}",backgroundCube_vert:"varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}",backgroundCube_frag:"#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nuniform mat3 backgroundRotation;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}",cube_vert:"varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}",cube_frag:"uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = texColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}",depth_vert:"#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <batching_vertex>\n\t#include <skinbase_vertex>\n\t#include <morphinstance_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}",depth_frag:"#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <clipping_planes_fragment>\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#elif DEPTH_PACKING == 3202\n\t\tgl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );\n\t#elif DEPTH_PACKING == 3203\n\t\tgl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );\n\t#endif\n}",distanceRGBA_vert:"#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <batching_vertex>\n\t#include <skinbase_vertex>\n\t#include <morphinstance_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}",distanceRGBA_frag:"#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <clipping_planes_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}",equirect_vert:"varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}",equirect_frag:"uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}",linedashed_vert:"uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}",linedashed_frag:"uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}",meshbasic_vert:"#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinbase_vertex>\n\t\t#include <skinnormal_vertex>\n\t\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}",meshbasic_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshlambert_vert:"#define LAMBERT\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}",meshlambert_frag:"#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_lambert_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_lambert_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshmatcap_vert:"#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}",meshmatcap_frag:"#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshnormal_vert:"#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}",meshnormal_frag:"#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}",meshphong_vert:"#define PHONG\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}",meshphong_frag:"#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshphysical_vert:"#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}",meshphysical_frag:"#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define USE_SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef USE_SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULAR_COLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_DISPERSION\n\tuniform float dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\tuniform vec2 anisotropyVector;\n\t#ifdef USE_ANISOTROPYMAP\n\t\tuniform sampler2D anisotropyMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <iridescence_fragment>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <iridescence_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;\n\t#endif\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",meshtoon_vert:"#define TOON\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}",meshtoon_frag:"#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}",points_vert:"uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n#ifdef USE_POINTS_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif\nvoid main() {\n\t#ifdef USE_POINTS_UV\n\t\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\t#endif\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}",points_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}",shadow_vert:"#include <common>\n#include <batching_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}",shadow_frag:"uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <logdepthbuf_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\t#include <logdepthbuf_fragment>\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n}",sprite_vert:"uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\tvec4 mvPosition = modelViewMatrix[ 3 ];\n\tvec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}",sprite_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n}"},Sa={common:{diffuse:{value:new Nr(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Bt},alphaMap:{value:null},alphaMapTransform:{value:new Bt},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Bt}},envmap:{envMap:{value:null},envMapRotation:{value:new Bt},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Bt}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Bt}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Bt},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Bt},normalScale:{value:new Dt(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Bt},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Bt}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Bt}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Bt}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Nr(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new Nr(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Bt},alphaTest:{value:0},uvTransform:{value:new Bt}},sprite:{diffuse:{value:new Nr(16777215)},opacity:{value:1},center:{value:new Dt(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Bt},alphaMap:{value:null},alphaMapTransform:{value:new Bt},alphaTest:{value:0}}},Ma={basic:{uniforms:gi([Sa.common,Sa.specularmap,Sa.envmap,Sa.aomap,Sa.lightmap,Sa.fog]),vertexShader:Ta.meshbasic_vert,fragmentShader:Ta.meshbasic_frag},lambert:{uniforms:gi([Sa.common,Sa.specularmap,Sa.envmap,Sa.aomap,Sa.lightmap,Sa.emissivemap,Sa.bumpmap,Sa.normalmap,Sa.displacementmap,Sa.fog,Sa.lights,{emissive:{value:new Nr(0)}}]),vertexShader:Ta.meshlambert_vert,fragmentShader:Ta.meshlambert_frag},phong:{uniforms:gi([Sa.common,Sa.specularmap,Sa.envmap,Sa.aomap,Sa.lightmap,Sa.emissivemap,Sa.bumpmap,Sa.normalmap,Sa.displacementmap,Sa.fog,Sa.lights,{emissive:{value:new Nr(0)},specular:{value:new Nr(1118481)},shininess:{value:30}}]),vertexShader:Ta.meshphong_vert,fragmentShader:Ta.meshphong_frag},standard:{uniforms:gi([Sa.common,Sa.envmap,Sa.aomap,Sa.lightmap,Sa.emissivemap,Sa.bumpmap,Sa.normalmap,Sa.displacementmap,Sa.roughnessmap,Sa.metalnessmap,Sa.fog,Sa.lights,{emissive:{value:new Nr(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Ta.meshphysical_vert,fragmentShader:Ta.meshphysical_frag},toon:{uniforms:gi([Sa.common,Sa.aomap,Sa.lightmap,Sa.emissivemap,Sa.bumpmap,Sa.normalmap,Sa.displacementmap,Sa.gradientmap,Sa.fog,Sa.lights,{emissive:{value:new Nr(0)}}]),vertexShader:Ta.meshtoon_vert,fragmentShader:Ta.meshtoon_frag},matcap:{uniforms:gi([Sa.common,Sa.bumpmap,Sa.normalmap,Sa.displacementmap,Sa.fog,{matcap:{value:null}}]),vertexShader:Ta.meshmatcap_vert,fragmentShader:Ta.meshmatcap_frag},points:{uniforms:gi([Sa.points,Sa.fog]),vertexShader:Ta.points_vert,fragmentShader:Ta.points_frag},dashed:{uniforms:gi([Sa.common,Sa.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Ta.linedashed_vert,fragmentShader:Ta.linedashed_frag},depth:{uniforms:gi([Sa.common,Sa.displacementmap]),vertexShader:Ta.depth_vert,fragmentShader:Ta.depth_frag},normal:{uniforms:gi([Sa.common,Sa.bumpmap,Sa.normalmap,Sa.displacementmap,{opacity:{value:1}}]),vertexShader:Ta.meshnormal_vert,fragmentShader:Ta.meshnormal_frag},sprite:{uniforms:gi([Sa.sprite,Sa.fog]),vertexShader:Ta.sprite_vert,fragmentShader:Ta.sprite_frag},background:{uniforms:{uvTransform:{value:new Bt},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Ta.background_vert,fragmentShader:Ta.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new Bt}},vertexShader:Ta.backgroundCube_vert,fragmentShader:Ta.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Ta.cube_vert,fragmentShader:Ta.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Ta.equirect_vert,fragmentShader:Ta.equirect_frag},distanceRGBA:{uniforms:gi([Sa.common,Sa.displacementmap,{referencePosition:{value:new Ut},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Ta.distanceRGBA_vert,fragmentShader:Ta.distanceRGBA_frag},shadow:{uniforms:gi([Sa.lights,Sa.fog,{color:{value:new Nr(0)},opacity:{value:1}}]),vertexShader:Ta.shadow_vert,fragmentShader:Ta.shadow_frag}};Ma.physical={uniforms:gi([Ma.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Bt},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Bt},clearcoatNormalScale:{value:new Dt(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Bt},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Bt},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Bt},sheen:{value:0},sheenColor:{value:new Nr(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Bt},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Bt},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Bt},transmissionSamplerSize:{value:new Dt},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Bt},attenuationDistance:{value:0},attenuationColor:{value:new Nr(0)},specularColor:{value:new Nr(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Bt},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Bt},anisotropyVector:{value:new Dt},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Bt}}]),vertexShader:Ta.meshphysical_vert,fragmentShader:Ta.meshphysical_frag};const wa={r:0,b:0,g:0},Ea=new $n,Aa=new Bn;function Ra(e,t,n,r,i,s,a){const o=new Nr(0);let l,u,c=!0===s?0:1,h=null,d=0,p=null;function f(e){let r=!0===e.isScene?e.background:null;if(r&&r.isTexture){r=(e.backgroundBlurriness>0?n:t).get(r)}return r}function m(t,n){t.getRGB(wa,_i(e)),r.buffers.color.setClear(wa.r,wa.g,wa.b,n,a)}return{getClearColor:function(){return o},setClearColor:function(e,t=1){o.set(e),c=t,m(o,c)},getClearAlpha:function(){return c},setClearAlpha:function(e){c=e,m(o,c)},render:function(t){let n=!1;const i=f(t);null===i?m(o,c):i&&i.isColor&&(m(i,1),n=!0);const s=e.xr.getEnvironmentBlendMode();"additive"===s?r.buffers.color.setClear(0,0,0,1,a):"alpha-blend"===s&&r.buffers.color.setClear(0,0,0,0,a),(e.autoClear||n)&&(r.buffers.depth.setTest(!0),r.buffers.depth.setMask(!0),r.buffers.color.setMask(!0),e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil))},addToRenderList:function(t,n){const r=f(n);r&&(r.isCubeTexture||r.mapping===X)?(void 0===u&&(u=new di(new fi(1,1,1),new yi({name:"BackgroundCubeMaterial",uniforms:mi(Ma.backgroundCube.uniforms),vertexShader:Ma.backgroundCube.vertexShader,fragmentShader:Ma.backgroundCube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),u.geometry.deleteAttribute("normal"),u.geometry.deleteAttribute("uv"),u.onBeforeRender=function(e,t,n){this.matrixWorld.copyPosition(n.matrixWorld)},Object.defineProperty(u.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),i.update(u)),Ea.copy(n.backgroundRotation),Ea.x*=-1,Ea.y*=-1,Ea.z*=-1,r.isCubeTexture&&!1===r.isRenderTargetTexture&&(Ea.y*=-1,Ea.z*=-1),u.material.uniforms.envMap.value=r,u.material.uniforms.flipEnvMap.value=r.isCubeTexture&&!1===r.isRenderTargetTexture?-1:1,u.material.uniforms.backgroundBlurriness.value=n.backgroundBlurriness,u.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,u.material.uniforms.backgroundRotation.value.setFromMatrix4(Aa.makeRotationFromEuler(Ea)),u.material.toneMapped=$t.getTransfer(r.colorSpace)!==at,h===r&&d===r.version&&p===e.toneMapping||(u.material.needsUpdate=!0,h=r,d=r.version,p=e.toneMapping),u.layers.enableAll(),t.unshift(u,u.geometry,u.material,0,0,null)):r&&r.isTexture&&(void 0===l&&(l=new di(new Ss(2,2),new yi({name:"BackgroundMaterial",uniforms:mi(Ma.background.uniforms),vertexShader:Ma.background.vertexShader,fragmentShader:Ma.background.fragmentShader,side:0,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),i.update(l)),l.material.uniforms.t2D.value=r,l.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,l.material.toneMapped=$t.getTransfer(r.colorSpace)!==at,!0===r.matrixAutoUpdate&&r.updateMatrix(),l.material.uniforms.uvTransform.value.copy(r.matrix),h===r&&d===r.version&&p===e.toneMapping||(l.material.needsUpdate=!0,h=r,d=r.version,p=e.toneMapping),l.layers.enableAll(),t.unshift(l,l.geometry,l.material,0,0,null))},dispose:function(){void 0!==u&&(u.geometry.dispose(),u.material.dispose(),u=void 0),void 0!==l&&(l.geometry.dispose(),l.material.dispose(),l=void 0)}}}function Ca(e,t){const n=e.getParameter(e.MAX_VERTEX_ATTRIBS),r={},i=u(null);let s=i,a=!1;function o(t){return e.bindVertexArray(t)}function l(t){return e.deleteVertexArray(t)}function u(e){const t=[],r=[],i=[];for(let e=0;e<n;e++)t[e]=0,r[e]=0,i[e]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:t,enabledAttributes:r,attributeDivisors:i,object:e,attributes:{},index:null}}function c(){const e=s.newAttributes;for(let t=0,n=e.length;t<n;t++)e[t]=0}function h(e){d(e,0)}function d(t,n){const r=s.newAttributes,i=s.enabledAttributes,a=s.attributeDivisors;r[t]=1,0===i[t]&&(e.enableVertexAttribArray(t),i[t]=1),a[t]!==n&&(e.vertexAttribDivisor(t,n),a[t]=n)}function p(){const t=s.newAttributes,n=s.enabledAttributes;for(let r=0,i=n.length;r<i;r++)n[r]!==t[r]&&(e.disableVertexAttribArray(r),n[r]=0)}function f(t,n,r,i,s,a,o){!0===o?e.vertexAttribIPointer(t,n,r,s,a):e.vertexAttribPointer(t,n,r,i,s,a)}function m(){g(),a=!0,s!==i&&(s=i,o(s.object))}function g(){i.geometry=null,i.program=null,i.wireframe=!1}return{setup:function(n,i,l,m,g){let _=!1;const v=function(t,n,i){const s=!0===i.wireframe;let a=r[t.id];void 0===a&&(a={},r[t.id]=a);let o=a[n.id];void 0===o&&(o={},a[n.id]=o);let l=o[s];void 0===l&&(l=u(e.createVertexArray()),o[s]=l);return l}(m,l,i);s!==v&&(s=v,o(s.object)),_=function(e,t,n,r){const i=s.attributes,a=t.attributes;let o=0;const l=n.getAttributes();for(const t in l){if(l[t].location>=0){const n=i[t];let r=a[t];if(void 0===r&&("instanceMatrix"===t&&e.instanceMatrix&&(r=e.instanceMatrix),"instanceColor"===t&&e.instanceColor&&(r=e.instanceColor)),void 0===n)return!0;if(n.attribute!==r)return!0;if(r&&n.data!==r.data)return!0;o++}}return s.attributesNum!==o||s.index!==r}(n,m,l,g),_&&function(e,t,n,r){const i={},a=t.attributes;let o=0;const l=n.getAttributes();for(const t in l){if(l[t].location>=0){let n=a[t];void 0===n&&("instanceMatrix"===t&&e.instanceMatrix&&(n=e.instanceMatrix),"instanceColor"===t&&e.instanceColor&&(n=e.instanceColor));const r={};r.attribute=n,n&&n.data&&(r.data=n.data),i[t]=r,o++}}s.attributes=i,s.attributesNum=o,s.index=r}(n,m,l,g),null!==g&&t.update(g,e.ELEMENT_ARRAY_BUFFER),(_||a)&&(a=!1,function(n,r,i,s){c();const a=s.attributes,o=i.getAttributes(),l=r.defaultAttributeValues;for(const r in o){const i=o[r];if(i.location>=0){let o=a[r];if(void 0===o&&("instanceMatrix"===r&&n.instanceMatrix&&(o=n.instanceMatrix),"instanceColor"===r&&n.instanceColor&&(o=n.instanceColor)),void 0!==o){const r=o.normalized,a=o.itemSize,l=t.get(o);if(void 0===l)continue;const u=l.buffer,c=l.type,p=l.bytesPerElement,m=c===e.INT||c===e.UNSIGNED_INT||o.gpuType===ae;if(o.isInterleavedBufferAttribute){const t=o.data,l=t.stride,g=o.offset;if(t.isInstancedInterleavedBuffer){for(let e=0;e<i.locationSize;e++)d(i.location+e,t.meshPerAttribute);!0!==n.isInstancedMesh&&void 0===s._maxInstanceCount&&(s._maxInstanceCount=t.meshPerAttribute*t.count)}else for(let e=0;e<i.locationSize;e++)h(i.location+e);e.bindBuffer(e.ARRAY_BUFFER,u);for(let e=0;e<i.locationSize;e++)f(i.location+e,a/i.locationSize,c,r,l*p,(g+a/i.locationSize*e)*p,m)}else{if(o.isInstancedBufferAttribute){for(let e=0;e<i.locationSize;e++)d(i.location+e,o.meshPerAttribute);!0!==n.isInstancedMesh&&void 0===s._maxInstanceCount&&(s._maxInstanceCount=o.meshPerAttribute*o.count)}else for(let e=0;e<i.locationSize;e++)h(i.location+e);e.bindBuffer(e.ARRAY_BUFFER,u);for(let e=0;e<i.locationSize;e++)f(i.location+e,a/i.locationSize,c,r,a*p,a/i.locationSize*e*p,m)}}else if(void 0!==l){const t=l[r];if(void 0!==t)switch(t.length){case 2:e.vertexAttrib2fv(i.location,t);break;case 3:e.vertexAttrib3fv(i.location,t);break;case 4:e.vertexAttrib4fv(i.location,t);break;default:e.vertexAttrib1fv(i.location,t)}}}}p()}(n,i,l,m),null!==g&&e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t.get(g).buffer))},reset:m,resetDefaultState:g,dispose:function(){m();for(const e in r){const t=r[e];for(const e in t){const n=t[e];for(const e in n)l(n[e].object),delete n[e];delete t[e]}delete r[e]}},releaseStatesOfGeometry:function(e){if(void 0===r[e.id])return;const t=r[e.id];for(const e in t){const n=t[e];for(const e in n)l(n[e].object),delete n[e];delete t[e]}delete r[e.id]},releaseStatesOfProgram:function(e){for(const t in r){const n=r[t];if(void 0===n[e.id])continue;const i=n[e.id];for(const e in i)l(i[e].object),delete i[e];delete n[e.id]}},initAttributes:c,enableAttribute:h,disableUnusedAttributes:p}}function Na(e,t,n){let r;function i(t,i,s){0!==s&&(e.drawArraysInstanced(r,t,i,s),n.update(i,r,s))}this.setMode=function(e){r=e},this.render=function(t,i){e.drawArrays(r,t,i),n.update(i,r,1)},this.renderInstances=i,this.renderMultiDraw=function(e,i,s){if(0===s)return;t.get("WEBGL_multi_draw").multiDrawArraysWEBGL(r,e,0,i,0,s);let a=0;for(let e=0;e<s;e++)a+=i[e];n.update(a,r,1)},this.renderMultiDrawInstances=function(e,s,a,o){if(0===a)return;const l=t.get("WEBGL_multi_draw");if(null===l)for(let t=0;t<e.length;t++)i(e[t],s[t],o[t]);else{l.multiDrawArraysInstancedWEBGL(r,e,0,s,0,o,0,a);let t=0;for(let e=0;e<a;e++)t+=s[e]*o[e];n.update(t,r,1)}}}function Pa(e,t,n,r){let i;function s(t){if("highp"===t){if(e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0)return"highp";t="mediump"}return"mediump"===t&&e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let a=void 0!==n.precision?n.precision:"highp";const o=s(a);o!==a&&(console.warn("THREE.WebGLRenderer:",a,"not supported, using",o,"instead."),a=o);const l=!0===n.logarithmicDepthBuffer,u=!0===n.reverseDepthBuffer&&t.has("EXT_clip_control"),c=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),h=e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS);return{isWebGL2:!0,getMaxAnisotropy:function(){if(void 0!==i)return i;if(!0===t.has("EXT_texture_filter_anisotropic")){const n=t.get("EXT_texture_filter_anisotropic");i=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else i=0;return i},getMaxPrecision:s,textureFormatReadable:function(t){return t===ge||r.convert(t)===e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)},textureTypeReadable:function(n){const i=n===ue&&(t.has("EXT_color_buffer_half_float")||t.has("EXT_color_buffer_float"));return!(n!==ne&&r.convert(n)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)&&n!==le&&!i)},precision:a,logarithmicDepthBuffer:l,reverseDepthBuffer:u,maxTextures:c,maxVertexTextures:h,maxTextureSize:e.getParameter(e.MAX_TEXTURE_SIZE),maxCubemapSize:e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),maxAttributes:e.getParameter(e.MAX_VERTEX_ATTRIBS),maxVertexUniforms:e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),maxVaryings:e.getParameter(e.MAX_VARYING_VECTORS),maxFragmentUniforms:e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),vertexTextures:h>0,maxSamples:e.getParameter(e.MAX_SAMPLES)}}function La(e){const t=this;let n=null,r=0,i=!1,s=!1;const a=new Gi,o=new Bt,l={value:null,needsUpdate:!1};function u(e,n,r,i){const s=null!==e?e.length:0;let u=null;if(0!==s){if(u=l.value,!0!==i||null===u){const t=r+4*s,i=n.matrixWorldInverse;o.getNormalMatrix(i),(null===u||u.length<t)&&(u=new Float32Array(t));for(let t=0,n=r;t!==s;++t,n+=4)a.copy(e[t]).applyMatrix4(i,o),a.normal.toArray(u,n),u[n+3]=a.constant}l.value=u,l.needsUpdate=!0}return t.numPlanes=s,t.numIntersection=0,u}this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(e,t){const n=0!==e.length||t||0!==r||i;return i=t,r=e.length,n},this.beginShadows=function(){s=!0,u(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(e,t){n=u(e,t,0)},this.setState=function(a,o,c){const h=a.clippingPlanes,d=a.clipIntersection,p=a.clipShadows,f=e.get(a);if(!i||null===h||0===h.length||s&&!p)s?u(null):function(){l.value!==n&&(l.value=n,l.needsUpdate=r>0);t.numPlanes=r,t.numIntersection=0}();else{const e=s?0:r,t=4*e;let i=f.clippingState||null;l.value=i,i=u(h,o,t,c);for(let e=0;e!==t;++e)i[e]=n[e];f.clippingState=i,this.numIntersection=d?this.numPlanes:0,this.numPlanes+=e}}}function Da(e){let t=new WeakMap;function n(e,t){return t===j?e.mapping=G:t===W&&(e.mapping=H),e}function r(e){const n=e.target;n.removeEventListener("dispose",r);const i=t.get(n);void 0!==i&&(t.delete(n),i.dispose())}return{get:function(i){if(i&&i.isTexture){const s=i.mapping;if(s===j||s===W){if(t.has(i)){return n(t.get(i).texture,i.mapping)}{const s=i.image;if(s&&s.height>0){const a=new Ri(s.height);return a.fromEquirectangularTexture(e,i),t.set(i,a),i.addEventListener("dispose",r),n(a.texture,i.mapping)}return null}}}return i},dispose:function(){t=new WeakMap}}}const Ia=[.125,.215,.35,.446,.526,.582],Ua=20,Oa=new na,Fa=new Nr;let Ba=null,ka=0,za=0,Va=!1;const Ga=(1+Math.sqrt(5))/2,Ha=1/Ga,ja=[new Ut(-Ga,Ha,0),new Ut(Ga,Ha,0),new Ut(-Ha,0,Ga),new Ut(Ha,0,Ga),new Ut(0,Ga,-Ha),new Ut(0,Ga,Ha),new Ut(-1,1,-1),new Ut(1,1,-1),new Ut(-1,1,1),new Ut(1,1,1)],Wa=new Ut;let Xa=class{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,t=0,n=.1,r=100,i={}){const{size:s=256,position:a=Wa}=i;Ba=this._renderer.getRenderTarget(),ka=this._renderer.getActiveCubeFace(),za=this._renderer.getActiveMipmapLevel(),Va=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(s);const o=this._allocateTargets();return o.depthBuffer=!0,this._sceneToCubeUV(e,n,r,o,a),t>0&&this._blur(o,0,0,t),this._applyPMREM(o),this._cleanup(o),o}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=Ka(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=Ya(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),null!==this._cubemapMaterial&&this._cubemapMaterial.dispose(),null!==this._equirectMaterial&&this._equirectMaterial.dispose()}_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._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodPlanes.length;e++)this._lodPlanes[e].dispose()}_cleanup(e){this._renderer.setRenderTarget(Ba,ka,za),this._renderer.xr.enabled=Va,e.scissorTest=!1,$a(e,0,0,e.width,e.height)}_fromTexture(e,t){e.mapping===G||e.mapping===H?this._setSize(0===e.image.length?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),Ba=this._renderer.getRenderTarget(),ka=this._renderer.getActiveCubeFace(),za=this._renderer.getActiveMipmapLevel(),Va=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;const n=t||this._allocateTargets();return this._textureToCubeUV(e,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTargets(){const e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize,n={magFilter:J,minFilter:J,generateMipmaps:!1,type:ue,format:ge,colorSpace:it,depthBuffer:!1},r=qa(e,t,n);if(null===this._pingPongRenderTarget||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){null!==this._pingPongRenderTarget&&this._dispose(),this._pingPongRenderTarget=qa(e,t,n);const{_lodMax:r}=this;({sizeLods:this._sizeLods,lodPlanes:this._lodPlanes,sigmas:this._sigmas}=function(e){const t=[],n=[],r=[];let i=e;const s=e-4+1+Ia.length;for(let a=0;a<s;a++){const s=Math.pow(2,i);n.push(s);let o=1/s;a>e-4?o=Ia[a-e+4-1]:0===a&&(o=0),r.push(o);const l=1/(s-2),u=-l,c=1+l,h=[u,u,c,u,c,c,u,u,c,c,u,c],d=6,p=6,f=3,m=2,g=1,_=new Float32Array(f*p*d),v=new Float32Array(m*p*d),y=new Float32Array(g*p*d);for(let e=0;e<d;e++){const t=e%3*2/3-1,n=e>2?0:-1,r=[t,n,0,t+2/3,n,0,t+2/3,n+1,0,t,n,0,t+2/3,n+1,0,t,n+1,0];_.set(r,f*p*e),v.set(h,m*p*e);const i=[e,e,e,e,e,e];y.set(i,g*p*e)}const x=new ei;x.setAttribute("position",new Gr(_,f)),x.setAttribute("uv",new Gr(v,m)),x.setAttribute("faceIndex",new Gr(y,g)),t.push(x),i>4&&i--}return{lodPlanes:t,sizeLods:n,sigmas:r}}(r)),this._blurMaterial=function(e,t,n){const r=new Float32Array(Ua),i=new Ut(0,1,0),s=new yi({name:"SphericalGaussianBlur",defines:{n:Ua,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:r},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:i}},vertexShader:Qa(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform int samples;\n\t\t\tuniform float weights[ n ];\n\t\t\tuniform bool latitudinal;\n\t\t\tuniform float dTheta;\n\t\t\tuniform float mipInt;\n\t\t\tuniform vec3 poleAxis;\n\n\t\t\t#define ENVMAP_TYPE_CUBE_UV\n\t\t\t#include <cube_uv_reflection_fragment>\n\n\t\t\tvec3 getSample( float theta, vec3 axis ) {\n\n\t\t\t\tfloat cosTheta = cos( theta );\n\t\t\t\t// Rodrigues' axis-angle rotation\n\t\t\t\tvec3 sampleDirection = vOutputDirection * cosTheta\n\t\t\t\t\t+ cross( axis, vOutputDirection ) * sin( theta )\n\t\t\t\t\t+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );\n\n\t\t\t\treturn bilinearCubeUV( envMap, sampleDirection, mipInt );\n\n\t\t\t}\n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );\n\n\t\t\t\tif ( all( equal( axis, vec3( 0.0 ) ) ) ) {\n\n\t\t\t\t\taxis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );\n\n\t\t\t\t}\n\n\t\t\t\taxis = normalize( axis );\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t\t\t\tgl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );\n\n\t\t\t\tfor ( int i = 1; i < n; i++ ) {\n\n\t\t\t\t\tif ( i >= samples ) {\n\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tfloat theta = dTheta * float( i );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( theta, axis );\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1});return s}(r,e,t)}return r}_compileMaterial(e){const t=new di(this._lodPlanes[0],e);this._renderer.compile(t,Oa)}_sceneToCubeUV(e,t,n,r,i){const s=new Mi(90,1,t,n),a=[1,-1,1,1,1,1],o=[1,1,1,-1,-1,-1],l=this._renderer,u=l.autoClear,c=l.toneMapping;l.getClearColor(Fa),l.toneMapping=0,l.autoClear=!1;const h=new Ir({name:"PMREM.Background",side:1,depthWrite:!1,depthTest:!1}),d=new di(new fi,h);let p=!1;const f=e.background;f?f.isColor&&(h.color.copy(f),e.background=null,p=!0):(h.color.copy(Fa),p=!0);for(let t=0;t<6;t++){const n=t%3;0===n?(s.up.set(0,a[t],0),s.position.set(i.x,i.y,i.z),s.lookAt(i.x+o[t],i.y,i.z)):1===n?(s.up.set(0,0,a[t]),s.position.set(i.x,i.y,i.z),s.lookAt(i.x,i.y+o[t],i.z)):(s.up.set(0,a[t],0),s.position.set(i.x,i.y,i.z),s.lookAt(i.x,i.y,i.z+o[t]));const u=this._cubeSize;$a(r,n*u,t>2?u:0,u,u),l.setRenderTarget(r),p&&l.render(d,s),l.render(e,s)}d.geometry.dispose(),d.material.dispose(),l.toneMapping=c,l.autoClear=u,e.background=f}_textureToCubeUV(e,t){const n=this._renderer,r=e.mapping===G||e.mapping===H;r?(null===this._cubemapMaterial&&(this._cubemapMaterial=Ka()),this._cubemapMaterial.uniforms.flipEnvMap.value=!1===e.isRenderTargetTexture?-1:1):null===this._equirectMaterial&&(this._equirectMaterial=Ya());const i=r?this._cubemapMaterial:this._equirectMaterial,s=new di(this._lodPlanes[0],i);i.uniforms.envMap.value=e;const a=this._cubeSize;$a(t,0,0,3*a,2*a),n.setRenderTarget(t),n.render(s,Oa)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;const r=this._lodPlanes.length;for(let t=1;t<r;t++){const n=Math.sqrt(this._sigmas[t]*this._sigmas[t]-this._sigmas[t-1]*this._sigmas[t-1]),i=ja[(r-t-1)%ja.length];this._blur(e,t-1,t,n,i)}t.autoClear=n}_blur(e,t,n,r,i){const s=this._pingPongRenderTarget;this._halfBlur(e,s,t,n,r,"latitudinal",i),this._halfBlur(s,e,n,n,r,"longitudinal",i)}_halfBlur(e,t,n,r,i,s,a){const o=this._renderer,l=this._blurMaterial;"latitudinal"!==s&&"longitudinal"!==s&&console.error("blur direction must be either latitudinal or longitudinal!");const u=new di(this._lodPlanes[r],l),c=l.uniforms,h=this._sizeLods[n]-1,d=isFinite(i)?Math.PI/(2*h):2*Math.PI/39,p=i/d,f=isFinite(i)?1+Math.floor(3*p):Ua;f>Ua&&console.warn(`sigmaRadians, ${i}, is too large and will clip, as it requested ${f} samples when the maximum is set to 20`);const m=[];let g=0;for(let e=0;e<Ua;++e){const t=e/p,n=Math.exp(-t*t/2);m.push(n),0===e?g+=n:e<f&&(g+=2*n)}for(let e=0;e<m.length;e++)m[e]=m[e]/g;c.envMap.value=e.texture,c.samples.value=f,c.weights.value=m,c.latitudinal.value="latitudinal"===s,a&&(c.poleAxis.value=a);const{_lodMax:_}=this;c.dTheta.value=d,c.mipInt.value=_-n;const v=this._sizeLods[r];$a(t,3*v*(r>_-4?r-_+4:0),4*(this._cubeSize-v),3*v,2*v),o.setRenderTarget(t),o.render(u,Oa)}};function qa(e,t,n){const r=new ln(e,t,n);return r.texture.mapping=X,r.texture.name="PMREM.cubeUv",r.scissorTest=!0,r}function $a(e,t,n,r,i){e.viewport.set(t,n,r,i),e.scissor.set(t,n,r,i)}function Ya(){return new yi({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:Qa(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\n\t\t\t#include <common>\n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 outputDirection = normalize( vOutputDirection );\n\t\t\t\tvec2 uv = equirectUv( outputDirection );\n\n\t\t\t\tgl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1})}function Ka(){return new yi({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Qa(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tuniform float flipEnvMap;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform samplerCube envMap;\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1})}function Qa(){return"\n\n\t\tprecision mediump float;\n\t\tprecision mediump int;\n\n\t\tattribute float faceIndex;\n\n\t\tvarying vec3 vOutputDirection;\n\n\t\t// RH coordinate system; PMREM face-indexing convention\n\t\tvec3 getDirection( vec2 uv, float face ) {\n\n\t\t\tuv = 2.0 * uv - 1.0;\n\n\t\t\tvec3 direction = vec3( uv, 1.0 );\n\n\t\t\tif ( face == 0.0 ) {\n\n\t\t\t\tdirection = direction.zyx; // ( 1, v, u ) pos x\n\n\t\t\t} else if ( face == 1.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xz *= -1.0; // ( -u, 1, -v ) pos y\n\n\t\t\t} else if ( face == 2.0 ) {\n\n\t\t\t\tdirection.x *= -1.0; // ( -u, v, 1 ) pos z\n\n\t\t\t} else if ( face == 3.0 ) {\n\n\t\t\t\tdirection = direction.zyx;\n\t\t\t\tdirection.xz *= -1.0; // ( -1, v, -u ) neg x\n\n\t\t\t} else if ( face == 4.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xy *= -1.0; // ( -u, -1, v ) neg y\n\n\t\t\t} else if ( face == 5.0 ) {\n\n\t\t\t\tdirection.z *= -1.0; // ( u, v, -1 ) neg z\n\n\t\t\t}\n\n\t\t\treturn direction;\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\tvOutputDirection = getDirection( uv, faceIndex );\n\t\t\tgl_Position = vec4( position, 1.0 );\n\n\t\t}\n\t"}function Za(e){let t=new WeakMap,n=null;function r(e){const n=e.target;n.removeEventListener("dispose",r);const i=t.get(n);void 0!==i&&(t.delete(n),i.dispose())}return{get:function(i){if(i&&i.isTexture){const s=i.mapping,a=s===j||s===W,o=s===G||s===H;if(a||o){let s=t.get(i);const l=void 0!==s?s.texture.pmremVersion:0;if(i.isRenderTargetTexture&&i.pmremVersion!==l)return null===n&&(n=new Xa(e)),s=a?n.fromEquirectangular(i,s):n.fromCubemap(i,s),s.texture.pmremVersion=i.pmremVersion,t.set(i,s),s.texture;if(void 0!==s)return s.texture;{const l=i.image;return a&&l&&l.height>0||o&&l&&function(e){let t=0;const n=6;for(let r=0;r<n;r++)void 0!==e[r]&&t++;return t===n}(l)?(null===n&&(n=new Xa(e)),s=a?n.fromEquirectangular(i):n.fromCubemap(i),s.texture.pmremVersion=i.pmremVersion,t.set(i,s),i.addEventListener("dispose",r),s.texture):null}}}return i},dispose:function(){t=new WeakMap,null!==n&&(n.dispose(),n=null)}}}function Ja(e){const t={};function n(n){if(void 0!==t[n])return t[n];let r;switch(n){case"WEBGL_depth_texture":r=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":r=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":r=e.getExtension("WEBGL_compressed_texture_s3tc")||e.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":r=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:r=e.getExtension(n)}return t[n]=r,r}return{has:function(e){return null!==n(e)},init:function(){n("EXT_color_buffer_float"),n("WEBGL_clip_cull_distance"),n("OES_texture_float_linear"),n("EXT_color_buffer_half_float"),n("WEBGL_multisampled_render_to_texture"),n("WEBGL_render_shared_exponent")},get:function(e){const t=n(e);return null===t&&jt("THREE.WebGLRenderer: "+e+" extension not supported."),t}}}function eo(e,t,n,r){const i={},s=new WeakMap;function a(e){const o=e.target;null!==o.index&&t.remove(o.index);for(const e in o.attributes)t.remove(o.attributes[e]);o.removeEventListener("dispose",a),delete i[o.id];const l=s.get(o);l&&(t.remove(l),s.delete(o)),r.releaseStatesOfGeometry(o),!0===o.isInstancedBufferGeometry&&delete o._maxInstanceCount,n.memory.geometries--}function o(e){const n=[],r=e.index,i=e.attributes.position;let a=0;if(null!==r){const e=r.array;a=r.version;for(let t=0,r=e.length;t<r;t+=3){const r=e[t+0],i=e[t+1],s=e[t+2];n.push(r,i,i,s,s,r)}}else{if(void 0===i)return;{const e=i.array;a=i.version;for(let t=0,r=e.length/3-1;t<r;t+=3){const e=t+0,r=t+1,i=t+2;n.push(e,r,r,i,i,e)}}}const o=new(zt(n)?jr:Hr)(n,1);o.version=a;const l=s.get(e);l&&t.remove(l),s.set(e,o)}return{get:function(e,t){return!0===i[t.id]||(t.addEventListener("dispose",a),i[t.id]=!0,n.memory.geometries++),t},update:function(n){const r=n.attributes;for(const n in r)t.update(r[n],e.ARRAY_BUFFER)},getWireframeAttribute:function(e){const t=s.get(e);if(t){const n=e.index;null!==n&&t.version<n.version&&o(e)}else o(e);return s.get(e)}}}function to(e,t,n){let r,i,s;function a(t,a,o){0!==o&&(e.drawElementsInstanced(r,a,i,t*s,o),n.update(a,r,o))}this.setMode=function(e){r=e},this.setIndex=function(e){i=e.type,s=e.bytesPerElement},this.render=function(t,a){e.drawElements(r,a,i,t*s),n.update(a,r,1)},this.renderInstances=a,this.renderMultiDraw=function(e,s,a){if(0===a)return;t.get("WEBGL_multi_draw").multiDrawElementsWEBGL(r,s,0,i,e,0,a);let o=0;for(let e=0;e<a;e++)o+=s[e];n.update(o,r,1)},this.renderMultiDrawInstances=function(e,o,l,u){if(0===l)return;const c=t.get("WEBGL_multi_draw");if(null===c)for(let t=0;t<e.length;t++)a(e[t]/s,o[t],u[t]);else{c.multiDrawElementsInstancedWEBGL(r,o,0,i,e,0,u,0,l);let t=0;for(let e=0;e<l;e++)t+=o[e]*u[e];n.update(t,r,1)}}}function no(e){const t={frame:0,calls:0,triangles:0,points:0,lines:0};return{memory:{geometries:0,textures:0},render:t,programs:null,autoReset:!0,reset:function(){t.calls=0,t.triangles=0,t.points=0,t.lines=0},update:function(n,r,i){switch(t.calls++,r){case e.TRIANGLES:t.triangles+=i*(n/3);break;case e.LINES:t.lines+=i*(n/2);break;case e.LINE_STRIP:t.lines+=i*(n-1);break;case e.LINE_LOOP:t.lines+=i*n;break;case e.POINTS:t.points+=i*n;break;default:console.error("THREE.WebGLInfo: Unknown draw mode:",r)}}}}function ro(e,t,n){const r=new WeakMap,i=new an;return{update:function(s,a,o){const l=s.morphTargetInfluences,u=a.morphAttributes.position||a.morphAttributes.normal||a.morphAttributes.color,c=void 0!==u?u.length:0;let h=r.get(a);if(void 0===h||h.count!==c){void 0!==h&&h.texture.dispose();const d=void 0!==a.morphAttributes.position,p=void 0!==a.morphAttributes.normal,f=void 0!==a.morphAttributes.color,m=a.morphAttributes.position||[],g=a.morphAttributes.normal||[],_=a.morphAttributes.color||[];let v=0;!0===d&&(v=1),!0===p&&(v=2),!0===f&&(v=3);let y=a.attributes.position.count*v,x=1;y>t.maxTextureSize&&(x=Math.ceil(y/t.maxTextureSize),y=t.maxTextureSize);const b=new Float32Array(y*x*4*c),T=new un(b,y,x,c);T.type=le,T.needsUpdate=!0;const S=4*v;for(let w=0;w<c;w++){const E=m[w],A=g[w],R=_[w],C=y*x*4*w;for(let N=0;N<E.count;N++){const P=N*S;!0===d&&(i.fromBufferAttribute(E,N),b[C+P+0]=i.x,b[C+P+1]=i.y,b[C+P+2]=i.z,b[C+P+3]=0),!0===p&&(i.fromBufferAttribute(A,N),b[C+P+4]=i.x,b[C+P+5]=i.y,b[C+P+6]=i.z,b[C+P+7]=0),!0===f&&(i.fromBufferAttribute(R,N),b[C+P+8]=i.x,b[C+P+9]=i.y,b[C+P+10]=i.z,b[C+P+11]=4===R.itemSize?i.w:1)}}function M(){T.dispose(),r.delete(a),a.removeEventListener("dispose",M)}h={count:c,texture:T,size:new Dt(y,x)},r.set(a,h),a.addEventListener("dispose",M)}if(!0===s.isInstancedMesh&&null!==s.morphTexture)o.getUniforms().setValue(e,"morphTexture",s.morphTexture,n);else{let L=0;for(let I=0;I<l.length;I++)L+=l[I];const D=a.morphTargetsRelative?1:1-L;o.getUniforms().setValue(e,"morphTargetBaseInfluence",D),o.getUniforms().setValue(e,"morphTargetInfluences",l)}o.getUniforms().setValue(e,"morphTargetsTexture",h.texture,n),o.getUniforms().setValue(e,"morphTargetsTextureSize",h.size)}}}function io(e,t,n,r){let i=new WeakMap;function s(e){const t=e.target;t.removeEventListener("dispose",s),n.remove(t.instanceMatrix),null!==t.instanceColor&&n.remove(t.instanceColor)}return{update:function(a){const o=r.render.frame,l=a.geometry,u=t.get(a,l);if(i.get(u)!==o&&(t.update(u),i.set(u,o)),a.isInstancedMesh&&(!1===a.hasEventListener("dispose",s)&&a.addEventListener("dispose",s),i.get(a)!==o&&(n.update(a.instanceMatrix,e.ARRAY_BUFFER),null!==a.instanceColor&&n.update(a.instanceColor,e.ARRAY_BUFFER),i.set(a,o))),a.isSkinnedMesh){const e=a.skeleton;i.get(e)!==o&&(e.update(),i.set(e,o))}return u},dispose:function(){i=new WeakMap}}}const so=new sn,ao=new os(1,1),oo=new un,lo=new cn,uo=new Ai,co=[],ho=[],po=new Float32Array(16),fo=new Float32Array(9),mo=new Float32Array(4);function go(e,t,n){const r=e[0];if(r<=0||r>0)return e;const i=t*n;let s=co[i];if(void 0===s&&(s=new Float32Array(i),co[i]=s),0!==t){r.toArray(s,0);for(let r=1,i=0;r!==t;++r)i+=n,e[r].toArray(s,i)}return s}function _o(e,t){if(e.length!==t.length)return!1;for(let n=0,r=e.length;n<r;n++)if(e[n]!==t[n])return!1;return!0}function vo(e,t){for(let n=0,r=t.length;n<r;n++)e[n]=t[n]}function yo(e,t){let n=ho[t];void 0===n&&(n=new Int32Array(t),ho[t]=n);for(let r=0;r!==t;++r)n[r]=e.allocateTextureUnit();return n}function xo(e,t){const n=this.cache;n[0]!==t&&(e.uniform1f(this.addr,t),n[0]=t)}function bo(e,t){const n=this.cache;if(void 0!==t.x)n[0]===t.x&&n[1]===t.y||(e.uniform2f(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y);else{if(_o(n,t))return;e.uniform2fv(this.addr,t),vo(n,t)}}function To(e,t){const n=this.cache;if(void 0!==t.x)n[0]===t.x&&n[1]===t.y&&n[2]===t.z||(e.uniform3f(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z);else if(void 0!==t.r)n[0]===t.r&&n[1]===t.g&&n[2]===t.b||(e.uniform3f(this.addr,t.r,t.g,t.b),n[0]=t.r,n[1]=t.g,n[2]=t.b);else{if(_o(n,t))return;e.uniform3fv(this.addr,t),vo(n,t)}}function So(e,t){const n=this.cache;if(void 0!==t.x)n[0]===t.x&&n[1]===t.y&&n[2]===t.z&&n[3]===t.w||(e.uniform4f(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w);else{if(_o(n,t))return;e.uniform4fv(this.addr,t),vo(n,t)}}function Mo(e,t){const n=this.cache,r=t.elements;if(void 0===r){if(_o(n,t))return;e.uniformMatrix2fv(this.addr,!1,t),vo(n,t)}else{if(_o(n,r))return;mo.set(r),e.uniformMatrix2fv(this.addr,!1,mo),vo(n,r)}}function wo(e,t){const n=this.cache,r=t.elements;if(void 0===r){if(_o(n,t))return;e.uniformMatrix3fv(this.addr,!1,t),vo(n,t)}else{if(_o(n,r))return;fo.set(r),e.uniformMatrix3fv(this.addr,!1,fo),vo(n,r)}}function Eo(e,t){const n=this.cache,r=t.elements;if(void 0===r){if(_o(n,t))return;e.uniformMatrix4fv(this.addr,!1,t),vo(n,t)}else{if(_o(n,r))return;po.set(r),e.uniformMatrix4fv(this.addr,!1,po),vo(n,r)}}function Ao(e,t){const n=this.cache;n[0]!==t&&(e.uniform1i(this.addr,t),n[0]=t)}function Ro(e,t){const n=this.cache;if(void 0!==t.x)n[0]===t.x&&n[1]===t.y||(e.uniform2i(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y);else{if(_o(n,t))return;e.uniform2iv(this.addr,t),vo(n,t)}}function Co(e,t){const n=this.cache;if(void 0!==t.x)n[0]===t.x&&n[1]===t.y&&n[2]===t.z||(e.uniform3i(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z);else{if(_o(n,t))return;e.uniform3iv(this.addr,t),vo(n,t)}}function No(e,t){const n=this.cache;if(void 0!==t.x)n[0]===t.x&&n[1]===t.y&&n[2]===t.z&&n[3]===t.w||(e.uniform4i(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w);else{if(_o(n,t))return;e.uniform4iv(this.addr,t),vo(n,t)}}function Po(e,t){const n=this.cache;n[0]!==t&&(e.uniform1ui(this.addr,t),n[0]=t)}function Lo(e,t){const n=this.cache;if(void 0!==t.x)n[0]===t.x&&n[1]===t.y||(e.uniform2ui(this.addr,t.x,t.y),n[0]=t.x,n[1]=t.y);else{if(_o(n,t))return;e.uniform2uiv(this.addr,t),vo(n,t)}}function Do(e,t){const n=this.cache;if(void 0!==t.x)n[0]===t.x&&n[1]===t.y&&n[2]===t.z||(e.uniform3ui(this.addr,t.x,t.y,t.z),n[0]=t.x,n[1]=t.y,n[2]=t.z);else{if(_o(n,t))return;e.uniform3uiv(this.addr,t),vo(n,t)}}function Io(e,t){const n=this.cache;if(void 0!==t.x)n[0]===t.x&&n[1]===t.y&&n[2]===t.z&&n[3]===t.w||(e.uniform4ui(this.addr,t.x,t.y,t.z,t.w),n[0]=t.x,n[1]=t.y,n[2]=t.z,n[3]=t.w);else{if(_o(n,t))return;e.uniform4uiv(this.addr,t),vo(n,t)}}function Uo(e,t,n){const r=this.cache,i=n.allocateTextureUnit();let s;r[0]!==i&&(e.uniform1i(this.addr,i),r[0]=i),this.type===e.SAMPLER_2D_SHADOW?(ao.compareFunction=ht,s=ao):s=so,n.setTexture2D(t||s,i)}function Oo(e,t,n){const r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(e.uniform1i(this.addr,i),r[0]=i),n.setTexture3D(t||lo,i)}function Fo(e,t,n){const r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(e.uniform1i(this.addr,i),r[0]=i),n.setTextureCube(t||uo,i)}function Bo(e,t,n){const r=this.cache,i=n.allocateTextureUnit();r[0]!==i&&(e.uniform1i(this.addr,i),r[0]=i),n.setTexture2DArray(t||oo,i)}function ko(e,t){e.uniform1fv(this.addr,t)}function zo(e,t){const n=go(t,this.size,2);e.uniform2fv(this.addr,n)}function Vo(e,t){const n=go(t,this.size,3);e.uniform3fv(this.addr,n)}function Go(e,t){const n=go(t,this.size,4);e.uniform4fv(this.addr,n)}function Ho(e,t){const n=go(t,this.size,4);e.uniformMatrix2fv(this.addr,!1,n)}function jo(e,t){const n=go(t,this.size,9);e.uniformMatrix3fv(this.addr,!1,n)}function Wo(e,t){const n=go(t,this.size,16);e.uniformMatrix4fv(this.addr,!1,n)}function Xo(e,t){e.uniform1iv(this.addr,t)}function qo(e,t){e.uniform2iv(this.addr,t)}function $o(e,t){e.uniform3iv(this.addr,t)}function Yo(e,t){e.uniform4iv(this.addr,t)}function Ko(e,t){e.uniform1uiv(this.addr,t)}function Qo(e,t){e.uniform2uiv(this.addr,t)}function Zo(e,t){e.uniform3uiv(this.addr,t)}function Jo(e,t){e.uniform4uiv(this.addr,t)}function el(e,t,n){const r=this.cache,i=t.length,s=yo(n,i);_o(r,s)||(e.uniform1iv(this.addr,s),vo(r,s));for(let e=0;e!==i;++e)n.setTexture2D(t[e]||so,s[e])}function tl(e,t,n){const r=this.cache,i=t.length,s=yo(n,i);_o(r,s)||(e.uniform1iv(this.addr,s),vo(r,s));for(let e=0;e!==i;++e)n.setTexture3D(t[e]||lo,s[e])}function nl(e,t,n){const r=this.cache,i=t.length,s=yo(n,i);_o(r,s)||(e.uniform1iv(this.addr,s),vo(r,s));for(let e=0;e!==i;++e)n.setTextureCube(t[e]||uo,s[e])}function rl(e,t,n){const r=this.cache,i=t.length,s=yo(n,i);_o(r,s)||(e.uniform1iv(this.addr,s),vo(r,s));for(let e=0;e!==i;++e)n.setTexture2DArray(t[e]||oo,s[e])}class il{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.setValue=function(e){switch(e){case 5126:return xo;case 35664:return bo;case 35665:return To;case 35666:return So;case 35674:return Mo;case 35675:return wo;case 35676:return Eo;case 5124:case 35670:return Ao;case 35667:case 35671:return Ro;case 35668:case 35672:return Co;case 35669:case 35673:return No;case 5125:return Po;case 36294:return Lo;case 36295:return Do;case 36296:return Io;case 35678:case 36198:case 36298:case 36306:case 35682:return Uo;case 35679:case 36299:case 36307:return Oo;case 35680:case 36300:case 36308:case 36293:return Fo;case 36289:case 36303:case 36311:case 36292:return Bo}}(t.type)}}class sl{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=function(e){switch(e){case 5126:return ko;case 35664:return zo;case 35665:return Vo;case 35666:return Go;case 35674:return Ho;case 35675:return jo;case 35676:return Wo;case 5124:case 35670:return Xo;case 35667:case 35671:return qo;case 35668:case 35672:return $o;case 35669:case 35673:return Yo;case 5125:return Ko;case 36294:return Qo;case 36295:return Zo;case 36296:return Jo;case 35678:case 36198:case 36298:case 36306:case 35682:return el;case 35679:case 36299:case 36307:return tl;case 35680:case 36300:case 36308:case 36293:return nl;case 36289:case 36303:case 36311:case 36292:return rl}}(t.type)}}class al{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,n){const r=this.seq;for(let i=0,s=r.length;i!==s;++i){const s=r[i];s.setValue(e,t[s.id],n)}}}const ol=/(\w+)(\])?(\[|\.)?/g;function ll(e,t){e.seq.push(t),e.map[t.id]=t}function ul(e,t,n){const r=e.name,i=r.length;for(ol.lastIndex=0;;){const s=ol.exec(r),a=ol.lastIndex;let o=s[1];const l="]"===s[2],u=s[3];if(l&&(o|=0),void 0===u||"["===u&&a+2===i){ll(n,void 0===u?new il(o,e,t):new sl(o,e,t));break}{let e=n.map[o];void 0===e&&(e=new al(o),ll(n,e)),n=e}}}class cl{constructor(e,t){this.seq=[],this.map={};const n=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let r=0;r<n;++r){const n=e.getActiveUniform(t,r);ul(n,e.getUniformLocation(t,n.name),this)}}setValue(e,t,n,r){const i=this.map[t];void 0!==i&&i.setValue(e,n,r)}setOptional(e,t,n){const r=t[n];void 0!==r&&this.setValue(e,n,r)}static upload(e,t,n,r){for(let i=0,s=t.length;i!==s;++i){const s=t[i],a=n[s.id];!1!==a.needsUpdate&&s.setValue(e,a.value,r)}}static seqWithValue(e,t){const n=[];for(let r=0,i=e.length;r!==i;++r){const i=e[r];i.id in t&&n.push(i)}return n}}function hl(e,t,n){const r=e.createShader(t);return e.shaderSource(r,n),e.compileShader(r),r}let dl=0;const pl=new Bt;function fl(e,t,n){const r=e.getShaderParameter(t,e.COMPILE_STATUS),i=e.getShaderInfoLog(t).trim();if(r&&""===i)return"";const s=/ERROR: 0:(\d+)/.exec(i);if(s){const r=parseInt(s[1]);return n.toUpperCase()+"\n\n"+i+"\n\n"+function(e,t){const n=e.split("\n"),r=[],i=Math.max(t-6,0),s=Math.min(t+6,n.length);for(let e=i;e<s;e++){const i=e+1;r.push(`${i===t?">":" "} ${i}: ${n[e]}`)}return r.join("\n")}(e.getShaderSource(t),r)}return i}function ml(e,t){const n=function(e){$t._getMatrix(pl,$t.workingColorSpace,e);const t=`mat3( ${pl.elements.map(e=>e.toFixed(4))} )`;switch($t.getTransfer(e)){case st:return[t,"LinearTransferOETF"];case at:return[t,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space: ",e),[t,"LinearTransferOETF"]}}(t);return[`vec4 ${e}( vec4 value ) {`,`\treturn ${n[1]}( vec4( value.rgb * ${n[0]}, value.a ) );`,"}"].join("\n")}function gl(e,t){let n;switch(t){case 1:n="Linear";break;case 2:n="Reinhard";break;case 3:n="Cineon";break;case 4:n="ACESFilmic";break;case 6:n="AgX";break;case 7:n="Neutral";break;case 5:n="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",t),n="Linear"}return"vec3 "+e+"( vec3 color ) { return "+n+"ToneMapping( color ); }"}const _l=new Ut;function vl(){$t.getLuminanceCoefficients(_l);return["float luminance( const in vec3 rgb ) {",`\tconst vec3 weights = vec3( ${_l.x.toFixed(4)}, ${_l.y.toFixed(4)}, ${_l.z.toFixed(4)} );`,"\treturn dot( weights, rgb );","}"].join("\n")}function yl(e){return""!==e}function xl(e,t){const n=t.numSpotLightShadows+t.numSpotLightMaps-t.numSpotLightShadowsWithMaps;return e.replace(/NUM_DIR_LIGHTS/g,t.numDirLights).replace(/NUM_SPOT_LIGHTS/g,t.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,t.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,n).replace(/NUM_RECT_AREA_LIGHTS/g,t.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,t.numPointLights).replace(/NUM_HEMI_LIGHTS/g,t.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,t.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,t.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,t.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,t.numPointLightShadows)}function bl(e,t){return e.replace(/NUM_CLIPPING_PLANES/g,t.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,t.numClippingPlanes-t.numClipIntersection)}const Tl=/^[ \t]*#include +<([\w\d./]+)>/gm;function Sl(e){return e.replace(Tl,wl)}const Ml=new Map;function wl(e,t){let n=Ta[t];if(void 0===n){const e=Ml.get(t);if(void 0===e)throw new Error("Can not resolve #include <"+t+">");n=Ta[e],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',t,e)}return Sl(n)}const El=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function Al(e){return e.replace(El,Rl)}function Rl(e,t,n,r){let i="";for(let e=parseInt(t);e<parseInt(n);e++)i+=r.replace(/\[\s*i\s*\]/g,"[ "+e+" ]").replace(/UNROLLED_LOOP_INDEX/g,e);return i}function Cl(e){let t=`precision ${e.precision} float;\n\tprecision ${e.precision} int;\n\tprecision ${e.precision} sampler2D;\n\tprecision ${e.precision} samplerCube;\n\tprecision ${e.precision} sampler3D;\n\tprecision ${e.precision} sampler2DArray;\n\tprecision ${e.precision} sampler2DShadow;\n\tprecision ${e.precision} samplerCubeShadow;\n\tprecision ${e.precision} sampler2DArrayShadow;\n\tprecision ${e.precision} isampler2D;\n\tprecision ${e.precision} isampler3D;\n\tprecision ${e.precision} isamplerCube;\n\tprecision ${e.precision} isampler2DArray;\n\tprecision ${e.precision} usampler2D;\n\tprecision ${e.precision} usampler3D;\n\tprecision ${e.precision} usamplerCube;\n\tprecision ${e.precision} usampler2DArray;\n\t`;return"highp"===e.precision?t+="\n#define HIGH_PRECISION":"mediump"===e.precision?t+="\n#define MEDIUM_PRECISION":"lowp"===e.precision&&(t+="\n#define LOW_PRECISION"),t}function Nl(e,t,n,r){const i=e.getContext(),s=n.defines;let a=n.vertexShader,o=n.fragmentShader;const l=function(e){let t="SHADOWMAP_TYPE_BASIC";return 1===e.shadowMapType?t="SHADOWMAP_TYPE_PCF":2===e.shadowMapType?t="SHADOWMAP_TYPE_PCF_SOFT":3===e.shadowMapType&&(t="SHADOWMAP_TYPE_VSM"),t}(n),u=function(e){let t="ENVMAP_TYPE_CUBE";if(e.envMap)switch(e.envMapMode){case G:case H:t="ENVMAP_TYPE_CUBE";break;case X:t="ENVMAP_TYPE_CUBE_UV"}return t}(n),c=function(e){let t="ENVMAP_MODE_REFLECTION";e.envMap&&e.envMapMode===H&&(t="ENVMAP_MODE_REFRACTION");return t}(n),h=function(e){let t="ENVMAP_BLENDING_NONE";if(e.envMap)switch(e.combine){case 0:t="ENVMAP_BLENDING_MULTIPLY";break;case 1:t="ENVMAP_BLENDING_MIX";break;case 2:t="ENVMAP_BLENDING_ADD"}return t}(n),d=function(e){const t=e.envMapCubeUVHeight;if(null===t)return null;const n=Math.log2(t)-2,r=1/t;return{texelWidth:1/(3*Math.max(Math.pow(2,n),112)),texelHeight:r,maxMip:n}}(n),p=function(e){return[e.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",e.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(yl).join("\n")}(n),f=function(e){const t=[];for(const n in e){const r=e[n];!1!==r&&t.push("#define "+n+" "+r)}return t.join("\n")}(s),m=i.createProgram();let g,_,v=n.glslVersion?"#version "+n.glslVersion+"\n":"";n.isRawShaderMaterial?(g=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,f].filter(yl).join("\n"),g.length>0&&(g+="\n"),_=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,f].filter(yl).join("\n"),_.length>0&&(_+="\n")):(g=[Cl(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,f,n.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",n.batching?"#define USE_BATCHING":"",n.batchingColor?"#define USE_BATCHING_COLOR":"",n.instancing?"#define USE_INSTANCING":"",n.instancingColor?"#define USE_INSTANCING_COLOR":"",n.instancingMorph?"#define USE_INSTANCING_MORPH":"",n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.map?"#define USE_MAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+c:"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",n.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",n.displacementMap?"#define USE_DISPLACEMENTMAP":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.anisotropy?"#define USE_ANISOTROPY":"",n.anisotropyMap?"#define USE_ANISOTROPYMAP":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.mapUv?"#define MAP_UV "+n.mapUv:"",n.alphaMapUv?"#define ALPHAMAP_UV "+n.alphaMapUv:"",n.lightMapUv?"#define LIGHTMAP_UV "+n.lightMapUv:"",n.aoMapUv?"#define AOMAP_UV "+n.aoMapUv:"",n.emissiveMapUv?"#define EMISSIVEMAP_UV "+n.emissiveMapUv:"",n.bumpMapUv?"#define BUMPMAP_UV "+n.bumpMapUv:"",n.normalMapUv?"#define NORMALMAP_UV "+n.normalMapUv:"",n.displacementMapUv?"#define DISPLACEMENTMAP_UV "+n.displacementMapUv:"",n.metalnessMapUv?"#define METALNESSMAP_UV "+n.metalnessMapUv:"",n.roughnessMapUv?"#define ROUGHNESSMAP_UV "+n.roughnessMapUv:"",n.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+n.anisotropyMapUv:"",n.clearcoatMapUv?"#define CLEARCOATMAP_UV "+n.clearcoatMapUv:"",n.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+n.clearcoatNormalMapUv:"",n.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+n.clearcoatRoughnessMapUv:"",n.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+n.iridescenceMapUv:"",n.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+n.iridescenceThicknessMapUv:"",n.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+n.sheenColorMapUv:"",n.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+n.sheenRoughnessMapUv:"",n.specularMapUv?"#define SPECULARMAP_UV "+n.specularMapUv:"",n.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+n.specularColorMapUv:"",n.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+n.specularIntensityMapUv:"",n.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+n.transmissionMapUv:"",n.thicknessMapUv?"#define THICKNESSMAP_UV "+n.thicknessMapUv:"",n.vertexTangents&&!1===n.flatShading?"#define USE_TANGENT":"",n.vertexColors?"#define USE_COLOR":"",n.vertexAlphas?"#define USE_COLOR_ALPHA":"",n.vertexUv1s?"#define USE_UV1":"",n.vertexUv2s?"#define USE_UV2":"",n.vertexUv3s?"#define USE_UV3":"",n.pointsUvs?"#define USE_POINTS_UV":"",n.flatShading?"#define FLAT_SHADED":"",n.skinning?"#define USE_SKINNING":"",n.morphTargets?"#define USE_MORPHTARGETS":"",n.morphNormals&&!1===n.flatShading?"#define USE_MORPHNORMALS":"",n.morphColors?"#define USE_MORPHCOLORS":"",n.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+n.morphTextureStride:"",n.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+n.morphTargetsCount:"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+l:"",n.sizeAttenuation?"#define USE_SIZEATTENUATION":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",n.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING","\tattribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR","\tattribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH","\tuniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1","\tattribute vec2 uv1;","#endif","#ifdef USE_UV2","\tattribute vec2 uv2;","#endif","#ifdef USE_UV3","\tattribute vec2 uv3;","#endif","#ifdef USE_TANGENT","\tattribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )","\tattribute vec4 color;","#elif defined( USE_COLOR )","\tattribute vec3 color;","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(yl).join("\n"),_=[Cl(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,f,n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",n.map?"#define USE_MAP":"",n.matcap?"#define USE_MATCAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+u:"",n.envMap?"#define "+c:"",n.envMap?"#define "+h:"",d?"#define CUBEUV_TEXEL_WIDTH "+d.texelWidth:"",d?"#define CUBEUV_TEXEL_HEIGHT "+d.texelHeight:"",d?"#define CUBEUV_MAX_MIP "+d.maxMip+".0":"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",n.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.anisotropy?"#define USE_ANISOTROPY":"",n.anisotropyMap?"#define USE_ANISOTROPYMAP":"",n.clearcoat?"#define USE_CLEARCOAT":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.dispersion?"#define USE_DISPERSION":"",n.iridescence?"#define USE_IRIDESCENCE":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaTest?"#define USE_ALPHATEST":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.sheen?"#define USE_SHEEN":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.vertexTangents&&!1===n.flatShading?"#define USE_TANGENT":"",n.vertexColors||n.instancingColor||n.batchingColor?"#define USE_COLOR":"",n.vertexAlphas?"#define USE_COLOR_ALPHA":"",n.vertexUv1s?"#define USE_UV1":"",n.vertexUv2s?"#define USE_UV2":"",n.vertexUv3s?"#define USE_UV3":"",n.pointsUvs?"#define USE_POINTS_UV":"",n.gradientMap?"#define USE_GRADIENTMAP":"",n.flatShading?"#define FLAT_SHADED":"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+l:"",n.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",n.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",n.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",n.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",0!==n.toneMapping?"#define TONE_MAPPING":"",0!==n.toneMapping?Ta.tonemapping_pars_fragment:"",0!==n.toneMapping?gl("toneMapping",n.toneMapping):"",n.dithering?"#define DITHERING":"",n.opaque?"#define OPAQUE":"",Ta.colorspace_pars_fragment,ml("linearToOutputTexel",n.outputColorSpace),vl(),n.useDepthPacking?"#define DEPTH_PACKING "+n.depthPacking:"","\n"].filter(yl).join("\n")),a=Sl(a),a=xl(a,n),a=bl(a,n),o=Sl(o),o=xl(o,n),o=bl(o,n),a=Al(a),o=Al(o),!0!==n.isRawShaderMaterial&&(v="#version 300 es\n",g=[p,"#define attribute in","#define varying out","#define texture2D texture"].join("\n")+"\n"+g,_=["#define varying in",n.glslVersion===vt?"":"layout(location = 0) out highp vec4 pc_fragColor;",n.glslVersion===vt?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join("\n")+"\n"+_);const y=v+g+a,x=v+_+o,b=hl(i,i.VERTEX_SHADER,y),T=hl(i,i.FRAGMENT_SHADER,x);function S(t){if(e.debug.checkShaderErrors){const n=i.getProgramInfoLog(m).trim(),r=i.getShaderInfoLog(b).trim(),s=i.getShaderInfoLog(T).trim();let a=!0,o=!0;if(!1===i.getProgramParameter(m,i.LINK_STATUS))if(a=!1,"function"==typeof e.debug.onShaderError)e.debug.onShaderError(i,m,b,T);else{const e=fl(i,b,"vertex"),r=fl(i,T,"fragment");console.error("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(m,i.VALIDATE_STATUS)+"\n\nMaterial Name: "+t.name+"\nMaterial Type: "+t.type+"\n\nProgram Info Log: "+n+"\n"+e+"\n"+r)}else""!==n?console.warn("THREE.WebGLProgram: Program Info Log:",n):""!==r&&""!==s||(o=!1);o&&(t.diagnostics={runnable:a,programLog:n,vertexShader:{log:r,prefix:g},fragmentShader:{log:s,prefix:_}})}i.deleteShader(b),i.deleteShader(T),M=new cl(i,m),w=function(e,t){const n={},r=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let i=0;i<r;i++){const r=e.getActiveAttrib(t,i),s=r.name;let a=1;r.type===e.FLOAT_MAT2&&(a=2),r.type===e.FLOAT_MAT3&&(a=3),r.type===e.FLOAT_MAT4&&(a=4),n[s]={type:r.type,location:e.getAttribLocation(t,s),locationSize:a}}return n}(i,m)}let M,w;i.attachShader(m,b),i.attachShader(m,T),void 0!==n.index0AttributeName?i.bindAttribLocation(m,0,n.index0AttributeName):!0===n.morphTargets&&i.bindAttribLocation(m,0,"position"),i.linkProgram(m),this.getUniforms=function(){return void 0===M&&S(this),M},this.getAttributes=function(){return void 0===w&&S(this),w};let E=!1===n.rendererExtensionParallelShaderCompile;return this.isReady=function(){return!1===E&&(E=i.getProgramParameter(m,37297)),E},this.destroy=function(){r.releaseStatesOfProgram(this),i.deleteProgram(m),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=dl++,this.cacheKey=t,this.usedTimes=1,this.program=m,this.vertexShader=b,this.fragmentShader=T,this}let Pl=0;class Ll{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,n=e.fragmentShader,r=this._getShaderStage(t),i=this._getShaderStage(n),s=this._getShaderCacheForMaterial(e);return!1===s.has(r)&&(s.add(r),r.usedTimes++),!1===s.has(i)&&(s.add(i),i.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const e of t)e.usedTimes--,0===e.usedTimes&&this.shaderCache.delete(e.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let n=t.get(e);return void 0===n&&(n=new Set,t.set(e,n)),n}_getShaderStage(e){const t=this.shaderCache;let n=t.get(e);return void 0===n&&(n=new Dl(e),t.set(e,n)),n}}class Dl{constructor(e){this.id=Pl++,this.code=e,this.usedTimes=0}}function Il(e,t,n,r,i,s,a){const o=new Yn,l=new Ll,u=new Set,c=[],h=i.logarithmicDepthBuffer,d=i.vertexTextures;let p=i.precision;const f={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function m(e){return u.add(e),0===e?"uv":`uv${e}`}return{getParameters:function(s,o,c,g,_){const v=g.fog,y=_.geometry,x=s.isMeshStandardMaterial?g.environment:null,b=(s.isMeshStandardMaterial?n:t).get(s.envMap||x),T=b&&b.mapping===X?b.image.height:null,S=f[s.type];null!==s.precision&&(p=i.getMaxPrecision(s.precision),p!==s.precision&&console.warn("THREE.WebGLProgram.getParameters:",s.precision,"not supported, using",p,"instead."));const M=y.morphAttributes.position||y.morphAttributes.normal||y.morphAttributes.color,w=void 0!==M?M.length:0;let E,A,R,C,N=0;if(void 0!==y.morphAttributes.position&&(N=1),void 0!==y.morphAttributes.normal&&(N=2),void 0!==y.morphAttributes.color&&(N=3),S){const e=Ma[S];E=e.vertexShader,A=e.fragmentShader}else E=s.vertexShader,A=s.fragmentShader,l.update(s),R=l.getVertexShaderID(s),C=l.getFragmentShaderID(s);const P=e.getRenderTarget(),L=e.state.buffers.depth.getReversed(),D=!0===_.isInstancedMesh,I=!0===_.isBatchedMesh,U=!!s.map,O=!!s.matcap,F=!!b,B=!!s.aoMap,k=!!s.lightMap,z=!!s.bumpMap,V=!!s.normalMap,G=!!s.displacementMap,H=!!s.emissiveMap,j=!!s.metalnessMap,W=!!s.roughnessMap,q=s.anisotropy>0,$=s.clearcoat>0,Y=s.dispersion>0,K=s.iridescence>0,Q=s.sheen>0,Z=s.transmission>0,J=q&&!!s.anisotropyMap,ee=$&&!!s.clearcoatMap,te=$&&!!s.clearcoatNormalMap,ne=$&&!!s.clearcoatRoughnessMap,re=K&&!!s.iridescenceMap,ie=K&&!!s.iridescenceThicknessMap,se=Q&&!!s.sheenColorMap,ae=Q&&!!s.sheenRoughnessMap,oe=!!s.specularMap,le=!!s.specularColorMap,ue=!!s.specularIntensityMap,ce=Z&&!!s.transmissionMap,he=Z&&!!s.thicknessMap,de=!!s.gradientMap,pe=!!s.alphaMap,fe=s.alphaTest>0,me=!!s.alphaHash,ge=!!s.extensions;let _e=0;s.toneMapped&&(null!==P&&!0!==P.isXRRenderTarget||(_e=e.toneMapping));const ve={shaderID:S,shaderType:s.type,shaderName:s.name,vertexShader:E,fragmentShader:A,defines:s.defines,customVertexShaderID:R,customFragmentShaderID:C,isRawShaderMaterial:!0===s.isRawShaderMaterial,glslVersion:s.glslVersion,precision:p,batching:I,batchingColor:I&&null!==_._colorsTexture,instancing:D,instancingColor:D&&null!==_.instanceColor,instancingMorph:D&&null!==_.morphTexture,supportsVertexTextures:d,outputColorSpace:null===P?e.outputColorSpace:!0===P.isXRRenderTarget?P.texture.colorSpace:it,alphaToCoverage:!!s.alphaToCoverage,map:U,matcap:O,envMap:F,envMapMode:F&&b.mapping,envMapCubeUVHeight:T,aoMap:B,lightMap:k,bumpMap:z,normalMap:V,displacementMap:d&&G,emissiveMap:H,normalMapObjectSpace:V&&1===s.normalMapType,normalMapTangentSpace:V&&0===s.normalMapType,metalnessMap:j,roughnessMap:W,anisotropy:q,anisotropyMap:J,clearcoat:$,clearcoatMap:ee,clearcoatNormalMap:te,clearcoatRoughnessMap:ne,dispersion:Y,iridescence:K,iridescenceMap:re,iridescenceThicknessMap:ie,sheen:Q,sheenColorMap:se,sheenRoughnessMap:ae,specularMap:oe,specularColorMap:le,specularIntensityMap:ue,transmission:Z,transmissionMap:ce,thicknessMap:he,gradientMap:de,opaque:!1===s.transparent&&1===s.blending&&!1===s.alphaToCoverage,alphaMap:pe,alphaTest:fe,alphaHash:me,combine:s.combine,mapUv:U&&m(s.map.channel),aoMapUv:B&&m(s.aoMap.channel),lightMapUv:k&&m(s.lightMap.channel),bumpMapUv:z&&m(s.bumpMap.channel),normalMapUv:V&&m(s.normalMap.channel),displacementMapUv:G&&m(s.displacementMap.channel),emissiveMapUv:H&&m(s.emissiveMap.channel),metalnessMapUv:j&&m(s.metalnessMap.channel),roughnessMapUv:W&&m(s.roughnessMap.channel),anisotropyMapUv:J&&m(s.anisotropyMap.channel),clearcoatMapUv:ee&&m(s.clearcoatMap.channel),clearcoatNormalMapUv:te&&m(s.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:ne&&m(s.clearcoatRoughnessMap.channel),iridescenceMapUv:re&&m(s.iridescenceMap.channel),iridescenceThicknessMapUv:ie&&m(s.iridescenceThicknessMap.channel),sheenColorMapUv:se&&m(s.sheenColorMap.channel),sheenRoughnessMapUv:ae&&m(s.sheenRoughnessMap.channel),specularMapUv:oe&&m(s.specularMap.channel),specularColorMapUv:le&&m(s.specularColorMap.channel),specularIntensityMapUv:ue&&m(s.specularIntensityMap.channel),transmissionMapUv:ce&&m(s.transmissionMap.channel),thicknessMapUv:he&&m(s.thicknessMap.channel),alphaMapUv:pe&&m(s.alphaMap.channel),vertexTangents:!!y.attributes.tangent&&(V||q),vertexColors:s.vertexColors,vertexAlphas:!0===s.vertexColors&&!!y.attributes.color&&4===y.attributes.color.itemSize,pointsUvs:!0===_.isPoints&&!!y.attributes.uv&&(U||pe),fog:!!v,useFog:!0===s.fog,fogExp2:!!v&&v.isFogExp2,flatShading:!0===s.flatShading&&!1===s.wireframe,sizeAttenuation:!0===s.sizeAttenuation,logarithmicDepthBuffer:h,reverseDepthBuffer:L,skinning:!0===_.isSkinnedMesh,morphTargets:void 0!==y.morphAttributes.position,morphNormals:void 0!==y.morphAttributes.normal,morphColors:void 0!==y.morphAttributes.color,morphTargetsCount:w,morphTextureStride:N,numDirLights:o.directional.length,numPointLights:o.point.length,numSpotLights:o.spot.length,numSpotLightMaps:o.spotLightMap.length,numRectAreaLights:o.rectArea.length,numHemiLights:o.hemi.length,numDirLightShadows:o.directionalShadowMap.length,numPointLightShadows:o.pointShadowMap.length,numSpotLightShadows:o.spotShadowMap.length,numSpotLightShadowsWithMaps:o.numSpotLightShadowsWithMaps,numLightProbes:o.numLightProbes,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:s.dithering,shadowMapEnabled:e.shadowMap.enabled&&c.length>0,shadowMapType:e.shadowMap.type,toneMapping:_e,decodeVideoTexture:U&&!0===s.map.isVideoTexture&&$t.getTransfer(s.map.colorSpace)===at,decodeVideoTextureEmissive:H&&!0===s.emissiveMap.isVideoTexture&&$t.getTransfer(s.emissiveMap.colorSpace)===at,premultipliedAlpha:s.premultipliedAlpha,doubleSided:2===s.side,flipSided:1===s.side,useDepthPacking:s.depthPacking>=0,depthPacking:s.depthPacking||0,index0AttributeName:s.index0AttributeName,extensionClipCullDistance:ge&&!0===s.extensions.clipCullDistance&&r.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(ge&&!0===s.extensions.multiDraw||I)&&r.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:r.has("KHR_parallel_shader_compile"),customProgramCacheKey:s.customProgramCacheKey()};return ve.vertexUv1s=u.has(1),ve.vertexUv2s=u.has(2),ve.vertexUv3s=u.has(3),u.clear(),ve},getProgramCacheKey:function(t){const n=[];if(t.shaderID?n.push(t.shaderID):(n.push(t.customVertexShaderID),n.push(t.customFragmentShaderID)),void 0!==t.defines)for(const e in t.defines)n.push(e),n.push(t.defines[e]);return!1===t.isRawShaderMaterial&&(!function(e,t){e.push(t.precision),e.push(t.outputColorSpace),e.push(t.envMapMode),e.push(t.envMapCubeUVHeight),e.push(t.mapUv),e.push(t.alphaMapUv),e.push(t.lightMapUv),e.push(t.aoMapUv),e.push(t.bumpMapUv),e.push(t.normalMapUv),e.push(t.displacementMapUv),e.push(t.emissiveMapUv),e.push(t.metalnessMapUv),e.push(t.roughnessMapUv),e.push(t.anisotropyMapUv),e.push(t.clearcoatMapUv),e.push(t.clearcoatNormalMapUv),e.push(t.clearcoatRoughnessMapUv),e.push(t.iridescenceMapUv),e.push(t.iridescenceThicknessMapUv),e.push(t.sheenColorMapUv),e.push(t.sheenRoughnessMapUv),e.push(t.specularMapUv),e.push(t.specularColorMapUv),e.push(t.specularIntensityMapUv),e.push(t.transmissionMapUv),e.push(t.thicknessMapUv),e.push(t.combine),e.push(t.fogExp2),e.push(t.sizeAttenuation),e.push(t.morphTargetsCount),e.push(t.morphAttributeCount),e.push(t.numDirLights),e.push(t.numPointLights),e.push(t.numSpotLights),e.push(t.numSpotLightMaps),e.push(t.numHemiLights),e.push(t.numRectAreaLights),e.push(t.numDirLightShadows),e.push(t.numPointLightShadows),e.push(t.numSpotLightShadows),e.push(t.numSpotLightShadowsWithMaps),e.push(t.numLightProbes),e.push(t.shadowMapType),e.push(t.toneMapping),e.push(t.numClippingPlanes),e.push(t.numClipIntersection),e.push(t.depthPacking)}(n,t),function(e,t){o.disableAll(),t.supportsVertexTextures&&o.enable(0);t.instancing&&o.enable(1);t.instancingColor&&o.enable(2);t.instancingMorph&&o.enable(3);t.matcap&&o.enable(4);t.envMap&&o.enable(5);t.normalMapObjectSpace&&o.enable(6);t.normalMapTangentSpace&&o.enable(7);t.clearcoat&&o.enable(8);t.iridescence&&o.enable(9);t.alphaTest&&o.enable(10);t.vertexColors&&o.enable(11);t.vertexAlphas&&o.enable(12);t.vertexUv1s&&o.enable(13);t.vertexUv2s&&o.enable(14);t.vertexUv3s&&o.enable(15);t.vertexTangents&&o.enable(16);t.anisotropy&&o.enable(17);t.alphaHash&&o.enable(18);t.batching&&o.enable(19);t.dispersion&&o.enable(20);t.batchingColor&&o.enable(21);t.gradientMap&&o.enable(22);e.push(o.mask),o.disableAll(),t.fog&&o.enable(0);t.useFog&&o.enable(1);t.flatShading&&o.enable(2);t.logarithmicDepthBuffer&&o.enable(3);t.reverseDepthBuffer&&o.enable(4);t.skinning&&o.enable(5);t.morphTargets&&o.enable(6);t.morphNormals&&o.enable(7);t.morphColors&&o.enable(8);t.premultipliedAlpha&&o.enable(9);t.shadowMapEnabled&&o.enable(10);t.doubleSided&&o.enable(11);t.flipSided&&o.enable(12);t.useDepthPacking&&o.enable(13);t.dithering&&o.enable(14);t.transmission&&o.enable(15);t.sheen&&o.enable(16);t.opaque&&o.enable(17);t.pointsUvs&&o.enable(18);t.decodeVideoTexture&&o.enable(19);t.decodeVideoTextureEmissive&&o.enable(20);t.alphaToCoverage&&o.enable(21);e.push(o.mask)}(n,t),n.push(e.outputColorSpace)),n.push(t.customProgramCacheKey),n.join()},getUniforms:function(e){const t=f[e.type];let n;if(t){const e=Ma[t];n=vi.clone(e.uniforms)}else n=e.uniforms;return n},acquireProgram:function(t,n){let r;for(let e=0,t=c.length;e<t;e++){const t=c[e];if(t.cacheKey===n){r=t,++r.usedTimes;break}}return void 0===r&&(r=new Nl(e,n,t,s),c.push(r)),r},releaseProgram:function(e){if(0===--e.usedTimes){const t=c.indexOf(e);c[t]=c[c.length-1],c.pop(),e.destroy()}},releaseShaderCache:function(e){l.remove(e)},programs:c,dispose:function(){l.dispose()}}}function Ul(){let e=new WeakMap;return{has:function(t){return e.has(t)},get:function(t){let n=e.get(t);return void 0===n&&(n={},e.set(t,n)),n},remove:function(t){e.delete(t)},update:function(t,n,r){e.get(t)[n]=r},dispose:function(){e=new WeakMap}}}function Ol(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.material.id!==t.material.id?e.material.id-t.material.id:e.z!==t.z?e.z-t.z:e.id-t.id}function Fl(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 Bl(){const e=[];let t=0;const n=[],r=[],i=[];function s(n,r,i,s,a,o){let l=e[t];return void 0===l?(l={id:n.id,object:n,geometry:r,material:i,groupOrder:s,renderOrder:n.renderOrder,z:a,group:o},e[t]=l):(l.id=n.id,l.object=n,l.geometry=r,l.material=i,l.groupOrder=s,l.renderOrder=n.renderOrder,l.z=a,l.group=o),t++,l}return{opaque:n,transmissive:r,transparent:i,init:function(){t=0,n.length=0,r.length=0,i.length=0},push:function(e,t,a,o,l,u){const c=s(e,t,a,o,l,u);a.transmission>0?r.push(c):!0===a.transparent?i.push(c):n.push(c)},unshift:function(e,t,a,o,l,u){const c=s(e,t,a,o,l,u);a.transmission>0?r.unshift(c):!0===a.transparent?i.unshift(c):n.unshift(c)},finish:function(){for(let n=t,r=e.length;n<r;n++){const t=e[n];if(null===t.id)break;t.id=null,t.object=null,t.geometry=null,t.material=null,t.group=null}},sort:function(e,t){n.length>1&&n.sort(e||Ol),r.length>1&&r.sort(t||Fl),i.length>1&&i.sort(t||Fl)}}}function kl(){let e=new WeakMap;return{get:function(t,n){const r=e.get(t);let i;return void 0===r?(i=new Bl,e.set(t,[i])):n>=r.length?(i=new Bl,r.push(i)):i=r[n],i},dispose:function(){e=new WeakMap}}}function zl(){const e={};return{get:function(t){if(void 0!==e[t.id])return e[t.id];let n;switch(t.type){case"DirectionalLight":n={direction:new Ut,color:new Nr};break;case"SpotLight":n={position:new Ut,direction:new Ut,color:new Nr,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":n={position:new Ut,color:new Nr,distance:0,decay:0};break;case"HemisphereLight":n={direction:new Ut,skyColor:new Nr,groundColor:new Nr};break;case"RectAreaLight":n={color:new Nr,position:new Ut,halfWidth:new Ut,halfHeight:new Ut}}return e[t.id]=n,n}}}let Vl=0;function Gl(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+(t.map?1:0)-(e.map?1:0)}function Hl(e){const t=new zl,n=function(){const e={};return{get:function(t){if(void 0!==e[t.id])return e[t.id];let n;switch(t.type){case"DirectionalLight":case"SpotLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Dt};break;case"PointLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Dt,shadowCameraNear:1,shadowCameraFar:1e3}}return e[t.id]=n,n}}}(),r={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let e=0;e<9;e++)r.probe.push(new Ut);const i=new Ut,s=new Bn,a=new Bn;return{setup:function(i){let s=0,a=0,o=0;for(let e=0;e<9;e++)r.probe[e].set(0,0,0);let l=0,u=0,c=0,h=0,d=0,p=0,f=0,m=0,g=0,_=0,v=0;i.sort(Gl);for(let e=0,y=i.length;e<y;e++){const y=i[e],x=y.color,b=y.intensity,T=y.distance,S=y.shadow&&y.shadow.map?y.shadow.map.texture:null;if(y.isAmbientLight)s+=x.r*b,a+=x.g*b,o+=x.b*b;else if(y.isLightProbe){for(let e=0;e<9;e++)r.probe[e].addScaledVector(y.sh.coefficients[e],b);v++}else if(y.isDirectionalLight){const e=t.get(y);if(e.color.copy(y.color).multiplyScalar(y.intensity),y.castShadow){const e=y.shadow,t=n.get(y);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,r.directionalShadow[l]=t,r.directionalShadowMap[l]=S,r.directionalShadowMatrix[l]=y.shadow.matrix,p++}r.directional[l]=e,l++}else if(y.isSpotLight){const e=t.get(y);e.position.setFromMatrixPosition(y.matrixWorld),e.color.copy(x).multiplyScalar(b),e.distance=T,e.coneCos=Math.cos(y.angle),e.penumbraCos=Math.cos(y.angle*(1-y.penumbra)),e.decay=y.decay,r.spot[c]=e;const i=y.shadow;if(y.map&&(r.spotLightMap[g]=y.map,g++,i.updateMatrices(y),y.castShadow&&_++),r.spotLightMatrix[c]=i.matrix,y.castShadow){const e=n.get(y);e.shadowIntensity=i.intensity,e.shadowBias=i.bias,e.shadowNormalBias=i.normalBias,e.shadowRadius=i.radius,e.shadowMapSize=i.mapSize,r.spotShadow[c]=e,r.spotShadowMap[c]=S,m++}c++}else if(y.isRectAreaLight){const e=t.get(y);e.color.copy(x).multiplyScalar(b),e.halfWidth.set(.5*y.width,0,0),e.halfHeight.set(0,.5*y.height,0),r.rectArea[h]=e,h++}else if(y.isPointLight){const e=t.get(y);if(e.color.copy(y.color).multiplyScalar(y.intensity),e.distance=y.distance,e.decay=y.decay,y.castShadow){const e=y.shadow,t=n.get(y);t.shadowIntensity=e.intensity,t.shadowBias=e.bias,t.shadowNormalBias=e.normalBias,t.shadowRadius=e.radius,t.shadowMapSize=e.mapSize,t.shadowCameraNear=e.camera.near,t.shadowCameraFar=e.camera.far,r.pointShadow[u]=t,r.pointShadowMap[u]=S,r.pointShadowMatrix[u]=y.shadow.matrix,f++}r.point[u]=e,u++}else if(y.isHemisphereLight){const e=t.get(y);e.skyColor.copy(y.color).multiplyScalar(b),e.groundColor.copy(y.groundColor).multiplyScalar(b),r.hemi[d]=e,d++}}h>0&&(!0===e.has("OES_texture_float_linear")?(r.rectAreaLTC1=Sa.LTC_FLOAT_1,r.rectAreaLTC2=Sa.LTC_FLOAT_2):(r.rectAreaLTC1=Sa.LTC_HALF_1,r.rectAreaLTC2=Sa.LTC_HALF_2)),r.ambient[0]=s,r.ambient[1]=a,r.ambient[2]=o;const y=r.hash;y.directionalLength===l&&y.pointLength===u&&y.spotLength===c&&y.rectAreaLength===h&&y.hemiLength===d&&y.numDirectionalShadows===p&&y.numPointShadows===f&&y.numSpotShadows===m&&y.numSpotMaps===g&&y.numLightProbes===v||(r.directional.length=l,r.spot.length=c,r.rectArea.length=h,r.point.length=u,r.hemi.length=d,r.directionalShadow.length=p,r.directionalShadowMap.length=p,r.pointShadow.length=f,r.pointShadowMap.length=f,r.spotShadow.length=m,r.spotShadowMap.length=m,r.directionalShadowMatrix.length=p,r.pointShadowMatrix.length=f,r.spotLightMatrix.length=m+g-_,r.spotLightMap.length=g,r.numSpotLightShadowsWithMaps=_,r.numLightProbes=v,y.directionalLength=l,y.pointLength=u,y.spotLength=c,y.rectAreaLength=h,y.hemiLength=d,y.numDirectionalShadows=p,y.numPointShadows=f,y.numSpotShadows=m,y.numSpotMaps=g,y.numLightProbes=v,r.version=Vl++)},setupView:function(e,t){let n=0,o=0,l=0,u=0,c=0;const h=t.matrixWorldInverse;for(let t=0,d=e.length;t<d;t++){const d=e[t];if(d.isDirectionalLight){const e=r.directional[n];e.direction.setFromMatrixPosition(d.matrixWorld),i.setFromMatrixPosition(d.target.matrixWorld),e.direction.sub(i),e.direction.transformDirection(h),n++}else if(d.isSpotLight){const e=r.spot[l];e.position.setFromMatrixPosition(d.matrixWorld),e.position.applyMatrix4(h),e.direction.setFromMatrixPosition(d.matrixWorld),i.setFromMatrixPosition(d.target.matrixWorld),e.direction.sub(i),e.direction.transformDirection(h),l++}else if(d.isRectAreaLight){const e=r.rectArea[u];e.position.setFromMatrixPosition(d.matrixWorld),e.position.applyMatrix4(h),a.identity(),s.copy(d.matrixWorld),s.premultiply(h),a.extractRotation(s),e.halfWidth.set(.5*d.width,0,0),e.halfHeight.set(0,.5*d.height,0),e.halfWidth.applyMatrix4(a),e.halfHeight.applyMatrix4(a),u++}else if(d.isPointLight){const e=r.point[o];e.position.setFromMatrixPosition(d.matrixWorld),e.position.applyMatrix4(h),o++}else if(d.isHemisphereLight){const e=r.hemi[c];e.direction.setFromMatrixPosition(d.matrixWorld),e.direction.transformDirection(h),c++}}},state:r}}function jl(e){const t=new Hl(e),n=[],r=[];const i={lightsArray:n,shadowsArray:r,camera:null,lights:t,transmissionRenderTarget:{}};return{init:function(e){i.camera=e,n.length=0,r.length=0},state:i,setupLights:function(){t.setup(n)},setupLightsView:function(e){t.setupView(n,e)},pushLight:function(e){n.push(e)},pushShadow:function(e){r.push(e)}}}function Wl(e){let t=new WeakMap;return{get:function(n,r=0){const i=t.get(n);let s;return void 0===i?(s=new jl(e),t.set(n,[s])):r>=i.length?(s=new jl(e),i.push(s)):s=i[r],s},dispose:function(){t=new WeakMap}}}function Xl(e,t,n){let r=new Xi;const i=new Dt,s=new Dt,a=new an,o=new Ds({depthPacking:3201}),l=new Is,u={},c=n.maxTextureSize,h={[p]:1,[f]:0,[m]:2},d=new yi({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Dt},radius:{value:4}},vertexShader:"void main() {\n\tgl_Position = vec4( position, 1.0 );\n}",fragmentShader:"uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}"}),g=d.clone();g.defines.HORIZONTAL_PASS=1;const _=new ei;_.setAttribute("position",new Gr(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const v=new di(_,d),y=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1;let x=this.type;function b(n,r){const s=t.update(v);d.defines.VSM_SAMPLES!==n.blurSamples&&(d.defines.VSM_SAMPLES=n.blurSamples,g.defines.VSM_SAMPLES=n.blurSamples,d.needsUpdate=!0,g.needsUpdate=!0),null===n.mapPass&&(n.mapPass=new ln(i.x,i.y)),d.uniforms.shadow_pass.value=n.map.texture,d.uniforms.resolution.value=n.mapSize,d.uniforms.radius.value=n.radius,e.setRenderTarget(n.mapPass),e.clear(),e.renderBufferDirect(r,null,s,d,v,null),g.uniforms.shadow_pass.value=n.mapPass.texture,g.uniforms.resolution.value=n.mapSize,g.uniforms.radius.value=n.radius,e.setRenderTarget(n.map),e.clear(),e.renderBufferDirect(r,null,s,g,v,null)}function T(t,n,r,i){let s=null;const a=!0===r.isPointLight?t.customDistanceMaterial:t.customDepthMaterial;if(void 0!==a)s=a;else if(s=!0===r.isPointLight?l:o,e.localClippingEnabled&&!0===n.clipShadows&&Array.isArray(n.clippingPlanes)&&0!==n.clippingPlanes.length||n.displacementMap&&0!==n.displacementScale||n.alphaMap&&n.alphaTest>0||n.map&&n.alphaTest>0||!0===n.alphaToCoverage){const e=s.uuid,t=n.uuid;let r=u[e];void 0===r&&(r={},u[e]=r);let i=r[t];void 0===i&&(i=s.clone(),r[t]=i,n.addEventListener("dispose",M)),s=i}if(s.visible=n.visible,s.wireframe=n.wireframe,s.side=3===i?null!==n.shadowSide?n.shadowSide:n.side:null!==n.shadowSide?n.shadowSide:h[n.side],s.alphaMap=n.alphaMap,s.alphaTest=!0===n.alphaToCoverage?.5:n.alphaTest,s.map=n.map,s.clipShadows=n.clipShadows,s.clippingPlanes=n.clippingPlanes,s.clipIntersection=n.clipIntersection,s.displacementMap=n.displacementMap,s.displacementScale=n.displacementScale,s.displacementBias=n.displacementBias,s.wireframeLinewidth=n.wireframeLinewidth,s.linewidth=n.linewidth,!0===r.isPointLight&&!0===s.isMeshDistanceMaterial){e.properties.get(s).light=r}return s}function S(n,i,s,a,o){if(!1===n.visible)return;if(n.layers.test(i.layers)&&(n.isMesh||n.isLine||n.isPoints)&&(n.castShadow||n.receiveShadow&&3===o)&&(!n.frustumCulled||r.intersectsObject(n))){n.modelViewMatrix.multiplyMatrices(s.matrixWorldInverse,n.matrixWorld);const r=t.update(n),l=n.material;if(Array.isArray(l)){const t=r.groups;for(let u=0,c=t.length;u<c;u++){const c=t[u],h=l[c.materialIndex];if(h&&h.visible){const t=T(n,h,a,o);n.onBeforeShadow(e,n,i,s,r,t,c),e.renderBufferDirect(s,null,r,t,n,c),n.onAfterShadow(e,n,i,s,r,t,c)}}}else if(l.visible){const t=T(n,l,a,o);n.onBeforeShadow(e,n,i,s,r,t,null),e.renderBufferDirect(s,null,r,t,n,null),n.onAfterShadow(e,n,i,s,r,t,null)}}const l=n.children;for(let e=0,t=l.length;e<t;e++)S(l[e],i,s,a,o)}function M(e){e.target.removeEventListener("dispose",M);for(const t in u){const n=u[t],r=e.target.uuid;if(r in n){n[r].dispose(),delete n[r]}}}this.render=function(t,n,o){if(!1===y.enabled)return;if(!1===y.autoUpdate&&!1===y.needsUpdate)return;if(0===t.length)return;const l=e.getRenderTarget(),u=e.getActiveCubeFace(),h=e.getActiveMipmapLevel(),d=e.state;d.setBlending(0),d.buffers.color.setClear(1,1,1,1),d.buffers.depth.setTest(!0),d.setScissorTest(!1);const p=3!==x&&3===this.type,f=3===x&&3!==this.type;for(let l=0,u=t.length;l<u;l++){const u=t[l],h=u.shadow;if(void 0===h){console.warn("THREE.WebGLShadowMap:",u,"has no shadow.");continue}if(!1===h.autoUpdate&&!1===h.needsUpdate)continue;i.copy(h.mapSize);const m=h.getFrameExtents();if(i.multiply(m),s.copy(h.mapSize),(i.x>c||i.y>c)&&(i.x>c&&(s.x=Math.floor(c/m.x),i.x=s.x*m.x,h.mapSize.x=s.x),i.y>c&&(s.y=Math.floor(c/m.y),i.y=s.y*m.y,h.mapSize.y=s.y)),null===h.map||!0===p||!0===f){const e=3!==this.type?{minFilter:K,magFilter:K}:{};null!==h.map&&h.map.dispose(),h.map=new ln(i.x,i.y,e),h.map.texture.name=u.name+".shadowMap",h.camera.updateProjectionMatrix()}e.setRenderTarget(h.map),e.clear();const g=h.getViewportCount();for(let e=0;e<g;e++){const t=h.getViewport(e);a.set(s.x*t.x,s.y*t.y,s.x*t.z,s.y*t.w),d.viewport(a),h.updateMatrices(u,e),r=h.getFrustum(),S(n,o,h.camera,u,this.type)}!0!==h.isPointLightShadow&&3===this.type&&b(h,o),h.needsUpdate=!1}x=this.type,y.needsUpdate=!1,e.setRenderTarget(l,u,h)}}const ql={[I]:1,[O]:6,[B]:7,[F]:5,[U]:0,[z]:2,[V]:4,[k]:3};function $l(e,t){const n=new function(){let t=!1;const n=new an;let r=null;const i=new an(0,0,0,0);return{setMask:function(n){r===n||t||(e.colorMask(n,n,n,n),r=n)},setLocked:function(e){t=e},setClear:function(t,r,s,a,o){!0===o&&(t*=a,r*=a,s*=a),n.set(t,r,s,a),!1===i.equals(n)&&(e.clearColor(t,r,s,a),i.copy(n))},reset:function(){t=!1,r=null,i.set(-1,0,0,0)}}},r=new function(){let n=!1,r=!1,i=null,s=null,a=null;return{setReversed:function(e){if(r!==e){const n=t.get("EXT_clip_control");e?n.clipControlEXT(n.LOWER_LEFT_EXT,n.ZERO_TO_ONE_EXT):n.clipControlEXT(n.LOWER_LEFT_EXT,n.NEGATIVE_ONE_TO_ONE_EXT),r=e;const i=a;a=null,this.setClear(i)}},getReversed:function(){return r},setTest:function(t){t?ie(e.DEPTH_TEST):se(e.DEPTH_TEST)},setMask:function(t){i===t||n||(e.depthMask(t),i=t)},setFunc:function(t){if(r&&(t=ql[t]),s!==t){switch(t){case 0:e.depthFunc(e.NEVER);break;case 1:e.depthFunc(e.ALWAYS);break;case 2:e.depthFunc(e.LESS);break;case 3:default:e.depthFunc(e.LEQUAL);break;case 4:e.depthFunc(e.EQUAL);break;case 5:e.depthFunc(e.GEQUAL);break;case 6:e.depthFunc(e.GREATER);break;case 7:e.depthFunc(e.NOTEQUAL)}s=t}},setLocked:function(e){n=e},setClear:function(t){a!==t&&(r&&(t=1-t),e.clearDepth(t),a=t)},reset:function(){n=!1,i=null,s=null,a=null,r=!1}}},i=new function(){let t=!1,n=null,r=null,i=null,s=null,a=null,o=null,l=null,u=null;return{setTest:function(n){t||(n?ie(e.STENCIL_TEST):se(e.STENCIL_TEST))},setMask:function(r){n===r||t||(e.stencilMask(r),n=r)},setFunc:function(t,n,a){r===t&&i===n&&s===a||(e.stencilFunc(t,n,a),r=t,i=n,s=a)},setOp:function(t,n,r){a===t&&o===n&&l===r||(e.stencilOp(t,n,r),a=t,o=n,l=r)},setLocked:function(e){t=e},setClear:function(t){u!==t&&(e.clearStencil(t),u=t)},reset:function(){t=!1,n=null,r=null,i=null,s=null,a=null,o=null,l=null,u=null}}},s=new WeakMap,a=new WeakMap;let o={},l={},u=new WeakMap,c=[],h=null,d=!1,p=null,f=null,m=null,I=null,U=null,O=null,F=null,B=new Nr(0,0,0),k=0,z=!1,V=null,G=null,H=null,j=null,W=null;const X=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let q=!1,$=0;const Y=e.getParameter(e.VERSION);-1!==Y.indexOf("WebGL")?($=parseFloat(/^WebGL (\d)/.exec(Y)[1]),q=$>=1):-1!==Y.indexOf("OpenGL ES")&&($=parseFloat(/^OpenGL ES (\d)/.exec(Y)[1]),q=$>=2);let K=null,Q={};const Z=e.getParameter(e.SCISSOR_BOX),J=e.getParameter(e.VIEWPORT),ee=(new an).fromArray(Z),te=(new an).fromArray(J);function ne(t,n,r,i){const s=new Uint8Array(4),a=e.createTexture();e.bindTexture(t,a),e.texParameteri(t,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(t,e.TEXTURE_MAG_FILTER,e.NEAREST);for(let a=0;a<r;a++)t===e.TEXTURE_3D||t===e.TEXTURE_2D_ARRAY?e.texImage3D(n,0,e.RGBA,1,1,i,0,e.RGBA,e.UNSIGNED_BYTE,s):e.texImage2D(n+a,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,s);return a}const re={};function ie(t){!0!==o[t]&&(e.enable(t),o[t]=!0)}function se(t){!1!==o[t]&&(e.disable(t),o[t]=!1)}re[e.TEXTURE_2D]=ne(e.TEXTURE_2D,e.TEXTURE_2D,1),re[e.TEXTURE_CUBE_MAP]=ne(e.TEXTURE_CUBE_MAP,e.TEXTURE_CUBE_MAP_POSITIVE_X,6),re[e.TEXTURE_2D_ARRAY]=ne(e.TEXTURE_2D_ARRAY,e.TEXTURE_2D_ARRAY,1,1),re[e.TEXTURE_3D]=ne(e.TEXTURE_3D,e.TEXTURE_3D,1,1),n.setClear(0,0,0,1),r.setClear(1),i.setClear(0),ie(e.DEPTH_TEST),r.setFunc(3),ue(!1),ce(1),ie(e.CULL_FACE),le(0);const ae={[g]:e.FUNC_ADD,[_]:e.FUNC_SUBTRACT,[v]:e.FUNC_REVERSE_SUBTRACT};ae[103]=e.MIN,ae[104]=e.MAX;const oe={[y]:e.ZERO,[x]:e.ONE,[b]:e.SRC_COLOR,[S]:e.SRC_ALPHA,[C]:e.SRC_ALPHA_SATURATE,[A]:e.DST_COLOR,[w]:e.DST_ALPHA,[T]:e.ONE_MINUS_SRC_COLOR,[M]:e.ONE_MINUS_SRC_ALPHA,[R]:e.ONE_MINUS_DST_COLOR,[E]:e.ONE_MINUS_DST_ALPHA,[N]:e.CONSTANT_COLOR,[P]:e.ONE_MINUS_CONSTANT_COLOR,[L]:e.CONSTANT_ALPHA,[D]:e.ONE_MINUS_CONSTANT_ALPHA};function le(t,n,r,i,s,a,o,l,u,c){if(0!==t){if(!1===d&&(ie(e.BLEND),d=!0),5===t)s=s||n,a=a||r,o=o||i,n===f&&s===U||(e.blendEquationSeparate(ae[n],ae[s]),f=n,U=s),r===m&&i===I&&a===O&&o===F||(e.blendFuncSeparate(oe[r],oe[i],oe[a],oe[o]),m=r,I=i,O=a,F=o),!1!==l.equals(B)&&u===k||(e.blendColor(l.r,l.g,l.b,u),B.copy(l),k=u),p=t,z=!1;else if(t!==p||c!==z){if(f===g&&U===g||(e.blendEquation(e.FUNC_ADD),f=g,U=g),c)switch(t){case 1:e.blendFuncSeparate(e.ONE,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 2:e.blendFunc(e.ONE,e.ONE);break;case 3:e.blendFuncSeparate(e.ZERO,e.ONE_MINUS_SRC_COLOR,e.ZERO,e.ONE);break;case 4:e.blendFuncSeparate(e.DST_COLOR,e.ONE_MINUS_SRC_ALPHA,e.ZERO,e.ONE);break;default:console.error("THREE.WebGLState: Invalid blending: ",t)}else switch(t){case 1:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case 2:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE,e.ONE,e.ONE);break;case 3:console.error("THREE.WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case 4:console.error("THREE.WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:console.error("THREE.WebGLState: Invalid blending: ",t)}m=null,I=null,O=null,F=null,B.set(0,0,0),k=0,p=t,z=c}}else!0===d&&(se(e.BLEND),d=!1)}function ue(t){V!==t&&(t?e.frontFace(e.CW):e.frontFace(e.CCW),V=t)}function ce(t){0!==t?(ie(e.CULL_FACE),t!==G&&(1===t?e.cullFace(e.BACK):2===t?e.cullFace(e.FRONT):e.cullFace(e.FRONT_AND_BACK))):se(e.CULL_FACE),G=t}function he(t,n,r){t?(ie(e.POLYGON_OFFSET_FILL),j===n&&W===r||(e.polygonOffset(n,r),j=n,W=r)):se(e.POLYGON_OFFSET_FILL)}return{buffers:{color:n,depth:r,stencil:i},enable:ie,disable:se,bindFramebuffer:function(t,n){return l[t]!==n&&(e.bindFramebuffer(t,n),l[t]=n,t===e.DRAW_FRAMEBUFFER&&(l[e.FRAMEBUFFER]=n),t===e.FRAMEBUFFER&&(l[e.DRAW_FRAMEBUFFER]=n),!0)},drawBuffers:function(t,n){let r=c,i=!1;if(t){r=u.get(n),void 0===r&&(r=[],u.set(n,r));const s=t.textures;if(r.length!==s.length||r[0]!==e.COLOR_ATTACHMENT0){for(let t=0,n=s.length;t<n;t++)r[t]=e.COLOR_ATTACHMENT0+t;r.length=s.length,i=!0}}else r[0]!==e.BACK&&(r[0]=e.BACK,i=!0);i&&e.drawBuffers(r)},useProgram:function(t){return h!==t&&(e.useProgram(t),h=t,!0)},setBlending:le,setMaterial:function(t,s){2===t.side?se(e.CULL_FACE):ie(e.CULL_FACE);let a=1===t.side;s&&(a=!a),ue(a),1===t.blending&&!1===t.transparent?le(0):le(t.blending,t.blendEquation,t.blendSrc,t.blendDst,t.blendEquationAlpha,t.blendSrcAlpha,t.blendDstAlpha,t.blendColor,t.blendAlpha,t.premultipliedAlpha),r.setFunc(t.depthFunc),r.setTest(t.depthTest),r.setMask(t.depthWrite),n.setMask(t.colorWrite);const o=t.stencilWrite;i.setTest(o),o&&(i.setMask(t.stencilWriteMask),i.setFunc(t.stencilFunc,t.stencilRef,t.stencilFuncMask),i.setOp(t.stencilFail,t.stencilZFail,t.stencilZPass)),he(t.polygonOffset,t.polygonOffsetFactor,t.polygonOffsetUnits),!0===t.alphaToCoverage?ie(e.SAMPLE_ALPHA_TO_COVERAGE):se(e.SAMPLE_ALPHA_TO_COVERAGE)},setFlipSided:ue,setCullFace:ce,setLineWidth:function(t){t!==H&&(q&&e.lineWidth(t),H=t)},setPolygonOffset:he,setScissorTest:function(t){t?ie(e.SCISSOR_TEST):se(e.SCISSOR_TEST)},activeTexture:function(t){void 0===t&&(t=e.TEXTURE0+X-1),K!==t&&(e.activeTexture(t),K=t)},bindTexture:function(t,n,r){void 0===r&&(r=null===K?e.TEXTURE0+X-1:K);let i=Q[r];void 0===i&&(i={type:void 0,texture:void 0},Q[r]=i),i.type===t&&i.texture===n||(K!==r&&(e.activeTexture(r),K=r),e.bindTexture(t,n||re[t]),i.type=t,i.texture=n)},unbindTexture:function(){const t=Q[K];void 0!==t&&void 0!==t.type&&(e.bindTexture(t.type,null),t.type=void 0,t.texture=void 0)},compressedTexImage2D:function(){try{e.compressedTexImage2D(...arguments)}catch(e){console.error("THREE.WebGLState:",e)}},compressedTexImage3D:function(){try{e.compressedTexImage3D(...arguments)}catch(e){console.error("THREE.WebGLState:",e)}},texImage2D:function(){try{e.texImage2D(...arguments)}catch(e){console.error("THREE.WebGLState:",e)}},texImage3D:function(){try{e.texImage3D(...arguments)}catch(e){console.error("THREE.WebGLState:",e)}},updateUBOMapping:function(t,n){let r=a.get(n);void 0===r&&(r=new WeakMap,a.set(n,r));let i=r.get(t);void 0===i&&(i=e.getUniformBlockIndex(n,t.name),r.set(t,i))},uniformBlockBinding:function(t,n){const r=a.get(n).get(t);s.get(n)!==r&&(e.uniformBlockBinding(n,r,t.__bindingPointIndex),s.set(n,r))},texStorage2D:function(){try{e.texStorage2D(...arguments)}catch(e){console.error("THREE.WebGLState:",e)}},texStorage3D:function(){try{e.texStorage3D(...arguments)}catch(e){console.error("THREE.WebGLState:",e)}},texSubImage2D:function(){try{e.texSubImage2D(...arguments)}catch(e){console.error("THREE.WebGLState:",e)}},texSubImage3D:function(){try{e.texSubImage3D(...arguments)}catch(e){console.error("THREE.WebGLState:",e)}},compressedTexSubImage2D:function(){try{e.compressedTexSubImage2D(...arguments)}catch(e){console.error("THREE.WebGLState:",e)}},compressedTexSubImage3D:function(){try{e.compressedTexSubImage3D(...arguments)}catch(e){console.error("THREE.WebGLState:",e)}},scissor:function(t){!1===ee.equals(t)&&(e.scissor(t.x,t.y,t.z,t.w),ee.copy(t))},viewport:function(t){!1===te.equals(t)&&(e.viewport(t.x,t.y,t.z,t.w),te.copy(t))},reset:function(){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),r.setReversed(!1),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),o={},K=null,Q={},l={},u=new WeakMap,c=[],h=null,d=!1,p=null,f=null,m=null,I=null,U=null,O=null,F=null,B=new Nr(0,0,0),k=0,z=!1,V=null,G=null,H=null,j=null,W=null,ee.set(0,0,e.canvas.width,e.canvas.height),te.set(0,0,e.canvas.width,e.canvas.height),n.reset(),r.reset(),i.reset()}}}function Yl(e,t,n,r,i,s,a){const o=t.has("WEBGL_multisampled_render_to_texture")?t.get("WEBGL_multisampled_render_to_texture"):null,l="undefined"!=typeof navigator&&/OculusBrowser/g.test(navigator.userAgent),u=new Dt,c=new WeakMap;let h;const d=new WeakMap;let p=!1;try{p="undefined"!=typeof OffscreenCanvas&&null!==new OffscreenCanvas(1,1).getContext("2d")}catch(e){}function f(e,t){return p?new OffscreenCanvas(e,t):Vt("canvas")}function m(e,t,n){let r=1;const i=H(e);if((i.width>n||i.height>n)&&(r=n/Math.max(i.width,i.height)),r<1){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof VideoFrame&&e instanceof VideoFrame){const n=Math.floor(r*i.width),s=Math.floor(r*i.height);void 0===h&&(h=f(n,s));const a=t?f(n,s):h;a.width=n,a.height=s;return a.getContext("2d").drawImage(e,0,0,n,s),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+i.width+"x"+i.height+") to ("+n+"x"+s+")."),a}return"data"in e&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+i.width+"x"+i.height+")."),e}return e}function g(e){return e.generateMipmaps}function _(t){e.generateMipmap(t)}function v(t){return t.isWebGLCubeRenderTarget?e.TEXTURE_CUBE_MAP:t.isWebGL3DRenderTarget?e.TEXTURE_3D:t.isWebGLArrayRenderTarget||t.isCompressedArrayTexture?e.TEXTURE_2D_ARRAY:e.TEXTURE_2D}function y(n,r,i,s,a=!1){if(null!==n){if(void 0!==e[n])return e[n];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+n+"'")}let o=r;if(r===e.RED&&(i===e.FLOAT&&(o=e.R32F),i===e.HALF_FLOAT&&(o=e.R16F),i===e.UNSIGNED_BYTE&&(o=e.R8)),r===e.RED_INTEGER&&(i===e.UNSIGNED_BYTE&&(o=e.R8UI),i===e.UNSIGNED_SHORT&&(o=e.R16UI),i===e.UNSIGNED_INT&&(o=e.R32UI),i===e.BYTE&&(o=e.R8I),i===e.SHORT&&(o=e.R16I),i===e.INT&&(o=e.R32I)),r===e.RG&&(i===e.FLOAT&&(o=e.RG32F),i===e.HALF_FLOAT&&(o=e.RG16F),i===e.UNSIGNED_BYTE&&(o=e.RG8)),r===e.RG_INTEGER&&(i===e.UNSIGNED_BYTE&&(o=e.RG8UI),i===e.UNSIGNED_SHORT&&(o=e.RG16UI),i===e.UNSIGNED_INT&&(o=e.RG32UI),i===e.BYTE&&(o=e.RG8I),i===e.SHORT&&(o=e.RG16I),i===e.INT&&(o=e.RG32I)),r===e.RGB_INTEGER&&(i===e.UNSIGNED_BYTE&&(o=e.RGB8UI),i===e.UNSIGNED_SHORT&&(o=e.RGB16UI),i===e.UNSIGNED_INT&&(o=e.RGB32UI),i===e.BYTE&&(o=e.RGB8I),i===e.SHORT&&(o=e.RGB16I),i===e.INT&&(o=e.RGB32I)),r===e.RGBA_INTEGER&&(i===e.UNSIGNED_BYTE&&(o=e.RGBA8UI),i===e.UNSIGNED_SHORT&&(o=e.RGBA16UI),i===e.UNSIGNED_INT&&(o=e.RGBA32UI),i===e.BYTE&&(o=e.RGBA8I),i===e.SHORT&&(o=e.RGBA16I),i===e.INT&&(o=e.RGBA32I)),r===e.RGB&&i===e.UNSIGNED_INT_5_9_9_9_REV&&(o=e.RGB9_E5),r===e.RGBA){const t=a?st:$t.getTransfer(s);i===e.FLOAT&&(o=e.RGBA32F),i===e.HALF_FLOAT&&(o=e.RGBA16F),i===e.UNSIGNED_BYTE&&(o=t===at?e.SRGB8_ALPHA8:e.RGBA8),i===e.UNSIGNED_SHORT_4_4_4_4&&(o=e.RGBA4),i===e.UNSIGNED_SHORT_5_5_5_1&&(o=e.RGB5_A1)}return o!==e.R16F&&o!==e.R32F&&o!==e.RG16F&&o!==e.RG32F&&o!==e.RGBA16F&&o!==e.RGBA32F||t.get("EXT_color_buffer_float"),o}function x(t,n){let r;return t?null===n||n===oe||n===de?r=e.DEPTH24_STENCIL8:n===le?r=e.DEPTH32F_STENCIL8:n===se&&(r=e.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):null===n||n===oe||n===de?r=e.DEPTH_COMPONENT24:n===le?r=e.DEPTH_COMPONENT32F:n===se&&(r=e.DEPTH_COMPONENT16),r}function b(e,t){return!0===g(e)||e.isFramebufferTexture&&e.minFilter!==K&&e.minFilter!==J?Math.log2(Math.max(t.width,t.height))+1:void 0!==e.mipmaps&&e.mipmaps.length>0?e.mipmaps.length:e.isCompressedTexture&&Array.isArray(e.image)?t.mipmaps.length:1}function T(e){const t=e.target;t.removeEventListener("dispose",T),function(e){const t=r.get(e);if(void 0===t.__webglInit)return;const n=e.source,i=d.get(n);if(i){const r=i[t.__cacheKey];r.usedTimes--,0===r.usedTimes&&M(e),0===Object.keys(i).length&&d.delete(n)}r.remove(e)}(t),t.isVideoTexture&&c.delete(t)}function S(t){const n=t.target;n.removeEventListener("dispose",S),function(t){const n=r.get(t);t.depthTexture&&(t.depthTexture.dispose(),r.remove(t.depthTexture));if(t.isWebGLCubeRenderTarget)for(let t=0;t<6;t++){if(Array.isArray(n.__webglFramebuffer[t]))for(let r=0;r<n.__webglFramebuffer[t].length;r++)e.deleteFramebuffer(n.__webglFramebuffer[t][r]);else e.deleteFramebuffer(n.__webglFramebuffer[t]);n.__webglDepthbuffer&&e.deleteRenderbuffer(n.__webglDepthbuffer[t])}else{if(Array.isArray(n.__webglFramebuffer))for(let t=0;t<n.__webglFramebuffer.length;t++)e.deleteFramebuffer(n.__webglFramebuffer[t]);else e.deleteFramebuffer(n.__webglFramebuffer);if(n.__webglDepthbuffer&&e.deleteRenderbuffer(n.__webglDepthbuffer),n.__webglMultisampledFramebuffer&&e.deleteFramebuffer(n.__webglMultisampledFramebuffer),n.__webglColorRenderbuffer)for(let t=0;t<n.__webglColorRenderbuffer.length;t++)n.__webglColorRenderbuffer[t]&&e.deleteRenderbuffer(n.__webglColorRenderbuffer[t]);n.__webglDepthRenderbuffer&&e.deleteRenderbuffer(n.__webglDepthRenderbuffer)}const i=t.textures;for(let t=0,n=i.length;t<n;t++){const n=r.get(i[t]);n.__webglTexture&&(e.deleteTexture(n.__webglTexture),a.memory.textures--),r.remove(i[t])}r.remove(t)}(n)}function M(t){const n=r.get(t);e.deleteTexture(n.__webglTexture);const i=t.source;delete d.get(i)[n.__cacheKey],a.memory.textures--}let w=0;function E(t,i){const s=r.get(t);if(t.isVideoTexture&&function(e){const t=a.render.frame;c.get(e)!==t&&(c.set(e,t),e.update())}(t),!1===t.isRenderTargetTexture&&t.version>0&&s.__version!==t.version){const e=t.image;if(null===e)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else{if(!1!==e.complete)return void D(s,t,i);console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete")}}n.bindTexture(e.TEXTURE_2D,s.__webglTexture,e.TEXTURE0+i)}const A={[q]:e.REPEAT,[$]:e.CLAMP_TO_EDGE,[Y]:e.MIRRORED_REPEAT},R={[K]:e.NEAREST,[Q]:e.NEAREST_MIPMAP_NEAREST,[Z]:e.NEAREST_MIPMAP_LINEAR,[J]:e.LINEAR,[ee]:e.LINEAR_MIPMAP_NEAREST,[te]:e.LINEAR_MIPMAP_LINEAR},C={[lt]:e.NEVER,[mt]:e.ALWAYS,[ut]:e.LESS,[ht]:e.LEQUAL,[ct]:e.EQUAL,[ft]:e.GEQUAL,[dt]:e.GREATER,[pt]:e.NOTEQUAL};function N(n,s){if(s.type!==le||!1!==t.has("OES_texture_float_linear")||s.magFilter!==J&&s.magFilter!==ee&&s.magFilter!==Z&&s.magFilter!==te&&s.minFilter!==J&&s.minFilter!==ee&&s.minFilter!==Z&&s.minFilter!==te||console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),e.texParameteri(n,e.TEXTURE_WRAP_S,A[s.wrapS]),e.texParameteri(n,e.TEXTURE_WRAP_T,A[s.wrapT]),n!==e.TEXTURE_3D&&n!==e.TEXTURE_2D_ARRAY||e.texParameteri(n,e.TEXTURE_WRAP_R,A[s.wrapR]),e.texParameteri(n,e.TEXTURE_MAG_FILTER,R[s.magFilter]),e.texParameteri(n,e.TEXTURE_MIN_FILTER,R[s.minFilter]),s.compareFunction&&(e.texParameteri(n,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE),e.texParameteri(n,e.TEXTURE_COMPARE_FUNC,C[s.compareFunction])),!0===t.has("EXT_texture_filter_anisotropic")){if(s.magFilter===K)return;if(s.minFilter!==Z&&s.minFilter!==te)return;if(s.type===le&&!1===t.has("OES_texture_float_linear"))return;if(s.anisotropy>1||r.get(s).__currentAnisotropy){const a=t.get("EXT_texture_filter_anisotropic");e.texParameterf(n,a.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(s.anisotropy,i.getMaxAnisotropy())),r.get(s).__currentAnisotropy=s.anisotropy}}}function P(t,n){let r=!1;void 0===t.__webglInit&&(t.__webglInit=!0,n.addEventListener("dispose",T));const i=n.source;let s=d.get(i);void 0===s&&(s={},d.set(i,s));const o=function(e){const t=[];return t.push(e.wrapS),t.push(e.wrapT),t.push(e.wrapR||0),t.push(e.magFilter),t.push(e.minFilter),t.push(e.anisotropy),t.push(e.internalFormat),t.push(e.format),t.push(e.type),t.push(e.generateMipmaps),t.push(e.premultiplyAlpha),t.push(e.flipY),t.push(e.unpackAlignment),t.push(e.colorSpace),t.join()}(n);if(o!==t.__cacheKey){void 0===s[o]&&(s[o]={texture:e.createTexture(),usedTimes:0},a.memory.textures++,r=!0),s[o].usedTimes++;const i=s[t.__cacheKey];void 0!==i&&(s[t.__cacheKey].usedTimes--,0===i.usedTimes&&M(n)),t.__cacheKey=o,t.__webglTexture=s[o].texture}return r}function L(e,t,n){return Math.floor(Math.floor(e/n)/t)}function D(t,a,o){let l=e.TEXTURE_2D;(a.isDataArrayTexture||a.isCompressedArrayTexture)&&(l=e.TEXTURE_2D_ARRAY),a.isData3DTexture&&(l=e.TEXTURE_3D);const u=P(t,a),c=a.source;n.bindTexture(l,t.__webglTexture,e.TEXTURE0+o);const h=r.get(c);if(c.version!==h.__version||!0===u){n.activeTexture(e.TEXTURE0+o);const t=$t.getPrimaries($t.workingColorSpace),r=a.colorSpace===nt?null:$t.getPrimaries(a.colorSpace),d=a.colorSpace===nt||t===r?e.NONE:e.BROWSER_DEFAULT_WEBGL;e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,a.flipY),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,a.premultiplyAlpha),e.pixelStorei(e.UNPACK_ALIGNMENT,a.unpackAlignment),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,d);let p=m(a.image,!1,i.maxTextureSize);p=G(a,p);const f=s.convert(a.format,a.colorSpace),v=s.convert(a.type);let T,S=y(a.internalFormat,f,v,a.colorSpace,a.isVideoTexture);N(l,a);const M=a.mipmaps,w=!0!==a.isVideoTexture,E=void 0===h.__version||!0===u,A=c.dataReady,R=b(a,p);if(a.isDepthTexture)S=x(a.format===ve,a.type),E&&(w?n.texStorage2D(e.TEXTURE_2D,1,S,p.width,p.height):n.texImage2D(e.TEXTURE_2D,0,S,p.width,p.height,0,f,v,null));else if(a.isDataTexture)if(M.length>0){w&&E&&n.texStorage2D(e.TEXTURE_2D,R,S,M[0].width,M[0].height);for(let t=0,r=M.length;t<r;t++)T=M[t],w?A&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,T.width,T.height,f,v,T.data):n.texImage2D(e.TEXTURE_2D,t,S,T.width,T.height,0,f,v,T.data);a.generateMipmaps=!1}else w?(E&&n.texStorage2D(e.TEXTURE_2D,R,S,p.width,p.height),A&&function(t,r,i,s){const a=t.updateRanges;if(0===a.length)n.texSubImage2D(e.TEXTURE_2D,0,0,0,r.width,r.height,i,s,r.data);else{a.sort((e,t)=>e.start-t.start);let o=0;for(let e=1;e<a.length;e++){const t=a[o],n=a[e],i=t.start+t.count,s=L(n.start,r.width,4),l=L(t.start,r.width,4);n.start<=i+1&&s===l&&L(n.start+n.count-1,r.width,4)===s?t.count=Math.max(t.count,n.start+n.count-t.start):(++o,a[o]=n)}a.length=o+1;const l=e.getParameter(e.UNPACK_ROW_LENGTH),u=e.getParameter(e.UNPACK_SKIP_PIXELS),c=e.getParameter(e.UNPACK_SKIP_ROWS);e.pixelStorei(e.UNPACK_ROW_LENGTH,r.width);for(let t=0,o=a.length;t<o;t++){const o=a[t],l=Math.floor(o.start/4),u=Math.ceil(o.count/4),c=l%r.width,h=Math.floor(l/r.width),d=u,p=1;e.pixelStorei(e.UNPACK_SKIP_PIXELS,c),e.pixelStorei(e.UNPACK_SKIP_ROWS,h),n.texSubImage2D(e.TEXTURE_2D,0,c,h,d,p,i,s,r.data)}t.clearUpdateRanges(),e.pixelStorei(e.UNPACK_ROW_LENGTH,l),e.pixelStorei(e.UNPACK_SKIP_PIXELS,u),e.pixelStorei(e.UNPACK_SKIP_ROWS,c)}}(a,p,f,v)):n.texImage2D(e.TEXTURE_2D,0,S,p.width,p.height,0,f,v,p.data);else if(a.isCompressedTexture)if(a.isCompressedArrayTexture){w&&E&&n.texStorage3D(e.TEXTURE_2D_ARRAY,R,S,M[0].width,M[0].height,p.depth);for(let t=0,r=M.length;t<r;t++)if(T=M[t],a.format!==ge)if(null!==f)if(w){if(A)if(a.layerUpdates.size>0){const r=ya(T.width,T.height,a.format,a.type);for(const i of a.layerUpdates){const s=T.data.subarray(i*r/T.data.BYTES_PER_ELEMENT,(i+1)*r/T.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,i,T.width,T.height,1,f,s)}a.clearLayerUpdates()}else n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,0,T.width,T.height,p.depth,f,T.data)}else n.compressedTexImage3D(e.TEXTURE_2D_ARRAY,t,S,T.width,T.height,p.depth,0,T.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else w?A&&n.texSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,0,T.width,T.height,p.depth,f,v,T.data):n.texImage3D(e.TEXTURE_2D_ARRAY,t,S,T.width,T.height,p.depth,0,f,v,T.data)}else{w&&E&&n.texStorage2D(e.TEXTURE_2D,R,S,M[0].width,M[0].height);for(let t=0,r=M.length;t<r;t++)T=M[t],a.format!==ge?null!==f?w?A&&n.compressedTexSubImage2D(e.TEXTURE_2D,t,0,0,T.width,T.height,f,T.data):n.compressedTexImage2D(e.TEXTURE_2D,t,S,T.width,T.height,0,T.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):w?A&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,T.width,T.height,f,v,T.data):n.texImage2D(e.TEXTURE_2D,t,S,T.width,T.height,0,f,v,T.data)}else if(a.isDataArrayTexture)if(w){if(E&&n.texStorage3D(e.TEXTURE_2D_ARRAY,R,S,p.width,p.height,p.depth),A)if(a.layerUpdates.size>0){const t=ya(p.width,p.height,a.format,a.type);for(const r of a.layerUpdates){const i=p.data.subarray(r*t/p.data.BYTES_PER_ELEMENT,(r+1)*t/p.data.BYTES_PER_ELEMENT);n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,r,p.width,p.height,1,f,v,i)}a.clearLayerUpdates()}else n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,0,p.width,p.height,p.depth,f,v,p.data)}else n.texImage3D(e.TEXTURE_2D_ARRAY,0,S,p.width,p.height,p.depth,0,f,v,p.data);else if(a.isData3DTexture)w?(E&&n.texStorage3D(e.TEXTURE_3D,R,S,p.width,p.height,p.depth),A&&n.texSubImage3D(e.TEXTURE_3D,0,0,0,0,p.width,p.height,p.depth,f,v,p.data)):n.texImage3D(e.TEXTURE_3D,0,S,p.width,p.height,p.depth,0,f,v,p.data);else if(a.isFramebufferTexture){if(E)if(w)n.texStorage2D(e.TEXTURE_2D,R,S,p.width,p.height);else{let t=p.width,r=p.height;for(let i=0;i<R;i++)n.texImage2D(e.TEXTURE_2D,i,S,t,r,0,f,v,null),t>>=1,r>>=1}}else if(M.length>0){if(w&&E){const t=H(M[0]);n.texStorage2D(e.TEXTURE_2D,R,S,t.width,t.height)}for(let t=0,r=M.length;t<r;t++)T=M[t],w?A&&n.texSubImage2D(e.TEXTURE_2D,t,0,0,f,v,T):n.texImage2D(e.TEXTURE_2D,t,S,f,v,T);a.generateMipmaps=!1}else if(w){if(E){const t=H(p);n.texStorage2D(e.TEXTURE_2D,R,S,t.width,t.height)}A&&n.texSubImage2D(e.TEXTURE_2D,0,0,0,f,v,p)}else n.texImage2D(e.TEXTURE_2D,0,S,f,v,p);g(a)&&_(l),h.__version=c.version,a.onUpdate&&a.onUpdate(a)}t.__version=a.version}function I(t,i,a,l,u,c){const h=s.convert(a.format,a.colorSpace),d=s.convert(a.type),p=y(a.internalFormat,h,d,a.colorSpace),f=r.get(i),m=r.get(a);if(m.__renderTarget=i,!f.__hasExternalTextures){const t=Math.max(1,i.width>>c),r=Math.max(1,i.height>>c);u===e.TEXTURE_3D||u===e.TEXTURE_2D_ARRAY?n.texImage3D(u,c,p,t,r,i.depth,0,h,d,null):n.texImage2D(u,c,p,t,r,0,h,d,null)}n.bindFramebuffer(e.FRAMEBUFFER,t),V(i)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,l,u,m.__webglTexture,0,z(i)):(u===e.TEXTURE_2D||u>=e.TEXTURE_CUBE_MAP_POSITIVE_X&&u<=e.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&e.framebufferTexture2D(e.FRAMEBUFFER,l,u,m.__webglTexture,c),n.bindFramebuffer(e.FRAMEBUFFER,null)}function U(t,n,r){if(e.bindRenderbuffer(e.RENDERBUFFER,t),n.depthBuffer){const i=n.depthTexture,s=i&&i.isDepthTexture?i.type:null,a=x(n.stencilBuffer,s),l=n.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,u=z(n);V(n)?o.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,u,a,n.width,n.height):r?e.renderbufferStorageMultisample(e.RENDERBUFFER,u,a,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,a,n.width,n.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,l,e.RENDERBUFFER,t)}else{const t=n.textures;for(let i=0;i<t.length;i++){const a=t[i],l=s.convert(a.format,a.colorSpace),u=s.convert(a.type),c=y(a.internalFormat,l,u,a.colorSpace),h=z(n);r&&!1===V(n)?e.renderbufferStorageMultisample(e.RENDERBUFFER,h,c,n.width,n.height):V(n)?o.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,h,c,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,c,n.width,n.height)}}e.bindRenderbuffer(e.RENDERBUFFER,null)}function O(t,i){if(i&&i.isWebGLCubeRenderTarget)throw new Error("Depth Texture with cube render targets is not supported");if(n.bindFramebuffer(e.FRAMEBUFFER,t),!i.depthTexture||!i.depthTexture.isDepthTexture)throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");const s=r.get(i.depthTexture);s.__renderTarget=i,s.__webglTexture&&i.depthTexture.image.width===i.width&&i.depthTexture.image.height===i.height||(i.depthTexture.image.width=i.width,i.depthTexture.image.height=i.height,i.depthTexture.needsUpdate=!0),E(i.depthTexture,0);const a=s.__webglTexture,l=z(i);if(i.depthTexture.format===_e)V(i)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.TEXTURE_2D,a,0,l):e.framebufferTexture2D(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.TEXTURE_2D,a,0);else{if(i.depthTexture.format!==ve)throw new Error("Unknown depthTexture format");V(i)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,e.TEXTURE_2D,a,0,l):e.framebufferTexture2D(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,e.TEXTURE_2D,a,0)}}function F(t){const i=r.get(t),s=!0===t.isWebGLCubeRenderTarget;if(i.__boundDepthTexture!==t.depthTexture){const e=t.depthTexture;if(i.__depthDisposeCallback&&i.__depthDisposeCallback(),e){const t=()=>{delete i.__boundDepthTexture,delete i.__depthDisposeCallback,e.removeEventListener("dispose",t)};e.addEventListener("dispose",t),i.__depthDisposeCallback=t}i.__boundDepthTexture=e}if(t.depthTexture&&!i.__autoAllocateDepthBuffer){if(s)throw new Error("target.depthTexture not supported in Cube render targets");const e=t.texture.mipmaps;e&&e.length>0?O(i.__webglFramebuffer[0],t):O(i.__webglFramebuffer,t)}else if(s){i.__webglDepthbuffer=[];for(let r=0;r<6;r++)if(n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer[r]),void 0===i.__webglDepthbuffer[r])i.__webglDepthbuffer[r]=e.createRenderbuffer(),U(i.__webglDepthbuffer[r],t,!1);else{const n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,s=i.__webglDepthbuffer[r];e.bindRenderbuffer(e.RENDERBUFFER,s),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,s)}}else{const r=t.texture.mipmaps;if(r&&r.length>0?n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer[0]):n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer),void 0===i.__webglDepthbuffer)i.__webglDepthbuffer=e.createRenderbuffer(),U(i.__webglDepthbuffer,t,!1);else{const n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,r=i.__webglDepthbuffer;e.bindRenderbuffer(e.RENDERBUFFER,r),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,r)}}n.bindFramebuffer(e.FRAMEBUFFER,null)}const B=[],k=[];function z(e){return Math.min(i.maxSamples,e.samples)}function V(e){const n=r.get(e);return e.samples>0&&!0===t.has("WEBGL_multisampled_render_to_texture")&&!1!==n.__useRenderToTexture}function G(e,t){const n=e.colorSpace,r=e.format,i=e.type;return!0===e.isCompressedTexture||!0===e.isVideoTexture||n!==it&&n!==nt&&($t.getTransfer(n)===at?r===ge&&i===ne||console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",n)),t}function H(e){return"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement?(u.width=e.naturalWidth||e.width,u.height=e.naturalHeight||e.height):"undefined"!=typeof VideoFrame&&e instanceof VideoFrame?(u.width=e.displayWidth,u.height=e.displayHeight):(u.width=e.width,u.height=e.height),u}this.allocateTextureUnit=function(){const e=w;return e>=i.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+e+" texture units while this GPU supports only "+i.maxTextures),w+=1,e},this.resetTextureUnits=function(){w=0},this.setTexture2D=E,this.setTexture2DArray=function(t,i){const s=r.get(t);t.version>0&&s.__version!==t.version?D(s,t,i):n.bindTexture(e.TEXTURE_2D_ARRAY,s.__webglTexture,e.TEXTURE0+i)},this.setTexture3D=function(t,i){const s=r.get(t);t.version>0&&s.__version!==t.version?D(s,t,i):n.bindTexture(e.TEXTURE_3D,s.__webglTexture,e.TEXTURE0+i)},this.setTextureCube=function(t,a){const o=r.get(t);t.version>0&&o.__version!==t.version?function(t,a,o){if(6!==a.image.length)return;const l=P(t,a),u=a.source;n.bindTexture(e.TEXTURE_CUBE_MAP,t.__webglTexture,e.TEXTURE0+o);const c=r.get(u);if(u.version!==c.__version||!0===l){n.activeTexture(e.TEXTURE0+o);const t=$t.getPrimaries($t.workingColorSpace),r=a.colorSpace===nt?null:$t.getPrimaries(a.colorSpace),h=a.colorSpace===nt||t===r?e.NONE:e.BROWSER_DEFAULT_WEBGL;e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,a.flipY),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,a.premultiplyAlpha),e.pixelStorei(e.UNPACK_ALIGNMENT,a.unpackAlignment),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,h);const d=a.isCompressedTexture||a.image[0].isCompressedTexture,p=a.image[0]&&a.image[0].isDataTexture,f=[];for(let e=0;e<6;e++)f[e]=d||p?p?a.image[e].image:a.image[e]:m(a.image[e],!0,i.maxCubemapSize),f[e]=G(a,f[e]);const v=f[0],x=s.convert(a.format,a.colorSpace),T=s.convert(a.type),S=y(a.internalFormat,x,T,a.colorSpace),M=!0!==a.isVideoTexture,w=void 0===c.__version||!0===l,E=u.dataReady;let A,R=b(a,v);if(N(e.TEXTURE_CUBE_MAP,a),d){M&&w&&n.texStorage2D(e.TEXTURE_CUBE_MAP,R,S,v.width,v.height);for(let t=0;t<6;t++){A=f[t].mipmaps;for(let r=0;r<A.length;r++){const i=A[r];a.format!==ge?null!==x?M?E&&n.compressedTexSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,0,0,i.width,i.height,x,i.data):n.compressedTexImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,S,i.width,i.height,0,i.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):M?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,0,0,i.width,i.height,x,T,i.data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r,S,i.width,i.height,0,x,T,i.data)}}}else{if(A=a.mipmaps,M&&w){A.length>0&&R++;const t=H(f[0]);n.texStorage2D(e.TEXTURE_CUBE_MAP,R,S,t.width,t.height)}for(let t=0;t<6;t++)if(p){M?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,f[t].width,f[t].height,x,T,f[t].data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,S,f[t].width,f[t].height,0,x,T,f[t].data);for(let r=0;r<A.length;r++){const i=A[r].image[t].image;M?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,0,0,i.width,i.height,x,T,i.data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,S,i.width,i.height,0,x,T,i.data)}}else{M?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,x,T,f[t]):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,S,x,T,f[t]);for(let r=0;r<A.length;r++){const i=A[r];M?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,0,0,x,T,i.image[t]):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,r+1,S,x,T,i.image[t])}}}g(a)&&_(e.TEXTURE_CUBE_MAP),c.__version=u.version,a.onUpdate&&a.onUpdate(a)}t.__version=a.version}(o,t,a):n.bindTexture(e.TEXTURE_CUBE_MAP,o.__webglTexture,e.TEXTURE0+a)},this.rebindTextures=function(t,n,i){const s=r.get(t);void 0!==n&&I(s.__webglFramebuffer,t,t.texture,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,0),void 0!==i&&F(t)},this.setupRenderTarget=function(t){const i=t.texture,o=r.get(t),l=r.get(i);t.addEventListener("dispose",S);const u=t.textures,c=!0===t.isWebGLCubeRenderTarget,h=u.length>1;if(h||(void 0===l.__webglTexture&&(l.__webglTexture=e.createTexture()),l.__version=i.version,a.memory.textures++),c){o.__webglFramebuffer=[];for(let t=0;t<6;t++)if(i.mipmaps&&i.mipmaps.length>0){o.__webglFramebuffer[t]=[];for(let n=0;n<i.mipmaps.length;n++)o.__webglFramebuffer[t][n]=e.createFramebuffer()}else o.__webglFramebuffer[t]=e.createFramebuffer()}else{if(i.mipmaps&&i.mipmaps.length>0){o.__webglFramebuffer=[];for(let t=0;t<i.mipmaps.length;t++)o.__webglFramebuffer[t]=e.createFramebuffer()}else o.__webglFramebuffer=e.createFramebuffer();if(h)for(let t=0,n=u.length;t<n;t++){const n=r.get(u[t]);void 0===n.__webglTexture&&(n.__webglTexture=e.createTexture(),a.memory.textures++)}if(t.samples>0&&!1===V(t)){o.__webglMultisampledFramebuffer=e.createFramebuffer(),o.__webglColorRenderbuffer=[],n.bindFramebuffer(e.FRAMEBUFFER,o.__webglMultisampledFramebuffer);for(let n=0;n<u.length;n++){const r=u[n];o.__webglColorRenderbuffer[n]=e.createRenderbuffer(),e.bindRenderbuffer(e.RENDERBUFFER,o.__webglColorRenderbuffer[n]);const i=s.convert(r.format,r.colorSpace),a=s.convert(r.type),l=y(r.internalFormat,i,a,r.colorSpace,!0===t.isXRRenderTarget),c=z(t);e.renderbufferStorageMultisample(e.RENDERBUFFER,c,l,t.width,t.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+n,e.RENDERBUFFER,o.__webglColorRenderbuffer[n])}e.bindRenderbuffer(e.RENDERBUFFER,null),t.depthBuffer&&(o.__webglDepthRenderbuffer=e.createRenderbuffer(),U(o.__webglDepthRenderbuffer,t,!0)),n.bindFramebuffer(e.FRAMEBUFFER,null)}}if(c){n.bindTexture(e.TEXTURE_CUBE_MAP,l.__webglTexture),N(e.TEXTURE_CUBE_MAP,i);for(let n=0;n<6;n++)if(i.mipmaps&&i.mipmaps.length>0)for(let r=0;r<i.mipmaps.length;r++)I(o.__webglFramebuffer[n][r],t,i,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+n,r);else I(o.__webglFramebuffer[n],t,i,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+n,0);g(i)&&_(e.TEXTURE_CUBE_MAP),n.unbindTexture()}else if(h){for(let i=0,s=u.length;i<s;i++){const s=u[i],a=r.get(s);n.bindTexture(e.TEXTURE_2D,a.__webglTexture),N(e.TEXTURE_2D,s),I(o.__webglFramebuffer,t,s,e.COLOR_ATTACHMENT0+i,e.TEXTURE_2D,0),g(s)&&_(e.TEXTURE_2D)}n.unbindTexture()}else{let r=e.TEXTURE_2D;if((t.isWebGL3DRenderTarget||t.isWebGLArrayRenderTarget)&&(r=t.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY),n.bindTexture(r,l.__webglTexture),N(r,i),i.mipmaps&&i.mipmaps.length>0)for(let n=0;n<i.mipmaps.length;n++)I(o.__webglFramebuffer[n],t,i,e.COLOR_ATTACHMENT0,r,n);else I(o.__webglFramebuffer,t,i,e.COLOR_ATTACHMENT0,r,0);g(i)&&_(r),n.unbindTexture()}t.depthBuffer&&F(t)},this.updateRenderTargetMipmap=function(e){const t=e.textures;for(let i=0,s=t.length;i<s;i++){const s=t[i];if(g(s)){const t=v(e),i=r.get(s).__webglTexture;n.bindTexture(t,i),_(t),n.unbindTexture()}}},this.updateMultisampleRenderTarget=function(t){if(t.samples>0)if(!1===V(t)){const i=t.textures,s=t.width,a=t.height;let o=e.COLOR_BUFFER_BIT;const u=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,c=r.get(t),h=i.length>1;if(h)for(let t=0;t<i.length;t++)n.bindFramebuffer(e.FRAMEBUFFER,c.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,null),n.bindFramebuffer(e.FRAMEBUFFER,c.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,null,0);n.bindFramebuffer(e.READ_FRAMEBUFFER,c.__webglMultisampledFramebuffer);const d=t.texture.mipmaps;d&&d.length>0?n.bindFramebuffer(e.DRAW_FRAMEBUFFER,c.__webglFramebuffer[0]):n.bindFramebuffer(e.DRAW_FRAMEBUFFER,c.__webglFramebuffer);for(let n=0;n<i.length;n++){if(t.resolveDepthBuffer&&(t.depthBuffer&&(o|=e.DEPTH_BUFFER_BIT),t.stencilBuffer&&t.resolveStencilBuffer&&(o|=e.STENCIL_BUFFER_BIT)),h){e.framebufferRenderbuffer(e.READ_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.RENDERBUFFER,c.__webglColorRenderbuffer[n]);const t=r.get(i[n]).__webglTexture;e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)}e.blitFramebuffer(0,0,s,a,0,0,s,a,o,e.NEAREST),!0===l&&(B.length=0,k.length=0,B.push(e.COLOR_ATTACHMENT0+n),t.depthBuffer&&!1===t.resolveDepthBuffer&&(B.push(u),k.push(u),e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,k)),e.invalidateFramebuffer(e.READ_FRAMEBUFFER,B))}if(n.bindFramebuffer(e.READ_FRAMEBUFFER,null),n.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),h)for(let t=0;t<i.length;t++){n.bindFramebuffer(e.FRAMEBUFFER,c.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.RENDERBUFFER,c.__webglColorRenderbuffer[t]);const s=r.get(i[t]).__webglTexture;n.bindFramebuffer(e.FRAMEBUFFER,c.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+t,e.TEXTURE_2D,s,0)}n.bindFramebuffer(e.DRAW_FRAMEBUFFER,c.__webglMultisampledFramebuffer)}else if(t.depthBuffer&&!1===t.resolveDepthBuffer&&l){const n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,[n])}},this.setupDepthRenderbuffer=F,this.setupFrameBufferTexture=I,this.useMultisampledRTT=V}function Kl(e,t){return{convert:function(n,r=""){let i;const s=$t.getTransfer(r);if(n===ne)return e.UNSIGNED_BYTE;if(n===ce)return e.UNSIGNED_SHORT_4_4_4_4;if(n===he)return e.UNSIGNED_SHORT_5_5_5_1;if(n===pe)return e.UNSIGNED_INT_5_9_9_9_REV;if(n===re)return e.BYTE;if(n===ie)return e.SHORT;if(n===se)return e.UNSIGNED_SHORT;if(n===ae)return e.INT;if(n===oe)return e.UNSIGNED_INT;if(n===le)return e.FLOAT;if(n===ue)return e.HALF_FLOAT;if(n===fe)return e.ALPHA;if(n===me)return e.RGB;if(n===ge)return e.RGBA;if(n===_e)return e.DEPTH_COMPONENT;if(n===ve)return e.DEPTH_STENCIL;if(n===ye)return e.RED;if(n===xe)return e.RED_INTEGER;if(n===be)return e.RG;if(n===Te)return e.RG_INTEGER;if(n===Se)return e.RGBA_INTEGER;if(n===Me||n===we||n===Ee||n===Ae)if(s===at){if(i=t.get("WEBGL_compressed_texture_s3tc_srgb"),null===i)return null;if(n===Me)return i.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===we)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===Ee)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===Ae)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(i=t.get("WEBGL_compressed_texture_s3tc"),null===i)return null;if(n===Me)return i.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===we)return i.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===Ee)return i.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===Ae)return i.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(n===Re||n===Ce||n===Ne||n===Pe){if(i=t.get("WEBGL_compressed_texture_pvrtc"),null===i)return null;if(n===Re)return i.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===Ce)return i.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===Ne)return i.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===Pe)return i.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(n===Le||n===De||n===Ie){if(i=t.get("WEBGL_compressed_texture_etc"),null===i)return null;if(n===Le||n===De)return s===at?i.COMPRESSED_SRGB8_ETC2:i.COMPRESSED_RGB8_ETC2;if(n===Ie)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:i.COMPRESSED_RGBA8_ETC2_EAC}if(n===Ue||n===Oe||n===Fe||n===Be||n===ke||n===ze||n===Ve||n===Ge||n===He||n===je||n===We||n===Xe||n===qe||n===$e){if(i=t.get("WEBGL_compressed_texture_astc"),null===i)return null;if(n===Ue)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:i.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===Oe)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:i.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===Fe)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:i.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===Be)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:i.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===ke)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:i.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===ze)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:i.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===Ve)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:i.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===Ge)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:i.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===He)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:i.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===je)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:i.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===We)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:i.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===Xe)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:i.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===qe)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:i.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===$e)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:i.COMPRESSED_RGBA_ASTC_12x12_KHR}if(n===Ye||n===Ke||n===Qe){if(i=t.get("EXT_texture_compression_bptc"),null===i)return null;if(n===Ye)return s===at?i.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:i.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===Ke)return i.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===Qe)return i.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}if(n===Ze||n===Je||n===et||n===tt){if(i=t.get("EXT_texture_compression_rgtc"),null===i)return null;if(n===Ye)return i.COMPRESSED_RED_RGTC1_EXT;if(n===Je)return i.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===et)return i.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===tt)return i.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}return n===de?e.UNSIGNED_INT_24_8:void 0!==e[n]?e[n]:null}}}class Ql{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t,n){if(null===this.texture){const r=new sn;e.properties.get(r).__webglTexture=t.texture,t.depthNear===n.depthNear&&t.depthFar===n.depthFar||(this.depthNear=t.depthNear,this.depthFar=t.depthFar),this.texture=r}}getMesh(e){if(null!==this.texture&&null===this.mesh){const t=e.cameras[0].viewport,n=new yi({vertexShader:"\nvoid main() {\n\n\tgl_Position = vec4( position, 1.0 );\n\n}",fragmentShader:"\nuniform sampler2DArray depthColor;\nuniform float depthWidth;\nuniform float depthHeight;\n\nvoid main() {\n\n\tvec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );\n\n\tif ( coord.x >= 1.0 ) {\n\n\t\tgl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;\n\n\t} else {\n\n\t\tgl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;\n\n\t}\n\n}",uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new di(new Ss(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class Zl extends bt{constructor(e,t){super();const n=this;let r=null,i=1,s=null,a="local-floor",o=1,l=null,u=null,c=null,h=null,d=null,p=null;const f=new Ql,m=t.getContextAttributes();let g=null,_=null;const v=[],y=[],x=new Dt;let b=null;const T=new Mi;T.viewport=new an;const S=new Mi;S.viewport=new an;const M=[T,S],w=new ua;let E=null,A=null;function R(e){const t=y.indexOf(e.inputSource);if(-1===t)return;const n=v[t];void 0!==n&&(n.update(e.inputSource,e.frame,l||s),n.dispatchEvent({type:e.type,data:e.inputSource}))}function C(){r.removeEventListener("select",R),r.removeEventListener("selectstart",R),r.removeEventListener("selectend",R),r.removeEventListener("squeeze",R),r.removeEventListener("squeezestart",R),r.removeEventListener("squeezeend",R),r.removeEventListener("end",C),r.removeEventListener("inputsourceschange",N);for(let e=0;e<v.length;e++){const t=y[e];null!==t&&(y[e]=null,v[e].disconnect(t))}E=null,A=null,f.reset(),e.setRenderTarget(g),d=null,h=null,c=null,r=null,_=null,U.stop(),n.isPresenting=!1,e.setPixelRatio(b),e.setSize(x.width,x.height,!1),n.dispatchEvent({type:"sessionend"})}function N(e){for(let t=0;t<e.removed.length;t++){const n=e.removed[t],r=y.indexOf(n);r>=0&&(y[r]=null,v[r].disconnect(n))}for(let t=0;t<e.added.length;t++){const n=e.added[t];let r=y.indexOf(n);if(-1===r){for(let e=0;e<v.length;e++){if(e>=y.length){y.push(n),r=e;break}if(null===y[e]){y[e]=n,r=e;break}}if(-1===r)break}const i=v[r];i&&i.connect(n)}}this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(e){let t=v[e];return void 0===t&&(t=new Pi,v[e]=t),t.getTargetRaySpace()},this.getControllerGrip=function(e){let t=v[e];return void 0===t&&(t=new Pi,v[e]=t),t.getGripSpace()},this.getHand=function(e){let t=v[e];return void 0===t&&(t=new Pi,v[e]=t),t.getHandSpace()},this.setFramebufferScaleFactor=function(e){i=e,!0===n.isPresenting&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(e){a=e,!0===n.isPresenting&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return l||s},this.setReferenceSpace=function(e){l=e},this.getBaseLayer=function(){return null!==h?h:d},this.getBinding=function(){return c},this.getFrame=function(){return p},this.getSession=function(){return r},this.setSession=async function(u){if(r=u,null!==r){g=e.getRenderTarget(),r.addEventListener("select",R),r.addEventListener("selectstart",R),r.addEventListener("selectend",R),r.addEventListener("squeeze",R),r.addEventListener("squeezestart",R),r.addEventListener("squeezeend",R),r.addEventListener("end",C),r.addEventListener("inputsourceschange",N),!0!==m.xrCompatible&&await t.makeXRCompatible(),b=e.getPixelRatio(),e.getSize(x);if("undefined"!=typeof XRWebGLBinding&&"createProjectionLayer"in XRWebGLBinding.prototype){let n=null,s=null,a=null;m.depth&&(a=m.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,n=m.stencil?ve:_e,s=m.stencil?de:oe);const o={colorFormat:t.RGBA8,depthFormat:a,scaleFactor:i};c=new XRWebGLBinding(r,t),h=c.createProjectionLayer(o),r.updateRenderState({layers:[h]}),e.setPixelRatio(1),e.setSize(h.textureWidth,h.textureHeight,!1),_=new ln(h.textureWidth,h.textureHeight,{format:ge,type:ne,depthTexture:new os(h.textureWidth,h.textureHeight,s,void 0,void 0,void 0,void 0,void 0,void 0,n),stencilBuffer:m.stencil,colorSpace:e.outputColorSpace,samples:m.antialias?4:0,resolveDepthBuffer:!1===h.ignoreDepthValues,resolveStencilBuffer:!1===h.ignoreDepthValues})}else{const n={antialias:m.antialias,alpha:!0,depth:m.depth,stencil:m.stencil,framebufferScaleFactor:i};d=new XRWebGLLayer(r,t,n),r.updateRenderState({baseLayer:d}),e.setPixelRatio(1),e.setSize(d.framebufferWidth,d.framebufferHeight,!1),_=new ln(d.framebufferWidth,d.framebufferHeight,{format:ge,type:ne,colorSpace:e.outputColorSpace,stencilBuffer:m.stencil,resolveDepthBuffer:!1===d.ignoreDepthValues,resolveStencilBuffer:!1===d.ignoreDepthValues})}_.isXRRenderTarget=!0,this.setFoveation(o),l=null,s=await r.requestReferenceSpace(a),U.setContext(r),U.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(null!==r)return r.environmentBlendMode},this.getDepthTexture=function(){return f.getDepthTexture()};const P=new Ut,L=new Ut;function D(e,t){null===t?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}this.updateCamera=function(e){if(null===r)return;let t=e.near,n=e.far;null!==f.texture&&(f.depthNear>0&&(t=f.depthNear),f.depthFar>0&&(n=f.depthFar)),w.near=S.near=T.near=t,w.far=S.far=T.far=n,E===w.near&&A===w.far||(r.updateRenderState({depthNear:w.near,depthFar:w.far}),E=w.near,A=w.far),T.layers.mask=2|e.layers.mask,S.layers.mask=4|e.layers.mask,w.layers.mask=T.layers.mask|S.layers.mask;const i=e.parent,s=w.cameras;D(w,i);for(let e=0;e<s.length;e++)D(s[e],i);2===s.length?function(e,t,n){P.setFromMatrixPosition(t.matrixWorld),L.setFromMatrixPosition(n.matrixWorld);const r=P.distanceTo(L),i=t.projectionMatrix.elements,s=n.projectionMatrix.elements,a=i[14]/(i[10]-1),o=i[14]/(i[10]+1),l=(i[9]+1)/i[5],u=(i[9]-1)/i[5],c=(i[8]-1)/i[0],h=(s[8]+1)/s[0],d=a*c,p=a*h,f=r/(-c+h),m=f*-c;if(t.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.translateX(m),e.translateZ(f),e.matrixWorld.compose(e.position,e.quaternion,e.scale),e.matrixWorldInverse.copy(e.matrixWorld).invert(),-1===i[10])e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse);else{const t=a+f,n=o+f,i=d-m,s=p+(r-m),c=l*o/n*t,h=u*o/n*t;e.projectionMatrix.makePerspective(i,s,c,h,t,n),e.projectionMatrixInverse.copy(e.projectionMatrix).invert()}}(w,T,S):w.projectionMatrix.copy(T.projectionMatrix),function(e,t,n){null===n?e.matrix.copy(t.matrixWorld):(e.matrix.copy(n.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*wt*Math.atan(1/e.projectionMatrix.elements[5]),e.zoom=1)}(e,w,i)},this.getCamera=function(){return w},this.getFoveation=function(){if(null!==h||null!==d)return o},this.setFoveation=function(e){o=e,null!==h&&(h.fixedFoveation=e),null!==d&&void 0!==d.fixedFoveation&&(d.fixedFoveation=e)},this.hasDepthSensing=function(){return null!==f.texture},this.getDepthSensingMesh=function(){return f.getMesh(w)};let I=null;const U=new xa;U.setAnimationLoop(function(t,i){if(u=i.getViewerPose(l||s),p=i,null!==u){const t=u.views;null!==d&&(e.setRenderTargetFramebuffer(_,d.framebuffer),e.setRenderTarget(_));let n=!1;t.length!==w.cameras.length&&(w.cameras.length=0,n=!0);for(let r=0;r<t.length;r++){const i=t[r];let s=null;if(null!==d)s=d.getViewport(i);else{const t=c.getViewSubImage(h,i);s=t.viewport,0===r&&(e.setRenderTargetTextures(_,t.colorTexture,t.depthStencilTexture),e.setRenderTarget(_))}let a=M[r];void 0===a&&(a=new Mi,a.layers.enable(r),a.viewport=new an,M[r]=a),a.matrix.fromArray(i.transform.matrix),a.matrix.decompose(a.position,a.quaternion,a.scale),a.projectionMatrix.fromArray(i.projectionMatrix),a.projectionMatrixInverse.copy(a.projectionMatrix).invert(),a.viewport.set(s.x,s.y,s.width,s.height),0===r&&(w.matrix.copy(a.matrix),w.matrix.decompose(w.position,w.quaternion,w.scale)),!0===n&&w.cameras.push(a)}const i=r.enabledFeatures;if(i&&i.includes("depth-sensing")&&"gpu-optimized"==r.depthUsage&&c){const n=c.getDepthInformation(t[0]);n&&n.isValid&&n.texture&&f.init(e,n,r.renderState)}}for(let e=0;e<v.length;e++){const t=y[e],n=v[e];null!==t&&void 0!==n&&n.update(t,i,l||s)}I&&I(t,i),i.detectedPlanes&&n.dispatchEvent({type:"planesdetected",data:i}),p=null}),this.setAnimationLoop=function(e){I=e},this.dispose=function(){}}}const Jl=new $n,eu=new Bn;function tu(e,t){function n(e,t){!0===e.matrixAutoUpdate&&e.updateMatrix(),t.value.copy(e.matrix)}function r(e,r){e.opacity.value=r.opacity,r.color&&e.diffuse.value.copy(r.color),r.emissive&&e.emissive.value.copy(r.emissive).multiplyScalar(r.emissiveIntensity),r.map&&(e.map.value=r.map,n(r.map,e.mapTransform)),r.alphaMap&&(e.alphaMap.value=r.alphaMap,n(r.alphaMap,e.alphaMapTransform)),r.bumpMap&&(e.bumpMap.value=r.bumpMap,n(r.bumpMap,e.bumpMapTransform),e.bumpScale.value=r.bumpScale,1===r.side&&(e.bumpScale.value*=-1)),r.normalMap&&(e.normalMap.value=r.normalMap,n(r.normalMap,e.normalMapTransform),e.normalScale.value.copy(r.normalScale),1===r.side&&e.normalScale.value.negate()),r.displacementMap&&(e.displacementMap.value=r.displacementMap,n(r.displacementMap,e.displacementMapTransform),e.displacementScale.value=r.displacementScale,e.displacementBias.value=r.displacementBias),r.emissiveMap&&(e.emissiveMap.value=r.emissiveMap,n(r.emissiveMap,e.emissiveMapTransform)),r.specularMap&&(e.specularMap.value=r.specularMap,n(r.specularMap,e.specularMapTransform)),r.alphaTest>0&&(e.alphaTest.value=r.alphaTest);const i=t.get(r),s=i.envMap,a=i.envMapRotation;s&&(e.envMap.value=s,Jl.copy(a),Jl.x*=-1,Jl.y*=-1,Jl.z*=-1,s.isCubeTexture&&!1===s.isRenderTargetTexture&&(Jl.y*=-1,Jl.z*=-1),e.envMapRotation.value.setFromMatrix4(eu.makeRotationFromEuler(Jl)),e.flipEnvMap.value=s.isCubeTexture&&!1===s.isRenderTargetTexture?-1:1,e.reflectivity.value=r.reflectivity,e.ior.value=r.ior,e.refractionRatio.value=r.refractionRatio),r.lightMap&&(e.lightMap.value=r.lightMap,e.lightMapIntensity.value=r.lightMapIntensity,n(r.lightMap,e.lightMapTransform)),r.aoMap&&(e.aoMap.value=r.aoMap,e.aoMapIntensity.value=r.aoMapIntensity,n(r.aoMap,e.aoMapTransform))}return{refreshFogUniforms:function(t,n){n.color.getRGB(t.fogColor.value,_i(e)),n.isFog?(t.fogNear.value=n.near,t.fogFar.value=n.far):n.isFogExp2&&(t.fogDensity.value=n.density)},refreshMaterialUniforms:function(e,i,s,a,o){i.isMeshBasicMaterial||i.isMeshLambertMaterial?r(e,i):i.isMeshToonMaterial?(r(e,i),function(e,t){t.gradientMap&&(e.gradientMap.value=t.gradientMap)}(e,i)):i.isMeshPhongMaterial?(r(e,i),function(e,t){e.specular.value.copy(t.specular),e.shininess.value=Math.max(t.shininess,1e-4)}(e,i)):i.isMeshStandardMaterial?(r(e,i),function(e,t){e.metalness.value=t.metalness,t.metalnessMap&&(e.metalnessMap.value=t.metalnessMap,n(t.metalnessMap,e.metalnessMapTransform));e.roughness.value=t.roughness,t.roughnessMap&&(e.roughnessMap.value=t.roughnessMap,n(t.roughnessMap,e.roughnessMapTransform));t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)}(e,i),i.isMeshPhysicalMaterial&&function(e,t,r){e.ior.value=t.ior,t.sheen>0&&(e.sheenColor.value.copy(t.sheenColor).multiplyScalar(t.sheen),e.sheenRoughness.value=t.sheenRoughness,t.sheenColorMap&&(e.sheenColorMap.value=t.sheenColorMap,n(t.sheenColorMap,e.sheenColorMapTransform)),t.sheenRoughnessMap&&(e.sheenRoughnessMap.value=t.sheenRoughnessMap,n(t.sheenRoughnessMap,e.sheenRoughnessMapTransform)));t.clearcoat>0&&(e.clearcoat.value=t.clearcoat,e.clearcoatRoughness.value=t.clearcoatRoughness,t.clearcoatMap&&(e.clearcoatMap.value=t.clearcoatMap,n(t.clearcoatMap,e.clearcoatMapTransform)),t.clearcoatRoughnessMap&&(e.clearcoatRoughnessMap.value=t.clearcoatRoughnessMap,n(t.clearcoatRoughnessMap,e.clearcoatRoughnessMapTransform)),t.clearcoatNormalMap&&(e.clearcoatNormalMap.value=t.clearcoatNormalMap,n(t.clearcoatNormalMap,e.clearcoatNormalMapTransform),e.clearcoatNormalScale.value.copy(t.clearcoatNormalScale),1===t.side&&e.clearcoatNormalScale.value.negate()));t.dispersion>0&&(e.dispersion.value=t.dispersion);t.iridescence>0&&(e.iridescence.value=t.iridescence,e.iridescenceIOR.value=t.iridescenceIOR,e.iridescenceThicknessMinimum.value=t.iridescenceThicknessRange[0],e.iridescenceThicknessMaximum.value=t.iridescenceThicknessRange[1],t.iridescenceMap&&(e.iridescenceMap.value=t.iridescenceMap,n(t.iridescenceMap,e.iridescenceMapTransform)),t.iridescenceThicknessMap&&(e.iridescenceThicknessMap.value=t.iridescenceThicknessMap,n(t.iridescenceThicknessMap,e.iridescenceThicknessMapTransform)));t.transmission>0&&(e.transmission.value=t.transmission,e.transmissionSamplerMap.value=r.texture,e.transmissionSamplerSize.value.set(r.width,r.height),t.transmissionMap&&(e.transmissionMap.value=t.transmissionMap,n(t.transmissionMap,e.transmissionMapTransform)),e.thickness.value=t.thickness,t.thicknessMap&&(e.thicknessMap.value=t.thicknessMap,n(t.thicknessMap,e.thicknessMapTransform)),e.attenuationDistance.value=t.attenuationDistance,e.attenuationColor.value.copy(t.attenuationColor));t.anisotropy>0&&(e.anisotropyVector.value.set(t.anisotropy*Math.cos(t.anisotropyRotation),t.anisotropy*Math.sin(t.anisotropyRotation)),t.anisotropyMap&&(e.anisotropyMap.value=t.anisotropyMap,n(t.anisotropyMap,e.anisotropyMapTransform)));e.specularIntensity.value=t.specularIntensity,e.specularColor.value.copy(t.specularColor),t.specularColorMap&&(e.specularColorMap.value=t.specularColorMap,n(t.specularColorMap,e.specularColorMapTransform));t.specularIntensityMap&&(e.specularIntensityMap.value=t.specularIntensityMap,n(t.specularIntensityMap,e.specularIntensityMapTransform))}(e,i,o)):i.isMeshMatcapMaterial?(r(e,i),function(e,t){t.matcap&&(e.matcap.value=t.matcap)}(e,i)):i.isMeshDepthMaterial?r(e,i):i.isMeshDistanceMaterial?(r(e,i),function(e,n){const r=t.get(n).light;e.referencePosition.value.setFromMatrixPosition(r.matrixWorld),e.nearDistance.value=r.shadow.camera.near,e.farDistance.value=r.shadow.camera.far}(e,i)):i.isMeshNormalMaterial?r(e,i):i.isLineBasicMaterial?(function(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform))}(e,i),i.isLineDashedMaterial&&function(e,t){e.dashSize.value=t.dashSize,e.totalSize.value=t.dashSize+t.gapSize,e.scale.value=t.scale}(e,i)):i.isPointsMaterial?function(e,t,r,i){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.size.value=t.size*r,e.scale.value=.5*i,t.map&&(e.map.value=t.map,n(t.map,e.uvTransform));t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform));t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}(e,i,s,a):i.isSpriteMaterial?function(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.rotation.value=t.rotation,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform));t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform));t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}(e,i):i.isShadowMaterial?(e.color.value.copy(i.color),e.opacity.value=i.opacity):i.isShaderMaterial&&(i.uniformsNeedUpdate=!1)}}}function nu(e,t,n,r){let i={},s={},a=[];const o=e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS);function l(e,t,n,r){const i=e.value,s=t+"_"+n;if(void 0===r[s])return r[s]="number"==typeof i||"boolean"==typeof i?i:i.clone(),!0;{const e=r[s];if("number"==typeof i||"boolean"==typeof i){if(e!==i)return r[s]=i,!0}else if(!1===e.equals(i))return e.copy(i),!0}return!1}function u(e){const t={boundary:0,storage:0};return"number"==typeof e||"boolean"==typeof e?(t.boundary=4,t.storage=4):e.isVector2?(t.boundary=8,t.storage=8):e.isVector3||e.isColor?(t.boundary=16,t.storage=12):e.isVector4?(t.boundary=16,t.storage=16):e.isMatrix3?(t.boundary=48,t.storage=48):e.isMatrix4?(t.boundary=64,t.storage=64):e.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",e),t}function c(t){const n=t.target;n.removeEventListener("dispose",c);const r=a.indexOf(n.__bindingPointIndex);a.splice(r,1),e.deleteBuffer(i[n.id]),delete i[n.id],delete s[n.id]}return{bind:function(e,t){const n=t.program;r.uniformBlockBinding(e,n)},update:function(n,h){let d=i[n.id];void 0===d&&(!function(e){const t=e.uniforms;let n=0;const r=16;for(let e=0,i=t.length;e<i;e++){const i=Array.isArray(t[e])?t[e]:[t[e]];for(let e=0,t=i.length;e<t;e++){const t=i[e],s=Array.isArray(t.value)?t.value:[t.value];for(let e=0,i=s.length;e<i;e++){const i=u(s[e]),a=n%r,o=a%i.boundary,l=a+o;n+=o,0!==l&&r-l<i.storage&&(n+=r-l),t.__data=new Float32Array(i.storage/Float32Array.BYTES_PER_ELEMENT),t.__offset=n,n+=i.storage}}}const i=n%r;i>0&&(n+=r-i);e.__size=n,e.__cache={}}(n),d=function(t){const n=function(){for(let e=0;e<o;e++)if(-1===a.indexOf(e))return a.push(e),e;return console.error("THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}();t.__bindingPointIndex=n;const r=e.createBuffer(),i=t.__size,s=t.usage;return e.bindBuffer(e.UNIFORM_BUFFER,r),e.bufferData(e.UNIFORM_BUFFER,i,s),e.bindBuffer(e.UNIFORM_BUFFER,null),e.bindBufferBase(e.UNIFORM_BUFFER,n,r),r}(n),i[n.id]=d,n.addEventListener("dispose",c));const p=h.program;r.updateUBOMapping(n,p);const f=t.render.frame;s[n.id]!==f&&(!function(t){const n=i[t.id],r=t.uniforms,s=t.__cache;e.bindBuffer(e.UNIFORM_BUFFER,n);for(let t=0,n=r.length;t<n;t++){const n=Array.isArray(r[t])?r[t]:[r[t]];for(let r=0,i=n.length;r<i;r++){const i=n[r];if(!0===l(i,t,r,s)){const t=i.__offset,n=Array.isArray(i.value)?i.value:[i.value];let r=0;for(let s=0;s<n.length;s++){const a=n[s],o=u(a);"number"==typeof a||"boolean"==typeof a?(i.__data[0]=a,e.bufferSubData(e.UNIFORM_BUFFER,t+r,i.__data)):a.isMatrix3?(i.__data[0]=a.elements[0],i.__data[1]=a.elements[1],i.__data[2]=a.elements[2],i.__data[3]=0,i.__data[4]=a.elements[3],i.__data[5]=a.elements[4],i.__data[6]=a.elements[5],i.__data[7]=0,i.__data[8]=a.elements[6],i.__data[9]=a.elements[7],i.__data[10]=a.elements[8],i.__data[11]=0):(a.toArray(i.__data,r),r+=o.storage/Float32Array.BYTES_PER_ELEMENT)}e.bufferSubData(e.UNIFORM_BUFFER,t,i.__data)}}}e.bindBuffer(e.UNIFORM_BUFFER,null)}(n),s[n.id]=f)},dispose:function(){for(const t in i)e.deleteBuffer(i[t]);a=[],i={},s={}}}}const ru=new Gi,iu=new Dt,su=new Ut,au=new Dt,ou=new Dt,lu=new Ut,uu=new Ut,cu=new Bn,hu=new Ut,du=new Ut;let pu=null,fu=null;const mu=[],gu=-1,_u=0,vu=1;class yu extends va{constructor(e,t,n=null){super(t,n),this.objects=e,this.recursive=!0,this.transformGroup=!1,this.rotateSpeed=1,this.raycaster=new pa,this.mouseButtons={LEFT:l,MIDDLE:l,RIGHT:a},this.touches={ONE:c},this._onPointerMove=xu.bind(this),this._onPointerDown=bu.bind(this),this._onPointerCancel=Tu.bind(this),this._onContextMenu=Su.bind(this),null!==n&&this.connect(n)}connect(e){super.connect(e),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointerup",this._onPointerCancel),this.domElement.addEventListener("pointerleave",this._onPointerCancel),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointerup",this._onPointerCancel),this.domElement.removeEventListener("pointerleave",this._onPointerCancel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction="auto",this.domElement.style.cursor=""}dispose(){this.disconnect()}_updatePointer(e){const t=this.domElement.getBoundingClientRect();iu.x=(e.clientX-t.left)/t.width*2-1,iu.y=-(e.clientY-t.top)/t.height*2+1}_updateState(e){let t;if("touch"===e.pointerType)t=this.touches.ONE;else switch(e.button){case 0:t=this.mouseButtons.LEFT;break;case 1:t=this.mouseButtons.MIDDLE;break;case 2:t=this.mouseButtons.RIGHT;break;default:t=null}switch(t){case l:case c:this.state=_u;break;case a:case u:this.state=vu;break;default:this.state=gu}}getRaycaster(){return console.warn("THREE.DragControls: getRaycaster() has been deprecated. Use controls.raycaster instead."),this.raycaster}setObjects(e){console.warn("THREE.DragControls: setObjects() has been deprecated. Use controls.objects instead."),this.objects=e}getObjects(){return console.warn("THREE.DragControls: getObjects() has been deprecated. Use controls.objects instead."),this.objects}activate(){console.warn("THREE.DragControls: activate() has been renamed to connect()."),this.connect()}deactivate(){console.warn("THREE.DragControls: deactivate() has been renamed to disconnect()."),this.disconnect()}set mode(e){console.warn("THREE.DragControls: The .mode property has been removed. Define the type of transformation via the .mouseButtons or .touches properties.")}get mode(){console.warn("THREE.DragControls: The .mode property has been removed. Define the type of transformation via the .mouseButtons or .touches properties.")}}function xu(e){const t=this.object,n=this.domElement,r=this.raycaster;if(!1!==this.enabled){if(this._updatePointer(e),r.setFromCamera(iu,t),pu)this.state===_u?r.ray.intersectPlane(ru,lu)&&pu.position.copy(lu.sub(su).applyMatrix4(cu)):this.state===vu&&(au.subVectors(iu,ou).multiplyScalar(this.rotateSpeed),pu.rotateOnWorldAxis(hu,au.x),pu.rotateOnWorldAxis(du.normalize(),-au.y)),this.dispatchEvent({type:"drag",object:pu}),ou.copy(iu);else if("mouse"===e.pointerType||"pen"===e.pointerType)if(mu.length=0,r.setFromCamera(iu,t),r.intersectObjects(this.objects,this.recursive,mu),mu.length>0){const e=mu[0].object;ru.setFromNormalAndCoplanarPoint(t.getWorldDirection(ru.normal),uu.setFromMatrixPosition(e.matrixWorld)),fu!==e&&null!==fu&&(this.dispatchEvent({type:"hoveroff",object:fu}),n.style.cursor="auto",fu=null),fu!==e&&(this.dispatchEvent({type:"hoveron",object:e}),n.style.cursor="pointer",fu=e)}else null!==fu&&(this.dispatchEvent({type:"hoveroff",object:fu}),n.style.cursor="auto",fu=null);ou.copy(iu)}}function bu(e){const t=this.object,n=this.domElement,r=this.raycaster;!1!==this.enabled&&(this._updatePointer(e),this._updateState(e),mu.length=0,r.setFromCamera(iu,t),r.intersectObjects(this.objects,this.recursive,mu),mu.length>0&&(pu=!0===this.transformGroup?Mu(mu[0].object):mu[0].object,ru.setFromNormalAndCoplanarPoint(t.getWorldDirection(ru.normal),uu.setFromMatrixPosition(pu.matrixWorld)),r.ray.intersectPlane(ru,lu)&&(this.state===_u?(cu.copy(pu.parent.matrixWorld).invert(),su.copy(lu).sub(uu.setFromMatrixPosition(pu.matrixWorld))):this.state===vu&&(hu.set(0,1,0).applyQuaternion(t.quaternion).normalize(),du.set(1,0,0).applyQuaternion(t.quaternion).normalize())),n.style.cursor="move",this.dispatchEvent({type:"dragstart",object:pu})),ou.copy(iu))}function Tu(){!1!==this.enabled&&(pu&&(this.dispatchEvent({type:"dragend",object:pu}),pu=null),this.domElement.style.cursor=fu?"pointer":"auto",this.state=gu)}function Su(e){!1!==this.enabled&&e.preventDefault()}function Mu(e,t=null){return e.isGroup&&(t=e),null===e.parent?t:Mu(e.parent,t)}function wu(e,t,n){var r,i=1;function s(){var s,a,o=r.length,l=0,u=0,c=0;for(s=0;s<o;++s)l+=(a=r[s]).x||0,u+=a.y||0,c+=a.z||0;for(l=(l/o-e)*i,u=(u/o-t)*i,c=(c/o-n)*i,s=0;s<o;++s)a=r[s],l&&(a.x-=l),u&&(a.y-=u),c&&(a.z-=c)}return null==e&&(e=0),null==t&&(t=0),null==n&&(n=0),s.initialize=function(e){r=e},s.x=function(t){return arguments.length?(e=+t,s):e},s.y=function(e){return arguments.length?(t=+e,s):t},s.z=function(e){return arguments.length?(n=+e,s):n},s.strength=function(e){return arguments.length?(i=+e,s):i},s}function Eu(e,t,n){if(isNaN(t))return e;var r,i,s,a,o,l,u=e._root,c={data:n},h=e._x0,d=e._x1;if(!u)return e._root=c,e;for(;u.length;)if((a=t>=(i=(h+d)/2))?h=i:d=i,r=u,!(u=u[o=+a]))return r[o]=c,e;if(t===(s=+e._x.call(null,u.data)))return c.next=u,r?r[o]=c:e._root=c,e;do{r=r?r[o]=new Array(2):e._root=new Array(2),(a=t>=(i=(h+d)/2))?h=i:d=i}while((o=+a)===(l=+(s>=i)));return r[l]=u,r[o]=c,e}function Au(e,t,n){this.node=e,this.x0=t,this.x1=n}function Ru(e){return e[0]}function Cu(e,t){var n=new Nu(null==t?Ru:t,NaN,NaN);return null==e?n:n.addAll(e)}function Nu(e,t,n){this._x=e,this._x0=t,this._x1=n,this._root=void 0}function Pu(e){for(var t={data:e.data},n=t;e=e.next;)n=n.next={data:e.data};return t}var Lu=Cu.prototype=Nu.prototype;function Du(e,t,n,r){if(isNaN(t)||isNaN(n))return e;var i,s,a,o,l,u,c,h,d,p=e._root,f={data:r},m=e._x0,g=e._y0,_=e._x1,v=e._y1;if(!p)return e._root=f,e;for(;p.length;)if((u=t>=(s=(m+_)/2))?m=s:_=s,(c=n>=(a=(g+v)/2))?g=a:v=a,i=p,!(p=p[h=c<<1|u]))return i[h]=f,e;if(o=+e._x.call(null,p.data),l=+e._y.call(null,p.data),t===o&&n===l)return f.next=p,i?i[h]=f:e._root=f,e;do{i=i?i[h]=new Array(4):e._root=new Array(4),(u=t>=(s=(m+_)/2))?m=s:_=s,(c=n>=(a=(g+v)/2))?g=a:v=a}while((h=c<<1|u)==(d=(l>=a)<<1|o>=s));return i[d]=p,i[h]=f,e}function Iu(e,t,n,r,i){this.node=e,this.x0=t,this.y0=n,this.x1=r,this.y1=i}function Uu(e){return e[0]}function Ou(e){return e[1]}function Fu(e,t,n){var r=new Bu(null==t?Uu:t,null==n?Ou:n,NaN,NaN,NaN,NaN);return null==e?r:r.addAll(e)}function Bu(e,t,n,r,i,s){this._x=e,this._y=t,this._x0=n,this._y0=r,this._x1=i,this._y1=s,this._root=void 0}function ku(e){for(var t={data:e.data},n=t;e=e.next;)n=n.next={data:e.data};return t}Lu.copy=function(){var e,t,n=new Nu(this._x,this._x0,this._x1),r=this._root;if(!r)return n;if(!r.length)return n._root=Pu(r),n;for(e=[{source:r,target:n._root=new Array(2)}];r=e.pop();)for(var i=0;i<2;++i)(t=r.source[i])&&(t.length?e.push({source:t,target:r.target[i]=new Array(2)}):r.target[i]=Pu(t));return n},Lu.add=function(e){const t=+this._x.call(null,e);return Eu(this.cover(t),t,e)},Lu.addAll=function(e){Array.isArray(e)||(e=Array.from(e));const t=e.length,n=new Float64Array(t);let r=1/0,i=-1/0;for(let s,a=0;a<t;++a)isNaN(s=+this._x.call(null,e[a]))||(n[a]=s,s<r&&(r=s),s>i&&(i=s));if(r>i)return this;this.cover(r).cover(i);for(let r=0;r<t;++r)Eu(this,n[r],e[r]);return this},Lu.cover=function(e){if(isNaN(e=+e))return this;var t=this._x0,n=this._x1;if(isNaN(t))n=(t=Math.floor(e))+1;else{for(var r,i,s=n-t||1,a=this._root;t>e||e>=n;)switch(i=+(e<t),(r=new Array(2))[i]=a,a=r,s*=2,i){case 0:n=t+s;break;case 1:t=n-s}this._root&&this._root.length&&(this._root=a)}return this._x0=t,this._x1=n,this},Lu.data=function(){var e=[];return this.visit(function(t){if(!t.length)do{e.push(t.data)}while(t=t.next)}),e},Lu.extent=function(e){return arguments.length?this.cover(+e[0][0]).cover(+e[1][0]):isNaN(this._x0)?void 0:[[this._x0],[this._x1]]},Lu.find=function(e,t){var n,r,i,s,a,o=this._x0,l=this._x1,u=[],c=this._root;for(c&&u.push(new Au(c,o,l)),null==t?t=1/0:(o=e-t,l=e+t);s=u.pop();)if(!(!(c=s.node)||(r=s.x0)>l||(i=s.x1)<o))if(c.length){var h=(r+i)/2;u.push(new Au(c[1],h,i),new Au(c[0],r,h)),(a=+(e>=h))&&(s=u[u.length-1],u[u.length-1]=u[u.length-1-a],u[u.length-1-a]=s)}else{var d=Math.abs(e-+this._x.call(null,c.data));d<t&&(t=d,o=e-d,l=e+d,n=c.data)}return n},Lu.remove=function(e){if(isNaN(s=+this._x.call(null,e)))return this;var t,n,r,i,s,a,o,l,u,c=this._root,h=this._x0,d=this._x1;if(!c)return this;if(c.length)for(;;){if((o=s>=(a=(h+d)/2))?h=a:d=a,t=c,!(c=c[l=+o]))return this;if(!c.length)break;t[l+1&1]&&(n=t,u=l)}for(;c.data!==e;)if(r=c,!(c=c.next))return this;return(i=c.next)&&delete c.next,r?(i?r.next=i:delete r.next,this):t?(i?t[l]=i:delete t[l],(c=t[0]||t[1])&&c===(t[1]||t[0])&&!c.length&&(n?n[u]=c:this._root=c),this):(this._root=i,this)},Lu.removeAll=function(e){for(var t=0,n=e.length;t<n;++t)this.remove(e[t]);return this},Lu.root=function(){return this._root},Lu.size=function(){var e=0;return this.visit(function(t){if(!t.length)do{++e}while(t=t.next)}),e},Lu.visit=function(e){var t,n,r,i,s=[],a=this._root;for(a&&s.push(new Au(a,this._x0,this._x1));t=s.pop();)if(!e(a=t.node,r=t.x0,i=t.x1)&&a.length){var o=(r+i)/2;(n=a[1])&&s.push(new Au(n,o,i)),(n=a[0])&&s.push(new Au(n,r,o))}return this},Lu.visitAfter=function(e){var t,n=[],r=[];for(this._root&&n.push(new Au(this._root,this._x0,this._x1));t=n.pop();){var i=t.node;if(i.length){var s,a=t.x0,o=t.x1,l=(a+o)/2;(s=i[0])&&n.push(new Au(s,a,l)),(s=i[1])&&n.push(new Au(s,l,o))}r.push(t)}for(;t=r.pop();)e(t.node,t.x0,t.x1);return this},Lu.x=function(e){return arguments.length?(this._x=e,this):this._x};var zu=Fu.prototype=Bu.prototype;function Vu(e,t,n,r,i){if(isNaN(t)||isNaN(n)||isNaN(r))return e;var s,a,o,l,u,c,h,d,p,f,m,g,_=e._root,v={data:i},y=e._x0,x=e._y0,b=e._z0,T=e._x1,S=e._y1,M=e._z1;if(!_)return e._root=v,e;for(;_.length;)if((d=t>=(a=(y+T)/2))?y=a:T=a,(p=n>=(o=(x+S)/2))?x=o:S=o,(f=r>=(l=(b+M)/2))?b=l:M=l,s=_,!(_=_[m=f<<2|p<<1|d]))return s[m]=v,e;if(u=+e._x.call(null,_.data),c=+e._y.call(null,_.data),h=+e._z.call(null,_.data),t===u&&n===c&&r===h)return v.next=_,s?s[m]=v:e._root=v,e;do{s=s?s[m]=new Array(8):e._root=new Array(8),(d=t>=(a=(y+T)/2))?y=a:T=a,(p=n>=(o=(x+S)/2))?x=o:S=o,(f=r>=(l=(b+M)/2))?b=l:M=l}while((m=f<<2|p<<1|d)==(g=(h>=l)<<2|(c>=o)<<1|u>=a));return s[g]=_,s[m]=v,e}function Gu(e,t,n,r,i,s,a){this.node=e,this.x0=t,this.y0=n,this.z0=r,this.x1=i,this.y1=s,this.z1=a}zu.copy=function(){var e,t,n=new Bu(this._x,this._y,this._x0,this._y0,this._x1,this._y1),r=this._root;if(!r)return n;if(!r.length)return n._root=ku(r),n;for(e=[{source:r,target:n._root=new Array(4)}];r=e.pop();)for(var i=0;i<4;++i)(t=r.source[i])&&(t.length?e.push({source:t,target:r.target[i]=new Array(4)}):r.target[i]=ku(t));return n},zu.add=function(e){const t=+this._x.call(null,e),n=+this._y.call(null,e);return Du(this.cover(t,n),t,n,e)},zu.addAll=function(e){var t,n,r,i,s=e.length,a=new Array(s),o=new Array(s),l=1/0,u=1/0,c=-1/0,h=-1/0;for(n=0;n<s;++n)isNaN(r=+this._x.call(null,t=e[n]))||isNaN(i=+this._y.call(null,t))||(a[n]=r,o[n]=i,r<l&&(l=r),r>c&&(c=r),i<u&&(u=i),i>h&&(h=i));if(l>c||u>h)return this;for(this.cover(l,u).cover(c,h),n=0;n<s;++n)Du(this,a[n],o[n],e[n]);return this},zu.cover=function(e,t){if(isNaN(e=+e)||isNaN(t=+t))return this;var n=this._x0,r=this._y0,i=this._x1,s=this._y1;if(isNaN(n))i=(n=Math.floor(e))+1,s=(r=Math.floor(t))+1;else{for(var a,o,l=i-n||1,u=this._root;n>e||e>=i||r>t||t>=s;)switch(o=(t<r)<<1|e<n,(a=new Array(4))[o]=u,u=a,l*=2,o){case 0:i=n+l,s=r+l;break;case 1:n=i-l,s=r+l;break;case 2:i=n+l,r=s-l;break;case 3:n=i-l,r=s-l}this._root&&this._root.length&&(this._root=u)}return this._x0=n,this._y0=r,this._x1=i,this._y1=s,this},zu.data=function(){var e=[];return this.visit(function(t){if(!t.length)do{e.push(t.data)}while(t=t.next)}),e},zu.extent=function(e){return arguments.length?this.cover(+e[0][0],+e[0][1]).cover(+e[1][0],+e[1][1]):isNaN(this._x0)?void 0:[[this._x0,this._y0],[this._x1,this._y1]]},zu.find=function(e,t,n){var r,i,s,a,o,l,u,c=this._x0,h=this._y0,d=this._x1,p=this._y1,f=[],m=this._root;for(m&&f.push(new Iu(m,c,h,d,p)),null==n?n=1/0:(c=e-n,h=t-n,d=e+n,p=t+n,n*=n);l=f.pop();)if(!(!(m=l.node)||(i=l.x0)>d||(s=l.y0)>p||(a=l.x1)<c||(o=l.y1)<h))if(m.length){var g=(i+a)/2,_=(s+o)/2;f.push(new Iu(m[3],g,_,a,o),new Iu(m[2],i,_,g,o),new Iu(m[1],g,s,a,_),new Iu(m[0],i,s,g,_)),(u=(t>=_)<<1|e>=g)&&(l=f[f.length-1],f[f.length-1]=f[f.length-1-u],f[f.length-1-u]=l)}else{var v=e-+this._x.call(null,m.data),y=t-+this._y.call(null,m.data),x=v*v+y*y;if(x<n){var b=Math.sqrt(n=x);c=e-b,h=t-b,d=e+b,p=t+b,r=m.data}}return r},zu.remove=function(e){if(isNaN(s=+this._x.call(null,e))||isNaN(a=+this._y.call(null,e)))return this;var t,n,r,i,s,a,o,l,u,c,h,d,p=this._root,f=this._x0,m=this._y0,g=this._x1,_=this._y1;if(!p)return this;if(p.length)for(;;){if((u=s>=(o=(f+g)/2))?f=o:g=o,(c=a>=(l=(m+_)/2))?m=l:_=l,t=p,!(p=p[h=c<<1|u]))return this;if(!p.length)break;(t[h+1&3]||t[h+2&3]||t[h+3&3])&&(n=t,d=h)}for(;p.data!==e;)if(r=p,!(p=p.next))return this;return(i=p.next)&&delete p.next,r?(i?r.next=i:delete r.next,this):t?(i?t[h]=i:delete t[h],(p=t[0]||t[1]||t[2]||t[3])&&p===(t[3]||t[2]||t[1]||t[0])&&!p.length&&(n?n[d]=p:this._root=p),this):(this._root=i,this)},zu.removeAll=function(e){for(var t=0,n=e.length;t<n;++t)this.remove(e[t]);return this},zu.root=function(){return this._root},zu.size=function(){var e=0;return this.visit(function(t){if(!t.length)do{++e}while(t=t.next)}),e},zu.visit=function(e){var t,n,r,i,s,a,o=[],l=this._root;for(l&&o.push(new Iu(l,this._x0,this._y0,this._x1,this._y1));t=o.pop();)if(!e(l=t.node,r=t.x0,i=t.y0,s=t.x1,a=t.y1)&&l.length){var u=(r+s)/2,c=(i+a)/2;(n=l[3])&&o.push(new Iu(n,u,c,s,a)),(n=l[2])&&o.push(new Iu(n,r,c,u,a)),(n=l[1])&&o.push(new Iu(n,u,i,s,c)),(n=l[0])&&o.push(new Iu(n,r,i,u,c))}return this},zu.visitAfter=function(e){var t,n=[],r=[];for(this._root&&n.push(new Iu(this._root,this._x0,this._y0,this._x1,this._y1));t=n.pop();){var i=t.node;if(i.length){var s,a=t.x0,o=t.y0,l=t.x1,u=t.y1,c=(a+l)/2,h=(o+u)/2;(s=i[0])&&n.push(new Iu(s,a,o,c,h)),(s=i[1])&&n.push(new Iu(s,c,o,l,h)),(s=i[2])&&n.push(new Iu(s,a,h,c,u)),(s=i[3])&&n.push(new Iu(s,c,h,l,u))}r.push(t)}for(;t=r.pop();)e(t.node,t.x0,t.y0,t.x1,t.y1);return this},zu.x=function(e){return arguments.length?(this._x=e,this):this._x},zu.y=function(e){return arguments.length?(this._y=e,this):this._y};const Hu=(e,t,n,r,i,s)=>Math.sqrt((e-r)**2+(t-i)**2+(n-s)**2);function ju(e){return e[0]}function Wu(e){return e[1]}function Xu(e){return e[2]}function qu(e,t,n,r){var i=new $u(null==t?ju:t,null==n?Wu:n,null==r?Xu:r,NaN,NaN,NaN,NaN,NaN,NaN);return null==e?i:i.addAll(e)}function $u(e,t,n,r,i,s,a,o,l){this._x=e,this._y=t,this._z=n,this._x0=r,this._y0=i,this._z0=s,this._x1=a,this._y1=o,this._z1=l,this._root=void 0}function Yu(e){for(var t={data:e.data},n=t;e=e.next;)n=n.next={data:e.data};return t}var Ku=qu.prototype=$u.prototype;function Qu(e){return function(){return e}}function Zu(e){return 1e-6*(e()-.5)}function Ju(e){return e.index}function ec(e,t){var n=e.get(t);if(!n)throw new Error("node not found: "+t);return n}function tc(e){var t,n,r,i,s,a,o,l=Ju,u=function(e){return 1/Math.min(s[e.source.index],s[e.target.index])},c=Qu(30),h=1;function d(r){for(var s=0,l=e.length;s<h;++s)for(var u,c,d,p,f,m=0,g=0,_=0,v=0;m<l;++m)c=(u=e[m]).source,g=(d=u.target).x+d.vx-c.x-c.vx||Zu(o),i>1&&(_=d.y+d.vy-c.y-c.vy||Zu(o)),i>2&&(v=d.z+d.vz-c.z-c.vz||Zu(o)),g*=p=((p=Math.sqrt(g*g+_*_+v*v))-n[m])/p*r*t[m],_*=p,v*=p,d.vx-=g*(f=a[m]),i>1&&(d.vy-=_*f),i>2&&(d.vz-=v*f),c.vx+=g*(f=1-f),i>1&&(c.vy+=_*f),i>2&&(c.vz+=v*f)}function p(){if(r){var i,o,u=r.length,c=e.length,h=new Map(r.map((e,t)=>[l(e,t,r),e]));for(i=0,s=new Array(u);i<c;++i)(o=e[i]).index=i,"object"!=typeof o.source&&(o.source=ec(h,o.source)),"object"!=typeof o.target&&(o.target=ec(h,o.target)),s[o.source.index]=(s[o.source.index]||0)+1,s[o.target.index]=(s[o.target.index]||0)+1;for(i=0,a=new Array(c);i<c;++i)o=e[i],a[i]=s[o.source.index]/(s[o.source.index]+s[o.target.index]);t=new Array(c),f(),n=new Array(c),m()}}function f(){if(r)for(var n=0,i=e.length;n<i;++n)t[n]=+u(e[n],n,e)}function m(){if(r)for(var t=0,i=e.length;t<i;++t)n[t]=+c(e[t],t,e)}return null==e&&(e=[]),d.initialize=function(e,...t){r=e,o=t.find(e=>"function"==typeof e)||Math.random,i=t.find(e=>[1,2,3].includes(e))||2,p()},d.links=function(t){return arguments.length?(e=t,p(),d):e},d.id=function(e){return arguments.length?(l=e,d):l},d.iterations=function(e){return arguments.length?(h=+e,d):h},d.strength=function(e){return arguments.length?(u="function"==typeof e?e:Qu(+e),f(),d):u},d.distance=function(e){return arguments.length?(c="function"==typeof e?e:Qu(+e),m(),d):c},d}Ku.copy=function(){var e,t,n=new $u(this._x,this._y,this._z,this._x0,this._y0,this._z0,this._x1,this._y1,this._z1),r=this._root;if(!r)return n;if(!r.length)return n._root=Yu(r),n;for(e=[{source:r,target:n._root=new Array(8)}];r=e.pop();)for(var i=0;i<8;++i)(t=r.source[i])&&(t.length?e.push({source:t,target:r.target[i]=new Array(8)}):r.target[i]=Yu(t));return n},Ku.add=function(e){const t=+this._x.call(null,e),n=+this._y.call(null,e),r=+this._z.call(null,e);return Vu(this.cover(t,n,r),t,n,r,e)},Ku.addAll=function(e){Array.isArray(e)||(e=Array.from(e));const t=e.length,n=new Float64Array(t),r=new Float64Array(t),i=new Float64Array(t);let s=1/0,a=1/0,o=1/0,l=-1/0,u=-1/0,c=-1/0;for(let h,d,p,f,m=0;m<t;++m)isNaN(d=+this._x.call(null,h=e[m]))||isNaN(p=+this._y.call(null,h))||isNaN(f=+this._z.call(null,h))||(n[m]=d,r[m]=p,i[m]=f,d<s&&(s=d),d>l&&(l=d),p<a&&(a=p),p>u&&(u=p),f<o&&(o=f),f>c&&(c=f));if(s>l||a>u||o>c)return this;this.cover(s,a,o).cover(l,u,c);for(let s=0;s<t;++s)Vu(this,n[s],r[s],i[s],e[s]);return this},Ku.cover=function(e,t,n){if(isNaN(e=+e)||isNaN(t=+t)||isNaN(n=+n))return this;var r=this._x0,i=this._y0,s=this._z0,a=this._x1,o=this._y1,l=this._z1;if(isNaN(r))a=(r=Math.floor(e))+1,o=(i=Math.floor(t))+1,l=(s=Math.floor(n))+1;else{for(var u,c,h=a-r||1,d=this._root;r>e||e>=a||i>t||t>=o||s>n||n>=l;)switch(c=(n<s)<<2|(t<i)<<1|e<r,(u=new Array(8))[c]=d,d=u,h*=2,c){case 0:a=r+h,o=i+h,l=s+h;break;case 1:r=a-h,o=i+h,l=s+h;break;case 2:a=r+h,i=o-h,l=s+h;break;case 3:r=a-h,i=o-h,l=s+h;break;case 4:a=r+h,o=i+h,s=l-h;break;case 5:r=a-h,o=i+h,s=l-h;break;case 6:a=r+h,i=o-h,s=l-h;break;case 7:r=a-h,i=o-h,s=l-h}this._root&&this._root.length&&(this._root=d)}return this._x0=r,this._y0=i,this._z0=s,this._x1=a,this._y1=o,this._z1=l,this},Ku.data=function(){var e=[];return this.visit(function(t){if(!t.length)do{e.push(t.data)}while(t=t.next)}),e},Ku.extent=function(e){return arguments.length?this.cover(+e[0][0],+e[0][1],+e[0][2]).cover(+e[1][0],+e[1][1],+e[1][2]):isNaN(this._x0)?void 0:[[this._x0,this._y0,this._z0],[this._x1,this._y1,this._z1]]},Ku.find=function(e,t,n,r){var i,s,a,o,l,u,c,h,d,p=this._x0,f=this._y0,m=this._z0,g=this._x1,_=this._y1,v=this._z1,y=[],x=this._root;for(x&&y.push(new Gu(x,p,f,m,g,_,v)),null==r?r=1/0:(p=e-r,f=t-r,m=n-r,g=e+r,_=t+r,v=n+r,r*=r);h=y.pop();)if(!(!(x=h.node)||(s=h.x0)>g||(a=h.y0)>_||(o=h.z0)>v||(l=h.x1)<p||(u=h.y1)<f||(c=h.z1)<m))if(x.length){var b=(s+l)/2,T=(a+u)/2,S=(o+c)/2;y.push(new Gu(x[7],b,T,S,l,u,c),new Gu(x[6],s,T,S,b,u,c),new Gu(x[5],b,a,S,l,T,c),new Gu(x[4],s,a,S,b,T,c),new Gu(x[3],b,T,o,l,u,S),new Gu(x[2],s,T,o,b,u,S),new Gu(x[1],b,a,o,l,T,S),new Gu(x[0],s,a,o,b,T,S)),(d=(n>=S)<<2|(t>=T)<<1|e>=b)&&(h=y[y.length-1],y[y.length-1]=y[y.length-1-d],y[y.length-1-d]=h)}else{var M=e-+this._x.call(null,x.data),w=t-+this._y.call(null,x.data),E=n-+this._z.call(null,x.data),A=M*M+w*w+E*E;if(A<r){var R=Math.sqrt(r=A);p=e-R,f=t-R,m=n-R,g=e+R,_=t+R,v=n+R,i=x.data}}return i},Ku.findAllWithinRadius=function(e,t,n,r){const i=[],s=e-r,a=t-r,o=n-r,l=e+r,u=t+r,c=n+r;return this.visit((h,d,p,f,m,g,_)=>{if(!h.length)do{const s=h.data;Hu(e,t,n,this._x(s),this._y(s),this._z(s))<=r&&i.push(s)}while(h=h.next);return d>l||p>u||f>c||m<s||g<a||_<o}),i},Ku.remove=function(e){if(isNaN(s=+this._x.call(null,e))||isNaN(a=+this._y.call(null,e))||isNaN(o=+this._z.call(null,e)))return this;var t,n,r,i,s,a,o,l,u,c,h,d,p,f,m,g=this._root,_=this._x0,v=this._y0,y=this._z0,x=this._x1,b=this._y1,T=this._z1;if(!g)return this;if(g.length)for(;;){if((h=s>=(l=(_+x)/2))?_=l:x=l,(d=a>=(u=(v+b)/2))?v=u:b=u,(p=o>=(c=(y+T)/2))?y=c:T=c,t=g,!(g=g[f=p<<2|d<<1|h]))return this;if(!g.length)break;(t[f+1&7]||t[f+2&7]||t[f+3&7]||t[f+4&7]||t[f+5&7]||t[f+6&7]||t[f+7&7])&&(n=t,m=f)}for(;g.data!==e;)if(r=g,!(g=g.next))return this;return(i=g.next)&&delete g.next,r?(i?r.next=i:delete r.next,this):t?(i?t[f]=i:delete t[f],(g=t[0]||t[1]||t[2]||t[3]||t[4]||t[5]||t[6]||t[7])&&g===(t[7]||t[6]||t[5]||t[4]||t[3]||t[2]||t[1]||t[0])&&!g.length&&(n?n[m]=g:this._root=g),this):(this._root=i,this)},Ku.removeAll=function(e){for(var t=0,n=e.length;t<n;++t)this.remove(e[t]);return this},Ku.root=function(){return this._root},Ku.size=function(){var e=0;return this.visit(function(t){if(!t.length)do{++e}while(t=t.next)}),e},Ku.visit=function(e){var t,n,r,i,s,a,o,l,u=[],c=this._root;for(c&&u.push(new Gu(c,this._x0,this._y0,this._z0,this._x1,this._y1,this._z1));t=u.pop();)if(!e(c=t.node,r=t.x0,i=t.y0,s=t.z0,a=t.x1,o=t.y1,l=t.z1)&&c.length){var h=(r+a)/2,d=(i+o)/2,p=(s+l)/2;(n=c[7])&&u.push(new Gu(n,h,d,p,a,o,l)),(n=c[6])&&u.push(new Gu(n,r,d,p,h,o,l)),(n=c[5])&&u.push(new Gu(n,h,i,p,a,d,l)),(n=c[4])&&u.push(new Gu(n,r,i,p,h,d,l)),(n=c[3])&&u.push(new Gu(n,h,d,s,a,o,p)),(n=c[2])&&u.push(new Gu(n,r,d,s,h,o,p)),(n=c[1])&&u.push(new Gu(n,h,i,s,a,d,p)),(n=c[0])&&u.push(new Gu(n,r,i,s,h,d,p))}return this},Ku.visitAfter=function(e){var t,n=[],r=[];for(this._root&&n.push(new Gu(this._root,this._x0,this._y0,this._z0,this._x1,this._y1,this._z1));t=n.pop();){var i=t.node;if(i.length){var s,a=t.x0,o=t.y0,l=t.z0,u=t.x1,c=t.y1,h=t.z1,d=(a+u)/2,p=(o+c)/2,f=(l+h)/2;(s=i[0])&&n.push(new Gu(s,a,o,l,d,p,f)),(s=i[1])&&n.push(new Gu(s,d,o,l,u,p,f)),(s=i[2])&&n.push(new Gu(s,a,p,l,d,c,f)),(s=i[3])&&n.push(new Gu(s,d,p,l,u,c,f)),(s=i[4])&&n.push(new Gu(s,a,o,f,d,p,h)),(s=i[5])&&n.push(new Gu(s,d,o,f,u,p,h)),(s=i[6])&&n.push(new Gu(s,a,p,f,d,c,h)),(s=i[7])&&n.push(new Gu(s,d,p,f,u,c,h))}r.push(t)}for(;t=r.pop();)e(t.node,t.x0,t.y0,t.z0,t.x1,t.y1,t.z1);return this},Ku.x=function(e){return arguments.length?(this._x=e,this):this._x},Ku.y=function(e){return arguments.length?(this._y=e,this):this._y},Ku.z=function(e){return arguments.length?(this._z=e,this):this._z};var nc={value:()=>{}};function rc(){for(var e,t=0,n=arguments.length,r={};t<n;++t){if(!(e=arguments[t]+"")||e in r||/[\s.]/.test(e))throw new Error("illegal type: "+e);r[e]=[]}return new ic(r)}function ic(e){this._=e}function sc(e,t){for(var n,r=0,i=e.length;r<i;++r)if((n=e[r]).name===t)return n.value}function ac(e,t,n){for(var r=0,i=e.length;r<i;++r)if(e[r].name===t){e[r]=nc,e=e.slice(0,r).concat(e.slice(r+1));break}return null!=n&&e.push({name:t,value:n}),e}ic.prototype=rc.prototype={constructor:ic,on:function(e,t){var n,r,i=this._,s=(r=i,(e+"").trim().split(/^|\s+/).map(function(e){var t="",n=e.indexOf(".");if(n>=0&&(t=e.slice(n+1),e=e.slice(0,n)),e&&!r.hasOwnProperty(e))throw new Error("unknown type: "+e);return{type:e,name:t}})),a=-1,o=s.length;if(!(arguments.length<2)){if(null!=t&&"function"!=typeof t)throw new Error("invalid callback: "+t);for(;++a<o;)if(n=(e=s[a]).type)i[n]=ac(i[n],e.name,t);else if(null==t)for(n in i)i[n]=ac(i[n],e.name,null);return this}for(;++a<o;)if((n=(e=s[a]).type)&&(n=sc(i[n],e.name)))return n},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new ic(e)},call:function(e,t){if((n=arguments.length-2)>0)for(var n,r,i=new Array(n),s=0;s<n;++s)i[s]=arguments[s+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(s=0,n=(r=this._[e]).length;s<n;++s)r[s].value.apply(t,i)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var r=this._[e],i=0,s=r.length;i<s;++i)r[i].value.apply(t,n)}};var oc,lc,uc=0,cc=0,hc=0,dc=0,pc=0,fc=0,mc="object"==typeof performance&&performance.now?performance:Date,gc="object"==typeof window&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function _c(){return pc||(gc(vc),pc=mc.now()+fc)}function vc(){pc=0}function yc(){this._call=this._time=this._next=null}function xc(e,t,n){var r=new yc;return r.restart(e,t,n),r}function bc(){pc=(dc=mc.now())+fc,uc=cc=0;try{!function(){_c(),++uc;for(var e,t=oc;t;)(e=pc-t._time)>=0&&t._call.call(void 0,e),t=t._next;--uc}()}finally{uc=0,function(){var e,t,n=oc,r=1/0;for(;n;)n._call?(r>n._time&&(r=n._time),e=n,n=n._next):(t=n._next,n._next=null,n=e?e._next=t:oc=t);lc=e,Sc(r)}(),pc=0}}function Tc(){var e=mc.now(),t=e-dc;t>1e3&&(fc-=t,dc=e)}function Sc(e){uc||(cc&&(cc=clearTimeout(cc)),e-pc>24?(e<1/0&&(cc=setTimeout(bc,e-mc.now()-fc)),hc&&(hc=clearInterval(hc))):(hc||(dc=mc.now(),hc=setInterval(Tc,1e3)),uc=1,gc(bc)))}yc.prototype=xc.prototype={constructor:yc,restart:function(e,t,n){if("function"!=typeof e)throw new TypeError("callback is not a function");n=(null==n?_c():+n)+(null==t?0:+t),this._next||lc===this||(lc?lc._next=this:oc=this,lc=this),this._call=e,this._time=n,Sc()},stop:function(){this._call&&(this._call=null,this._time=1/0,Sc())}};const Mc=4294967296;function wc(e){return e.x}function Ec(e){return e.y}function Ac(e){return e.z}var Rc,Cc,Nc,Pc,Lc=Math.PI*(3-Math.sqrt(5)),Dc=20*Math.PI/(9+Math.sqrt(221));function Ic(e,t){t=t||2;var n,r=Math.min(3,Math.max(1,Math.round(t))),i=1,s=.001,a=1-Math.pow(s,1/300),o=0,l=.6,u=new Map,c=xc(p),h=rc("tick","end"),d=function(){let e=1;return()=>(e=(1664525*e+1013904223)%Mc)/Mc}();function p(){f(),h.call("tick",n),i<s&&(c.stop(),h.call("end",n))}function f(t){var s,c,h=e.length;void 0===t&&(t=1);for(var d=0;d<t;++d)for(i+=(o-i)*a,u.forEach(function(e){e(i)}),s=0;s<h;++s)null==(c=e[s]).fx?c.x+=c.vx*=l:(c.x=c.fx,c.vx=0),r>1&&(null==c.fy?c.y+=c.vy*=l:(c.y=c.fy,c.vy=0)),r>2&&(null==c.fz?c.z+=c.vz*=l:(c.z=c.fz,c.vz=0));return n}function m(){for(var t,n=0,i=e.length;n<i;++n){if((t=e[n]).index=n,null!=t.fx&&(t.x=t.fx),null!=t.fy&&(t.y=t.fy),null!=t.fz&&(t.z=t.fz),isNaN(t.x)||r>1&&isNaN(t.y)||r>2&&isNaN(t.z)){var s=10*(r>2?Math.cbrt(.5+n):r>1?Math.sqrt(.5+n):n),a=n*Lc,o=n*Dc;1===r?t.x=s:2===r?(t.x=s*Math.cos(a),t.y=s*Math.sin(a)):(t.x=s*Math.sin(a)*Math.cos(o),t.y=s*Math.cos(a),t.z=s*Math.sin(a)*Math.sin(o))}(isNaN(t.vx)||r>1&&isNaN(t.vy)||r>2&&isNaN(t.vz))&&(t.vx=0,r>1&&(t.vy=0),r>2&&(t.vz=0))}}function g(t){return t.initialize&&t.initialize(e,d,r),t}return null==e&&(e=[]),m(),n={tick:f,restart:function(){return c.restart(p),n},stop:function(){return c.stop(),n},numDimensions:function(e){return arguments.length?(r=Math.min(3,Math.max(1,Math.round(e))),u.forEach(g),n):r},nodes:function(t){return arguments.length?(e=t,m(),u.forEach(g),n):e},alpha:function(e){return arguments.length?(i=+e,n):i},alphaMin:function(e){return arguments.length?(s=+e,n):s},alphaDecay:function(e){return arguments.length?(a=+e,n):+a},alphaTarget:function(e){return arguments.length?(o=+e,n):o},velocityDecay:function(e){return arguments.length?(l=1-e,n):1-l},randomSource:function(e){return arguments.length?(d=e,u.forEach(g),n):d},force:function(e,t){return arguments.length>1?(null==t?u.delete(e):u.set(e,g(t)),n):u.get(e)},find:function(){var t,n,i,s,a,o,l=Array.prototype.slice.call(arguments),u=l.shift()||0,c=(r>1?l.shift():null)||0,h=(r>2?l.shift():null)||0,d=l.shift()||1/0,p=0,f=e.length;for(d*=d,p=0;p<f;++p)(s=(t=u-(a=e[p]).x)*t+(n=c-(a.y||0))*n+(i=h-(a.z||0))*i)<d&&(o=a,d=s);return o},on:function(e,t){return arguments.length>1?(h.on(e,t),n):h.on(e)}}}function Uc(){var e,t,n,r,i,s,a=Qu(-30),o=1,l=1/0,u=.81;function c(r){var s,a=e.length,o=(1===t?Cu(e,wc):2===t?Fu(e,wc,Ec):3===t?qu(e,wc,Ec,Ac):null).visitAfter(d);for(i=r,s=0;s<a;++s)n=e[s],o.visit(p)}function h(){if(e){var t,n,r=e.length;for(s=new Array(r),t=0;t<r;++t)n=e[t],s[n.index]=+a(n,t,e)}}function d(e){var n,r,i,a,o,l,u=0,c=0,h=e.length;if(h){for(i=a=o=l=0;l<h;++l)(n=e[l])&&(r=Math.abs(n.value))&&(u+=n.value,c+=r,i+=r*(n.x||0),a+=r*(n.y||0),o+=r*(n.z||0));u*=Math.sqrt(4/h),e.x=i/c,t>1&&(e.y=a/c),t>2&&(e.z=o/c)}else{(n=e).x=n.data.x,t>1&&(n.y=n.data.y),t>2&&(n.z=n.data.z);do{u+=s[n.data.index]}while(n=n.next)}e.value=u}function p(e,a,c,h,d){if(!e.value)return!0;var p=[c,h,d][t-1],f=e.x-n.x,m=t>1?e.y-n.y:0,g=t>2?e.z-n.z:0,_=p-a,v=f*f+m*m+g*g;if(_*_/u<v)return v<l&&(0===f&&(v+=(f=Zu(r))*f),t>1&&0===m&&(v+=(m=Zu(r))*m),t>2&&0===g&&(v+=(g=Zu(r))*g),v<o&&(v=Math.sqrt(o*v)),n.vx+=f*e.value*i/v,t>1&&(n.vy+=m*e.value*i/v),t>2&&(n.vz+=g*e.value*i/v)),!0;if(!(e.length||v>=l)){(e.data!==n||e.next)&&(0===f&&(v+=(f=Zu(r))*f),t>1&&0===m&&(v+=(m=Zu(r))*m),t>2&&0===g&&(v+=(g=Zu(r))*g),v<o&&(v=Math.sqrt(o*v)));do{e.data!==n&&(_=s[e.data.index]*i/v,n.vx+=f*_,t>1&&(n.vy+=m*_),t>2&&(n.vz+=g*_))}while(e=e.next)}}return c.initialize=function(n,...i){e=n,r=i.find(e=>"function"==typeof e)||Math.random,t=i.find(e=>[1,2,3].includes(e))||2,h()},c.strength=function(e){return arguments.length?(a="function"==typeof e?e:Qu(+e),h(),c):a},c.distanceMin=function(e){return arguments.length?(o=e*e,c):Math.sqrt(o)},c.distanceMax=function(e){return arguments.length?(l=e*e,c):Math.sqrt(l)},c.theta=function(e){return arguments.length?(u=e*e,c):Math.sqrt(u)},c}function Oc(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Fc(){if(Cc)return Rc;return Cc=1,Rc=function(e){!function(e){if(!e)throw new Error("Eventify cannot use falsy object as events subject");for(var t=["on","fire","off"],n=0;n<t.length;++n)if(e.hasOwnProperty(t[n]))throw new Error("Subject cannot be eventified, since it already has property '"+t[n]+"'")}(e);var t=function(e){var t=Object.create(null);return{on:function(n,r,i){if("function"!=typeof r)throw new Error("callback is expected to be a function");var s=t[n];return s||(s=t[n]=[]),s.push({callback:r,ctx:i}),e},off:function(n,r){if(void 0===n)return t=Object.create(null),e;if(t[n])if("function"!=typeof r)delete t[n];else for(var i=t[n],s=0;s<i.length;++s)i[s].callback===r&&i.splice(s,1);return e},fire:function(n){var r,i=t[n];if(!i)return e;arguments.length>1&&(r=Array.prototype.splice.call(arguments,1));for(var s=0;s<i.length;++s){var a=i[s];a.callback.apply(a.ctx,r)}return e}}}(e);return e.on=t.on,e.off=t.off,e.fire=t.fire,e},Rc}var Bc,kc,zc,Vc,Gc,Hc=function(){if(Pc)return Nc;Pc=1,Nc=function(s){"uniqueLinkId"in(s=s||{})&&(console.warn("ngraph.graph: Starting from version 0.14 `uniqueLinkId` is deprecated.\nUse `multigraph` option instead\n","\n","Note: there is also change in default behavior: From now on each graph\nis considered to be not a multigraph by default (each edge is unique)."),s.multigraph=s.uniqueLinkId);void 0===s.multigraph&&(s.multigraph=!1);if("function"!=typeof Map)throw new Error("ngraph.graph requires `Map` to be defined. Please polyfill it before using ngraph");var a=new Map,o=new Map,l={},u=0,c=s.multigraph?function(e,t,n){var s=i(e,t),a=l.hasOwnProperty(s);if(a||w(e,t)){a||(l[s]=0);var o="@"+ ++l[s];s=i(e+o,t+o)}return new r(e,t,n,s)}:function(e,t,n){var s=i(e,t),a=o.get(s);if(a)return a.data=n,a;return new r(e,t,n,s)},h=[],d=E,p=E,f=E,m=E,g={version:20,addNode:y,addLink:function(e,t,r){f();var i=x(e)||y(e),s=x(t)||y(t),a=c(e,t,r),l=o.has(a.id);o.set(a.id,a),n(i,a),e!==t&&n(s,a);return d(a,l?"update":"add"),m(),a},removeLink:function(e,t){void 0!==t&&(e=w(e,t));return M(e)},removeNode:b,getNode:x,getNodeCount:T,getLinkCount:S,getEdgeCount:S,getLinksCount:S,getNodesCount:T,getLinks:function(e){var t=x(e);return t?t.links:null},forEachNode:C,forEachLinkedNode:function(e,t,n){var r=x(e);if(r&&r.links&&"function"==typeof t)return n?function(e,t,n){var r=e.values(),i=r.next();for(;!i.done;){var s=i.value;if(s.fromId===t&&n(a.get(s.toId),s))return!0;i=r.next()}}(r.links,e,t):function(e,t,n){var r=e.values(),i=r.next();for(;!i.done;){var s=i.value,o=s.fromId===t?s.toId:s.fromId;if(n(a.get(o),s))return!0;i=r.next()}}(r.links,e,t)},forEachLink:function(e){if("function"==typeof e)for(var t=o.values(),n=t.next();!n.done;){if(e(n.value))return!0;n=t.next()}},beginUpdate:f,endUpdate:m,clear:function(){f(),C(function(e){b(e.id)}),m()},hasLink:w,hasNode:x,getLink:w};return e(g),function(){var e=g.on;function t(){return g.beginUpdate=f=A,g.endUpdate=m=R,d=_,p=v,g.on=e,e.apply(g,arguments)}g.on=t}(),g;function _(e,t){h.push({link:e,changeType:t})}function v(e,t){h.push({node:e,changeType:t})}function y(e,n){if(void 0===e)throw new Error("Invalid node identifier");f();var r=x(e);return r?(r.data=n,p(r,"update")):(r=new t(e,n),p(r,"add")),a.set(e,r),m(),r}function x(e){return a.get(e)}function b(e){var t=x(e);if(!t)return!1;f();var n=t.links;return n&&(n.forEach(M),t.links=null),a.delete(e),p(t,"remove"),m(),!0}function T(){return a.size}function S(){return o.size}function M(e){if(!e)return!1;if(!o.get(e.id))return!1;f(),o.delete(e.id);var t=x(e.fromId),n=x(e.toId);return t&&t.links.delete(e),n&&n.links.delete(e),d(e,"remove"),m(),!0}function w(e,t){if(void 0!==e&&void 0!==t)return o.get(i(e,t))}function E(){}function A(){u+=1}function R(){0===(u-=1)&&h.length>0&&(g.fire("changed",h),h.length=0)}function C(e){if("function"!=typeof e)throw new Error("Function is expected to iterate over graph nodes. You passed "+e);for(var t=a.values(),n=t.next();!n.done;){if(e(n.value))return!0;n=t.next()}}};var e=Fc();function t(e,t){this.id=e,this.links=null,this.data=t}function n(e,t){e.links?e.links.add(t):e.links=new Set([t])}function r(e,t,n,r){this.fromId=e,this.toId=t,this.data=n,this.id=r}function i(e,t){return e.toString()+"👉 "+t.toString()}return Nc}(),jc=Oc(Hc),Wc={exports:{}},Xc={exports:{}};function qc(){return kc||(kc=1,Bc=function(e){return 0===e?"x":1===e?"y":2===e?"z":"c"+(e+1)}),Bc}function $c(){if(Vc)return zc;Vc=1;const e=qc();return zc=function(t){return function(n,r){let i=r&&r.indent||0,s=r&&void 0!==r.join?r.join:"\n",a=Array(i+1).join(" "),o=[];for(let r=0;r<t;++r){let t=e(r),i=0===r?"":a;o.push(i+n.replace(/{var}/g,t))}return o.join(s)}},zc}var Yc,Kc={exports:{}};var Qc,Zc={exports:{}};var Jc,eh={exports:{}};var th,nh={exports:{}};var rh,ih,sh,ah,oh,lh={exports:{}};var uh,ch,hh,dh,ph={exports:{}};function fh(){if(hh)return ch;hh=1,ch=function(l){var u=(sh||(sh=1,ih=function(e,t,n,r){this.from=e,this.to=t,this.length=n,this.coefficient=r}),ih),c=(oh||(oh=1,ah=function e(t,n){var r;if(t||(t={}),n)for(r in n)if(n.hasOwnProperty(r)){var i=t.hasOwnProperty(r),s=typeof n[r];i&&typeof t[r]===s?"object"===s&&(t[r]=e(t[r],n[r])):t[r]=n[r]}return t}),ah),h=Fc();if(l){if(void 0!==l.springCoeff)throw new Error("springCoeff was renamed to springCoefficient");if(void 0!==l.dragCoeff)throw new Error("dragCoeff was renamed to dragCoefficient")}l=c(l,{springLength:10,springCoefficient:.8,gravity:-12,theta:.8,dragCoefficient:.9,timeStep:.5,adaptiveTimeStepWeight:0,dimensions:2,debug:!1});var d=a[l.dimensions];if(!d){var p=l.dimensions;d={Body:e(p,l.debug),createQuadTree:t(p),createBounds:n(p),createDragForce:r(p),createSpringForce:i(p),integrate:s(p)},a[p]=d}var f=d.Body,m=d.createQuadTree,g=d.createBounds,_=d.createDragForce,v=d.createSpringForce,y=d.integrate,x=function(){if(uh)return ph.exports;function e(e){return new t("number"==typeof e?e:+new Date)}function t(e){this.seed=e}function n(e){return Math.sqrt(2*Math.PI/e)*Math.pow(1/Math.E*(e+1/(12*e-1/(10*e))),e)}function r(){var e=this.seed;return e=4294967295&(3042594569^(e=4251993797+(e=4294967295&(3550635116+(e=374761393+(e=4294967295&(3345072700^(e=e+2127912214+(e<<12)&4294967295)^e>>>19))+(e<<5)&4294967295)^e<<9))+(e<<3)&4294967295)^e>>>16),this.seed=e,(268435455&e)/268435456}return uh=1,ph.exports=e,ph.exports.random=e,ph.exports.randomIterator=function(t,n){var r=n||e();if("function"!=typeof r.next)throw new Error("customRandom does not match expected API: next() function is missing");return{forEach:function(e){var n,i,s;for(n=t.length-1;n>0;--n)i=r.next(n+1),s=t[i],t[i]=t[n],t[n]=s,e(s);t.length&&e(t[0])},shuffle:function(){var e,n,i;for(e=t.length-1;e>0;--e)n=r.next(e+1),i=t[n],t[n]=t[e],t[e]=i;return t}}},t.prototype.next=function(e){return Math.floor(this.nextDouble()*e)},t.prototype.nextDouble=r,t.prototype.uniform=r,t.prototype.gaussian=function(){var e,t,n;do{e=(t=2*this.nextDouble()-1)*t+(n=2*this.nextDouble()-1)*n}while(e>=1||0===e);return t*Math.sqrt(-2*Math.log(e)/e)},t.prototype.random=r,t.prototype.levy=function(){var e=1.5,t=Math.pow(n(2.5)*Math.sin(Math.PI*e/2)/(n(1.25)*e*Math.pow(2,.25)),1/e);return this.gaussian()*t/Math.pow(Math.abs(this.gaussian()),1/e)},ph.exports}().random(42),b=[],T=[],S=m(l,x),M=g(b,l,x),w=v(l,x),E=_(l),A=[],R=new Map,C=0;L("nbody",function(){if(0===b.length)return;S.insertBodies(b);var e=b.length;for(;e--;){var t=b[e];t.isPinned||(t.reset(),S.updateBodyForce(t),E.update(t))}}),L("spring",function(){var e=T.length;for(;e--;)w.update(T[e])});var N={bodies:b,quadTree:S,springs:T,settings:l,addForce:L,removeForce:function(e){var t=A.indexOf(R.get(e));if(t<0)return;A.splice(t,1),R.delete(e)},getForces:function(){return R},step:function(){for(var e=0;e<A.length;++e)A[e](C);var t=y(b,l.timeStep,l.adaptiveTimeStepWeight);return C+=1,t},addBody:function(e){if(!e)throw new Error("Body is required");return b.push(e),e},addBodyAt:function(e){if(!e)throw new Error("Body position is required");var t=(e=>new f(e))(e);return b.push(t),t},removeBody:function(e){if(e){var t=b.indexOf(e);if(!(t<0))return b.splice(t,1),0===b.length&&M.reset(),!0}},addSpring:function(e,t,n,r){if(!e||!t)throw new Error("Cannot add null spring to force simulator");"number"!=typeof n&&(n=-1);var i=new u(e,t,n,r>=0?r:-1);return T.push(i),i},getTotalMovement:function(){return 0},removeSpring:function(e){if(e){var t=T.indexOf(e);return t>-1?(T.splice(t,1),!0):void 0}},getBestNewBodyPosition:function(e){return M.getBestNewPosition(e)},getBBox:P,getBoundingBox:P,invalidateBBox:function(){console.warn("invalidateBBox() is deprecated, bounds always recomputed on `getBBox()` call")},gravity:function(e){return void 0!==e?(l.gravity=e,S.options({gravity:e}),this):l.gravity},theta:function(e){return void 0!==e?(l.theta=e,S.options({theta:e}),this):l.theta},random:x};return function(e,t){for(var n in e)o(e,t,n)}(l,N),h(N),N;function P(){return M.update(),M.box}function L(e,t){if(R.has(e))throw new Error("Force "+e+" is already added");R.set(e,t),A.push(t)}};var e=function(){if(Gc)return Xc.exports;Gc=1;const e=$c();function t(e,t){return`\n${r(e,t)}\n${n(e)}\nreturn {Body: Body, Vector: Vector};\n`}function n(t){let n=e(t),r=n("{var}",{join:", "});return`\nfunction Body(${r}) {\n this.isPinned = false;\n this.pos = new Vector(${r});\n this.force = new Vector();\n this.velocity = new Vector();\n this.mass = 1;\n\n this.springCount = 0;\n this.springLength = 0;\n}\n\nBody.prototype.reset = function() {\n this.force.reset();\n this.springCount = 0;\n this.springLength = 0;\n}\n\nBody.prototype.setPosition = function (${r}) {\n ${n("this.pos.{var} = {var} || 0;",{indent:2})}\n};`}function r(t,n){let r=e(t),i="";return n&&(i=`${r("\n\t var v{var};\n\tObject.defineProperty(this, '{var}', {\n\t set: function(v) { \n\t if (!Number.isFinite(v)) throw new Error('Cannot set non-numbers to {var}');\n\t v{var} = v; \n\t },\n\t get: function() { return v{var}; }\n\t});")}`),`function Vector(${r("{var}",{join:", "})}) {\n ${i}\n if (typeof arguments[0] === 'object') {\n // could be another vector\n let v = arguments[0];\n ${r('if (!Number.isFinite(v.{var})) throw new Error("Expected value is not a finite number at Vector constructor ({var})");',{indent:4})}\n ${r("this.{var} = v.{var};",{indent:4})}\n } else {\n ${r('this.{var} = typeof {var} === "number" ? {var} : 0;',{indent:4})}\n }\n }\n \n Vector.prototype.reset = function () {\n ${r("this.{var} = ",{join:""})}0;\n };`}return Xc.exports=function(e,n){let r=t(e,n),{Body:i}=new Function(r)();return i},Xc.exports.generateCreateBodyFunctionBody=t,Xc.exports.getVectorCode=r,Xc.exports.getBodyCode=n,Xc.exports}(),t=function(){if(Yc)return Kc.exports;Yc=1;const e=$c(),t=qc();function n(n){let l=e(n),u=Math.pow(2,n),c=`\n${o()}\n${a(n)}\n${r(n)}\n${s(n)}\n${i(n)}\n\nfunction createQuadTree(options, random) {\n options = options || {};\n options.gravity = typeof options.gravity === 'number' ? options.gravity : -1;\n options.theta = typeof options.theta === 'number' ? options.theta : 0.8;\n\n var gravity = options.gravity;\n var updateQueue = [];\n var insertStack = new InsertStack();\n var theta = options.theta;\n\n var nodesCache = [];\n var currentInCache = 0;\n var root = newNode();\n\n return {\n insertBodies: insertBodies,\n\n /**\n * Gets root node if it is present\n */\n getRoot: function() {\n return root;\n },\n\n updateBodyForce: update,\n\n options: function(newOptions) {\n if (newOptions) {\n if (typeof newOptions.gravity === 'number') {\n gravity = newOptions.gravity;\n }\n if (typeof newOptions.theta === 'number') {\n theta = newOptions.theta;\n }\n\n return this;\n }\n\n return {\n gravity: gravity,\n theta: theta\n };\n }\n };\n\n function newNode() {\n // To avoid pressure on GC we reuse nodes.\n var node = nodesCache[currentInCache];\n if (node) {\n${function(e){let t=[];for(let n=0;n<u;++n)t.push(`${e}quad${n} = null;`);return t.join("\n")}(" node.")}\n node.body = null;\n node.mass = ${l("node.mass_{var} = ",{join:""})}0;\n ${l("node.min_{var} = node.max_{var} = ",{join:""})}0;\n } else {\n node = new QuadNode();\n nodesCache[currentInCache] = node;\n }\n\n ++currentInCache;\n return node;\n }\n\n function update(sourceBody) {\n var queue = updateQueue;\n var v;\n ${l("var d{var};",{indent:4})}\n var r; \n ${l("var f{var} = 0;",{indent:4})}\n var queueLength = 1;\n var shiftIdx = 0;\n var pushIdx = 1;\n\n queue[0] = root;\n\n while (queueLength) {\n var node = queue[shiftIdx];\n var body = node.body;\n\n queueLength -= 1;\n shiftIdx += 1;\n var differentBody = (body !== sourceBody);\n if (body && differentBody) {\n // If the current node is a leaf node (and it is not source body),\n // calculate the force exerted by the current node on body, and add this\n // amount to body's net force.\n ${l("d{var} = body.pos.{var} - sourceBody.pos.{var};",{indent:8})}\n r = Math.sqrt(${l("d{var} * d{var}",{join:" + "})});\n\n if (r === 0) {\n // Poor man's protection against zero distance.\n ${l("d{var} = (random.nextDouble() - 0.5) / 50;",{indent:10})}\n r = Math.sqrt(${l("d{var} * d{var}",{join:" + "})});\n }\n\n // This is standard gravitation force calculation but we divide\n // by r^3 to save two operations when normalizing force vector.\n v = gravity * body.mass * sourceBody.mass / (r * r * r);\n ${l("f{var} += v * d{var};",{indent:8})}\n } else if (differentBody) {\n // Otherwise, calculate the ratio s / r, where s is the width of the region\n // represented by the internal node, and r is the distance between the body\n // and the node's center-of-mass\n ${l("d{var} = node.mass_{var} / node.mass - sourceBody.pos.{var};",{indent:8})}\n r = Math.sqrt(${l("d{var} * d{var}",{join:" + "})});\n\n if (r === 0) {\n // Sorry about code duplication. I don't want to create many functions\n // right away. Just want to see performance first.\n ${l("d{var} = (random.nextDouble() - 0.5) / 50;",{indent:10})}\n r = Math.sqrt(${l("d{var} * d{var}",{join:" + "})});\n }\n // If s / r < θ, treat this internal node as a single body, and calculate the\n // force it exerts on sourceBody, and add this amount to sourceBody's net force.\n if ((node.max_${t(0)} - node.min_${t(0)}) / r < theta) {\n // in the if statement above we consider node's width only\n // because the region was made into square during tree creation.\n // Thus there is no difference between using width or height.\n v = gravity * node.mass * sourceBody.mass / (r * r * r);\n ${l("f{var} += v * d{var};",{indent:10})}\n } else {\n // Otherwise, run the procedure recursively on each of the current node's children.\n\n // I intentionally unfolded this loop, to save several CPU cycles.\n${function(){let e=Array(11).join(" "),t=[];for(let n=0;n<u;++n)t.push(e+`if (node.quad${n}) {`),t.push(e+` queue[pushIdx] = node.quad${n};`),t.push(e+" queueLength += 1;"),t.push(e+" pushIdx += 1;"),t.push(e+"}");return t.join("\n")}()}\n }\n }\n }\n\n ${l("sourceBody.force.{var} += f{var};",{indent:4})}\n }\n\n function insertBodies(bodies) {\n ${l("var {var}min = Number.MAX_VALUE;",{indent:4})}\n ${l("var {var}max = Number.MIN_VALUE;",{indent:4})}\n var i = bodies.length;\n\n // To reduce quad tree depth we are looking for exact bounding box of all particles.\n while (i--) {\n var pos = bodies[i].pos;\n ${l("if (pos.{var} < {var}min) {var}min = pos.{var};",{indent:6})}\n ${l("if (pos.{var} > {var}max) {var}max = pos.{var};",{indent:6})}\n }\n\n // Makes the bounds square.\n var maxSideLength = -Infinity;\n ${l("if ({var}max - {var}min > maxSideLength) maxSideLength = {var}max - {var}min ;",{indent:4})}\n\n currentInCache = 0;\n root = newNode();\n ${l("root.min_{var} = {var}min;",{indent:4})}\n ${l("root.max_{var} = {var}min + maxSideLength;",{indent:4})}\n\n i = bodies.length - 1;\n if (i >= 0) {\n root.body = bodies[i];\n }\n while (i--) {\n insert(bodies[i], root);\n }\n }\n\n function insert(newBody) {\n insertStack.reset();\n insertStack.push(root, newBody);\n\n while (!insertStack.isEmpty()) {\n var stackItem = insertStack.pop();\n var node = stackItem.node;\n var body = stackItem.body;\n\n if (!node.body) {\n // This is internal node. Update the total mass of the node and center-of-mass.\n ${l("var {var} = body.pos.{var};",{indent:8})}\n node.mass += body.mass;\n ${l("node.mass_{var} += body.mass * {var};",{indent:8})}\n\n // Recursively insert the body in the appropriate quadrant.\n // But first find the appropriate quadrant.\n var quadIdx = 0; // Assume we are in the 0's quad.\n ${l("var min_{var} = node.min_{var};",{indent:8})}\n ${l("var max_{var} = (min_{var} + node.max_{var}) / 2;",{indent:8})}\n\n${function(){let e=[],r=Array(8+1).join(" ");for(let i=0;i<n;++i)e.push(r+`if (${t(i)} > max_${t(i)}) {`),e.push(r+` quadIdx = quadIdx + ${Math.pow(2,i)};`),e.push(r+` min_${t(i)} = max_${t(i)};`),e.push(r+` max_${t(i)} = node.max_${t(i)};`),e.push(r+"}");return e.join("\n")}()}\n\n var child = getChild(node, quadIdx);\n\n if (!child) {\n // The node is internal but this quadrant is not taken. Add\n // subnode to it.\n child = newNode();\n ${l("child.min_{var} = min_{var};",{indent:10})}\n ${l("child.max_{var} = max_{var};",{indent:10})}\n child.body = body;\n\n setChild(node, quadIdx, child);\n } else {\n // continue searching in this quadrant.\n insertStack.push(child, body);\n }\n } else {\n // We are trying to add to the leaf node.\n // We have to convert current leaf into internal node\n // and continue adding two nodes.\n var oldBody = node.body;\n node.body = null; // internal nodes do not cary bodies\n\n if (isSamePosition(oldBody.pos, body.pos)) {\n // Prevent infinite subdivision by bumping one node\n // anywhere in this quadrant\n var retriesCount = 3;\n do {\n var offset = random.nextDouble();\n ${l("var d{var} = (node.max_{var} - node.min_{var}) * offset;",{indent:12})}\n\n ${l("oldBody.pos.{var} = node.min_{var} + d{var};",{indent:12})}\n retriesCount -= 1;\n // Make sure we don't bump it out of the box. If we do, next iteration should fix it\n } while (retriesCount > 0 && isSamePosition(oldBody.pos, body.pos));\n\n if (retriesCount === 0 && isSamePosition(oldBody.pos, body.pos)) {\n // This is very bad, we ran out of precision.\n // if we do not return from the method we'll get into\n // infinite loop here. So we sacrifice correctness of layout, and keep the app running\n // Next layout iteration should get larger bounding box in the first step and fix this\n return;\n }\n }\n // Next iteration should subdivide node further.\n insertStack.push(node, oldBody);\n insertStack.push(node, body);\n }\n }\n }\n}\nreturn createQuadTree;\n\n`;return c}function r(t){let n=e(t);return`\n function isSamePosition(point1, point2) {\n ${n("var d{var} = Math.abs(point1.{var} - point2.{var});",{indent:2})}\n \n return ${n("d{var} < 1e-8",{join:" && "})};\n } \n`}function i(e){var t=Math.pow(2,e);return`\nfunction setChild(node, idx, child) {\n ${function(){let e=[];for(let n=0;n<t;++n){let t=0===n?" ":" else ";e.push(`${t}if (idx === ${n}) node.quad${n} = child;`)}return e.join("\n")}()}\n}`}function s(e){return`function getChild(node, idx) {\n${function(){let t=[],n=Math.pow(2,e);for(let e=0;e<n;++e)t.push(` if (idx === ${e}) return node.quad${e};`);return t.join("\n")}()}\n return null;\n}`}function a(t){let n=e(t),r=Math.pow(2,t);var i=`\nfunction QuadNode() {\n // body stored inside this node. In quad tree only leaf nodes (by construction)\n // contain bodies:\n this.body = null;\n\n // Child nodes are stored in quads. Each quad is presented by number:\n // 0 | 1\n // -----\n // 2 | 3\n${function(e){let t=[];for(let n=0;n<r;++n)t.push(`${e}quad${n} = null;`);return t.join("\n")}(" this.")}\n\n // Total mass of current node\n this.mass = 0;\n\n // Center of mass coordinates\n ${n("this.mass_{var} = 0;",{indent:2})}\n\n // bounding box coordinates\n ${n("this.min_{var} = 0;",{indent:2})}\n ${n("this.max_{var} = 0;",{indent:2})}\n}\n`;return i}function o(){return"\n/**\n * Our implementation of QuadTree is non-recursive to avoid GC hit\n * This data structure represent stack of elements\n * which we are trying to insert into quad tree.\n */\nfunction InsertStack () {\n this.stack = [];\n this.popIdx = 0;\n}\n\nInsertStack.prototype = {\n isEmpty: function() {\n return this.popIdx === 0;\n },\n push: function (node, body) {\n var item = this.stack[this.popIdx];\n if (!item) {\n // we are trying to avoid memory pressure: create new element\n // only when absolutely necessary\n this.stack[this.popIdx] = new InsertStackElement(node, body);\n } else {\n item.node = node;\n item.body = body;\n }\n ++this.popIdx;\n },\n pop: function () {\n if (this.popIdx > 0) {\n return this.stack[--this.popIdx];\n }\n },\n reset: function () {\n this.popIdx = 0;\n }\n};\n\nfunction InsertStackElement(node, body) {\n this.node = node; // QuadTree node\n this.body = body; // physical body which needs to be inserted to node\n}\n"}return Kc.exports=function(e){let t=n(e);return new Function(t)()},Kc.exports.generateQuadTreeFunctionBody=n,Kc.exports.getInsertStackCode=o,Kc.exports.getQuadNodeCode=a,Kc.exports.isSamePosition=r,Kc.exports.getChildBodyCode=s,Kc.exports.setChildBodyCode=i,Kc.exports}(),n=function(){if(Qc)return Zc.exports;Qc=1,Zc.exports=function(e){let n=t(e);return new Function("bodies","settings","random",n)},Zc.exports.generateFunctionBody=t;const e=$c();function t(t){let n=e(t);return`\n var boundingBox = {\n ${n("min_{var}: 0, max_{var}: 0,",{indent:4})}\n };\n\n return {\n box: boundingBox,\n\n update: updateBoundingBox,\n\n reset: resetBoundingBox,\n\n getBestNewPosition: function (neighbors) {\n var ${n("base_{var} = 0",{join:", "})};\n\n if (neighbors.length) {\n for (var i = 0; i < neighbors.length; ++i) {\n let neighborPos = neighbors[i].pos;\n ${n("base_{var} += neighborPos.{var};",{indent:10})}\n }\n\n ${n("base_{var} /= neighbors.length;",{indent:8})}\n } else {\n ${n("base_{var} = (boundingBox.min_{var} + boundingBox.max_{var}) / 2;",{indent:8})}\n }\n\n var springLength = settings.springLength;\n return {\n ${n("{var}: base_{var} + (random.nextDouble() - 0.5) * springLength,",{indent:8})}\n };\n }\n };\n\n function updateBoundingBox() {\n var i = bodies.length;\n if (i === 0) return; // No bodies - no borders.\n\n ${n("var max_{var} = -Infinity;",{indent:4})}\n ${n("var min_{var} = Infinity;",{indent:4})}\n\n while(i--) {\n // this is O(n), it could be done faster with quadtree, if we check the root node bounds\n var bodyPos = bodies[i].pos;\n ${n("if (bodyPos.{var} < min_{var}) min_{var} = bodyPos.{var};",{indent:6})}\n ${n("if (bodyPos.{var} > max_{var}) max_{var} = bodyPos.{var};",{indent:6})}\n }\n\n ${n("boundingBox.min_{var} = min_{var};",{indent:4})}\n ${n("boundingBox.max_{var} = max_{var};",{indent:4})}\n }\n\n function resetBoundingBox() {\n ${n("boundingBox.min_{var} = boundingBox.max_{var} = 0;",{indent:4})}\n }\n`}return Zc.exports}(),r=function(){if(Jc)return eh.exports;Jc=1;const e=$c();function t(t){return`\n if (!Number.isFinite(options.dragCoefficient)) throw new Error('dragCoefficient is not a finite number');\n\n return {\n update: function(body) {\n ${e(t)("body.force.{var} -= options.dragCoefficient * body.velocity.{var};",{indent:6})}\n }\n };\n`}return eh.exports=function(e){let n=t(e);return new Function("options",n)},eh.exports.generateCreateDragForceFunctionBody=t,eh.exports}(),i=function(){if(th)return nh.exports;th=1;const e=$c();function t(t){let n=e(t);return`\n if (!Number.isFinite(options.springCoefficient)) throw new Error('Spring coefficient is not a number');\n if (!Number.isFinite(options.springLength)) throw new Error('Spring length is not a number');\n\n return {\n /**\n * Updates forces acting on a spring\n */\n update: function (spring) {\n var body1 = spring.from;\n var body2 = spring.to;\n var length = spring.length < 0 ? options.springLength : spring.length;\n ${n("var d{var} = body2.pos.{var} - body1.pos.{var};",{indent:6})}\n var r = Math.sqrt(${n("d{var} * d{var}",{join:" + "})});\n\n if (r === 0) {\n ${n("d{var} = (random.nextDouble() - 0.5) / 50;",{indent:8})}\n r = Math.sqrt(${n("d{var} * d{var}",{join:" + "})});\n }\n\n var d = r - length;\n var coefficient = ((spring.coefficient > 0) ? spring.coefficient : options.springCoefficient) * d / r;\n\n ${n("body1.force.{var} += coefficient * d{var}",{indent:6})};\n body1.springCount += 1;\n body1.springLength += r;\n\n ${n("body2.force.{var} -= coefficient * d{var}",{indent:6})};\n body2.springCount += 1;\n body2.springLength += r;\n }\n };\n`}return nh.exports=function(e){let n=t(e);return new Function("options","random",n)},nh.exports.generateCreateSpringForceFunctionBody=t,nh.exports}(),s=function(){if(rh)return lh.exports;rh=1;const e=$c();function t(t){let n=e(t);return`\n var length = bodies.length;\n if (length === 0) return 0;\n\n ${n("var d{var} = 0, t{var} = 0;",{indent:2})}\n\n for (var i = 0; i < length; ++i) {\n var body = bodies[i];\n if (body.isPinned) continue;\n\n if (adaptiveTimeStepWeight && body.springCount) {\n timeStep = (adaptiveTimeStepWeight * body.springLength/body.springCount);\n }\n\n var coeff = timeStep / body.mass;\n\n ${n("body.velocity.{var} += coeff * body.force.{var};",{indent:4})}\n ${n("var v{var} = body.velocity.{var};",{indent:4})}\n var v = Math.sqrt(${n("v{var} * v{var}",{join:" + "})});\n\n if (v > 1) {\n // We normalize it so that we move within timeStep range. \n // for the case when v <= 1 - we let velocity to fade out.\n ${n("body.velocity.{var} = v{var} / v;",{indent:6})}\n }\n\n ${n("d{var} = timeStep * body.velocity.{var};",{indent:4})}\n\n ${n("body.pos.{var} += d{var};",{indent:4})}\n\n ${n("t{var} += Math.abs(d{var});",{indent:4})}\n }\n\n return (${n("t{var} * t{var}",{join:" + "})})/length;\n`}return lh.exports=function(e){let n=t(e);return new Function("bodies","timeStep","adaptiveTimeStepWeight",n)},lh.exports.generateIntegratorFunctionBody=t,lh.exports}(),a={};function o(e,t,n){if(e.hasOwnProperty(n)&&"function"!=typeof t[n]){var r=Number.isFinite(e[n]);t[n]=r?function(r){if(void 0!==r){if(!Number.isFinite(r))throw new Error("Value of "+n+" should be a valid number.");return e[n]=r,t}return e[n]}:function(r){return void 0!==r?(e[n]=r,t):e[n]}}}return ch}var mh=function(){if(dh)return Wc.exports;dh=1,Wc.exports=function(n,r){if(!n)throw new Error("Graph structure cannot be undefined");var i=(r&&r.createSimulator||fh())(r);if(Array.isArray(r))throw new Error("Physics settings is expected to be an object");var s=n.version>19?function(e){var t=n.getLinks(e);return t?1+t.size/3:1}:function(e){var t=n.getLinks(e);return t?1+t.length/3:1};r&&"function"==typeof r.nodeMass&&(s=r.nodeMass);var a=new Map,o={},l=0,u=i.settings.springTransform||t;l=0,n.forEachNode(function(e){m(e.id),l+=1}),n.forEachLink(_),n.on("changed",f);var c=!1,h={step:function(){if(0===l)return d(!0),!0;var e=i.step();h.lastMove=e,h.fire("step");var t=e/l<=.01;return d(t),t},getNodePosition:function(e){return x(e).pos},setNodePosition:function(e){var t=x(e);t.setPosition.apply(t,Array.prototype.slice.call(arguments,1))},getLinkPosition:function(e){var t=o[e];if(t)return{from:t.from.pos,to:t.to.pos}},getGraphRect:function(){return i.getBBox()},forEachBody:p,pinNode:function(e,t){x(e.id).isPinned=!!t},isNodePinned:function(e){return x(e.id).isPinned},dispose:function(){n.off("changed",f),h.fire("disposed")},getBody:function(e){return a.get(e)},getSpring:function(e,t){var r;if(void 0===t)r="object"!=typeof e?e:e.id;else{var i=n.hasLink(e,t);if(!i)return;r=i.id}return o[r]},getForceVectorLength:function(){var e=0,t=0;return p(function(n){e+=Math.abs(n.force.x),t+=Math.abs(n.force.y)}),Math.sqrt(e*e+t*t)},simulator:i,graph:n,lastMove:0};return e(h),h;function d(e){var t;c!==e&&(c=e,t=e,h.fire("stable",t))}function p(e){a.forEach(e)}function f(e){for(var t=0;t<e.length;++t){var r=e[t];"add"===r.changeType?(r.node&&m(r.node.id),r.link&&_(r.link)):"remove"===r.changeType&&(r.node&&g(r.node),r.link&&v(r.link))}l=n.getNodesCount()}function m(e){var t=a.get(e);if(!t){var r=n.getNode(e);if(!r)throw new Error("initBody() was called with unknown node id");var s=r.position;if(!s){var o=function(e){var t=[];if(!e.links)return t;for(var n=Math.min(e.links.length,2),r=0;r<n;++r){var i=e.links[r],s=i.fromId!==e.id?a.get(i.fromId):a.get(i.toId);s&&s.pos&&t.push(s)}return t}(r);s=i.getBestNewBodyPosition(o)}(t=i.addBodyAt(s)).id=e,a.set(e,t),y(e),function(e){return e&&(e.isPinned||e.data&&e.data.isPinned)}(r)&&(t.isPinned=!0)}}function g(e){var t=e.id,n=a.get(t);n&&(a.delete(t),i.removeBody(n))}function _(e){y(e.fromId),y(e.toId);var t=a.get(e.fromId),n=a.get(e.toId),r=i.addSpring(t,n,e.length);u(e,r),o[e.id]=r}function v(e){var t=o[e.id];if(t){var r=n.getNode(e.fromId),s=n.getNode(e.toId);r&&y(r.id),s&&y(s.id),delete o[e.id],i.removeSpring(t)}}function y(e){var t=a.get(e);if(t.mass=s(e),Number.isNaN(t.mass))throw new Error("Node mass should be a number")}function x(e){var t=a.get(e);return t||(m(e),t=a.get(e)),t}},Wc.exports.simulator=fh();var e=Fc();function t(){}return Wc.exports}(),gh=Oc(mh);function _h(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}var vh="object"==typeof global&&global&&global.Object===Object&&global,yh="object"==typeof self&&self&&self.Object===Object&&self,xh=vh||yh||Function("return this")(),bh=function(){return xh.Date.now()},Th=/\s/;var Sh=/^\s+/;function Mh(e){return e?e.slice(0,function(e){for(var t=e.length;t--&&Th.test(e.charAt(t)););return t}(e)+1).replace(Sh,""):e}var wh=xh.Symbol,Eh=Object.prototype,Ah=Eh.hasOwnProperty,Rh=Eh.toString,Ch=wh?wh.toStringTag:void 0;var Nh=Object.prototype.toString;var Ph=wh?wh.toStringTag:void 0;function Lh(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":Ph&&Ph in Object(e)?function(e){var t=Ah.call(e,Ch),n=e[Ch];try{e[Ch]=void 0;var r=!0}catch(e){}var i=Rh.call(e);return r&&(t?e[Ch]=n:delete e[Ch]),i}(e):function(e){return Nh.call(e)}(e)}var Dh=/^[-+]0x[0-9a-f]+$/i,Ih=/^0b[01]+$/i,Uh=/^0o[0-7]+$/i,Oh=parseInt;function Fh(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]"==Lh(e)}(e))return NaN;if(_h(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=_h(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=Mh(e);var n=Ih.test(e);return n||Uh.test(e)?Oh(e.slice(2),n?2:8):Dh.test(e)?NaN:+e}var Bh=Math.max,kh=Math.min;function zh(e,t,n){var r,i,s,a,o,l,u=0,c=!1,h=!1,d=!0;if("function"!=typeof e)throw new TypeError("Expected a function");function p(t){var n=r,s=i;return r=i=void 0,u=t,a=e.apply(s,n)}function f(e){var n=e-l;return void 0===l||n>=t||n<0||h&&e-u>=s}function m(){var e=bh();if(f(e))return g(e);o=setTimeout(m,function(e){var n=t-(e-l);return h?kh(n,s-(e-u)):n}(e))}function g(e){return o=void 0,d&&r?p(e):(r=i=void 0,a)}function _(){var e=bh(),n=f(e);if(r=arguments,i=this,l=e,n){if(void 0===o)return function(e){return u=e,o=setTimeout(m,t),c?p(e):a}(l);if(h)return clearTimeout(o),o=setTimeout(m,t),p(l)}return void 0===o&&(o=setTimeout(m,t)),a}return t=Fh(t)||0,_h(n)&&(c=!!n.leading,s=(h="maxWait"in n)?Bh(Fh(n.maxWait)||0,t):s,d="trailing"in n?!!n.trailing:d),_.cancel=function(){void 0!==o&&clearTimeout(o),u=0,r=l=i=o=void 0},_.flush=function(){return void 0===o?a:g(bh())},_}function Vh(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function Gh(e,t,n){return Object.defineProperty(e,"prototype",{writable:!1}),e}function Hh(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,s,a,o=[],l=!0,u=!1;try{if(s=(n=n.call(e)).next,0===t);else for(;!(l=(r=s.call(n)).done)&&(o.push(r.value),o.length!==t);l=!0);}catch(e){u=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(u)throw i}}return o}}(e,t)||function(e,t){if(e){if("string"==typeof e)return Vh(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Vh(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 jh=Gh(function e(t,n){var r=n.default,i=void 0===r?null:r,s=n.triggerUpdate,a=void 0===s||s,o=n.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=i,this.triggerUpdate=a,this.onChange=l});function Wh(e){var t=e.stateInit,n=void 0===t?function(){return{}}:t,r=e.props,i=void 0===r?{}:r,s=e.methods,a=void 0===s?{}:s,o=e.aliases,l=void 0===o?{}:o,u=e.init,c=void 0===u?function(){}:u,h=e.update,d=void 0===h?function(){}:h,p=Object.keys(i).map(function(e){return new jh(e,i[e])});return function e(){for(var t=arguments.length,r=new Array(t),i=0;i<t;i++)r[i]=arguments[i];var s=!!(this instanceof e?this.constructor:void 0),o=s?r.shift():void 0,u=r[0],h=void 0===u?{}:u,f=Object.assign({},n instanceof Function?n(h):n,{initialised:!1}),m={};function g(e){return _(e,h),v(),g}var _=function(e,t){c.call(g,e,f,t),f.initialised=!0},v=zh(function(){f.initialised&&(d.call(g,f,m),m={})},1);return p.forEach(function(e){g[e.name]=function(e){var t=e.name,n=e.triggerUpdate,r=void 0!==n&&n,i=e.onChange,s=void 0===i?function(e,t){}:i,a=e.defaultVal,o=void 0===a?null:a;return function(e){var n=f[t];if(!arguments.length)return n;var i=void 0===e?o:e;return f[t]=i,s.call(g,i,f,n),!m.hasOwnProperty(t)&&(m[t]=n),r&&v(),g}}(e)}),Object.keys(a).forEach(function(e){g[e]=function(){for(var t,n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];return(t=a[e]).call.apply(t,[g,f].concat(r))}}),Object.entries(l).forEach(function(e){var t=Hh(e,2),n=t[0],r=t[1];return g[n]=g[r]}),g.resetProps=function(){return p.forEach(function(e){g[e.name](e.defaultVal)}),g},g.resetProps(),f._rerender=v,s&&o&&g(o),g}}var Xh=function(e){return"function"==typeof e?e:"string"==typeof e?function(t){return t[e]}:function(t){return e}};class qh extends Map{constructor(e,t=Yh){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:t}}),null!=e)for(const[t,n]of e)this.set(t,n)}get(e){return super.get($h(this,e))}has(e){return super.has($h(this,e))}set(e,t){return super.set(function({_intern:e,_key:t},n){const r=t(n);return e.has(r)?e.get(r):(e.set(r,n),n)}(this,e),t)}delete(e){return super.delete(function({_intern:e,_key:t},n){const r=t(n);e.has(r)&&(n=e.get(r),e.delete(r));return n}(this,e))}}function $h({_intern:e,_key:t},n){const r=t(n);return e.has(r)?e.get(r):n}function Yh(e){return null!==e&&"object"==typeof e?e.valueOf():e}function Kh(e,t){let n;if(void 0===t)for(const t of e)null!=t&&(n<t||void 0===n&&t>=t)&&(n=t);else{let r=-1;for(let i of e)null!=(i=t(i,++r,e))&&(n<i||void 0===n&&i>=i)&&(n=i)}return n}function Qh(e,t){let n;if(void 0===t)for(const t of e)null!=t&&(n>t||void 0===n&&t>=t)&&(n=t);else{let r=-1;for(let i of e)null!=(i=t(i,++r,e))&&(n>i||void 0===n&&i>=i)&&(n=i)}return n}function Zh(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function Jh(e,t,n){if("function"==typeof e?e===t:e.has(t))return arguments.length<3?t:n;throw new TypeError("Private element is not present on this object")}function ed(e,t){return e.get(Jh(e,t))}function td(e,t,n){(function(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")})(e,t),t.set(e,n)}function nd(e,t,n){return e.set(Jh(e,t),n),n}function rd(e,t,n){return t&&function(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,ad(r.key),r)}}(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function id(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,s,a,o=[],l=!0,u=!1;try{if(s=(n=n.call(e)).next,0===t);else for(;!(l=(r=s.call(n)).done)&&(o.push(r.value),o.length!==t);l=!0);}catch(e){u=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(u)throw i}}return o}}(e,t)||od(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 sd(e){return function(e){if(Array.isArray(e))return Zh(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||od(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 ad(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t);if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e,"string");return"symbol"==typeof t?t:t+""}function od(e,t){if(e){if("string"==typeof e)return Zh(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Zh(e,t):void 0}}var ld=new WeakMap,ud=new WeakMap,cd=new WeakMap,hd=new WeakMap,dd=new WeakMap,pd=new WeakMap,fd=function(){return rd(function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),td(this,ld,new Map),td(this,ud,new Map),td(this,cd,function(e){return e}),td(this,hd,function(){return{}}),td(this,dd,function(){}),td(this,pd,function(){})},[{key:"getObj",value:function(e){return ed(ld,this).get(ed(cd,this).call(this,e))}},{key:"getData",value:function(e){return ed(ud,this).get(e)}},{key:"entries",value:function(){return sd(ed(ud,this).entries()).map(function(e){var t=id(e,2),n=t[0];return[t[1],n]})}},{key:"id",value:function(e){return nd(cd,this,Xh(e)),this}},{key:"onCreateObj",value:function(e){return nd(hd,this,e),this}},{key:"onUpdateObj",value:function(e){return nd(dd,this,e),this}},{key:"onRemoveObj",value:function(e){return nd(pd,this,e),this}},{key:"digest",value:function(e){var t=this;e.filter(function(e){return!ed(ld,t).has(ed(cd,t).call(t,e))}).forEach(function(e){var n=ed(hd,t).call(t,e);ed(ld,t).set(ed(cd,t).call(t,e),n),ed(ud,t).set(n,e)});var n=new Map(e.map(function(e){return[ed(cd,t).call(t,e),e]}));return ed(ld,this).forEach(function(e,r){n.has(r)?ed(dd,t).call(t,e,n.get(r)):(ed(pd,t).call(t,e,r),ed(ld,t).delete(r),ed(ud,t).delete(e))}),this}},{key:"clear",value:function(){return this.digest([]),this}}])}();function md(e,t){switch(arguments.length){case 0:break;case 1:this.range(e);break;default:this.range(t).domain(e)}return this}const gd=Symbol("implicit");var _d=function(e){for(var t=e.length/6|0,n=new Array(t),r=0;r<t;)n[r]="#"+e.slice(6*r,6*++r);return n}("a6cee31f78b4b2df8a33a02cfb9a99e31a1cfdbf6fff7f00cab2d66a3d9affff99b15928");function vd(e){return vd="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},vd(e)}var yd=/^\s+/,xd=/\s+$/;function bd(e,t){if(t=t||{},(e=e||"")instanceof bd)return e;if(!(this instanceof bd))return new bd(e,t);var n=function(e){var t={r:0,g:0,b:0},n=1,r=null,i=null,s=null,a=!1,o=!1;"string"==typeof e&&(e=function(e){e=e.replace(yd,"").replace(xd,"").toLowerCase();var t,n=!1;if(Bd[e])e=Bd[e],n=!0;else if("transparent"==e)return{r:0,g:0,b:0,a:0,format:"name"};if(t=Qd.rgb.exec(e))return{r:t[1],g:t[2],b:t[3]};if(t=Qd.rgba.exec(e))return{r:t[1],g:t[2],b:t[3],a:t[4]};if(t=Qd.hsl.exec(e))return{h:t[1],s:t[2],l:t[3]};if(t=Qd.hsla.exec(e))return{h:t[1],s:t[2],l:t[3],a:t[4]};if(t=Qd.hsv.exec(e))return{h:t[1],s:t[2],v:t[3]};if(t=Qd.hsva.exec(e))return{h:t[1],s:t[2],v:t[3],a:t[4]};if(t=Qd.hex8.exec(e))return{r:Hd(t[1]),g:Hd(t[2]),b:Hd(t[3]),a:qd(t[4]),format:n?"name":"hex8"};if(t=Qd.hex6.exec(e))return{r:Hd(t[1]),g:Hd(t[2]),b:Hd(t[3]),format:n?"name":"hex"};if(t=Qd.hex4.exec(e))return{r:Hd(t[1]+""+t[1]),g:Hd(t[2]+""+t[2]),b:Hd(t[3]+""+t[3]),a:qd(t[4]+""+t[4]),format:n?"name":"hex8"};if(t=Qd.hex3.exec(e))return{r:Hd(t[1]+""+t[1]),g:Hd(t[2]+""+t[2]),b:Hd(t[3]+""+t[3]),format:n?"name":"hex"};return!1}(e));"object"==vd(e)&&(Zd(e.r)&&Zd(e.g)&&Zd(e.b)?(t=function(e,t,n){return{r:255*Vd(e,255),g:255*Vd(t,255),b:255*Vd(n,255)}}(e.r,e.g,e.b),a=!0,o="%"===String(e.r).substr(-1)?"prgb":"rgb"):Zd(e.h)&&Zd(e.s)&&Zd(e.v)?(r=Wd(e.s),i=Wd(e.v),t=function(e,t,n){e=6*Vd(e,360),t=Vd(t,100),n=Vd(n,100);var r=Math.floor(e),i=e-r,s=n*(1-t),a=n*(1-i*t),o=n*(1-(1-i)*t),l=r%6,u=[n,a,s,s,o,n][l],c=[o,n,n,a,s,s][l],h=[s,s,o,n,n,a][l];return{r:255*u,g:255*c,b:255*h}}(e.h,r,i),a=!0,o="hsv"):Zd(e.h)&&Zd(e.s)&&Zd(e.l)&&(r=Wd(e.s),s=Wd(e.l),t=function(e,t,n){var r,i,s;function a(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+(t-e)*(2/3-n)*6:e}if(e=Vd(e,360),t=Vd(t,100),n=Vd(n,100),0===t)r=i=s=n;else{var o=n<.5?n*(1+t):n+t-n*t,l=2*n-o;r=a(l,o,e+1/3),i=a(l,o,e),s=a(l,o,e-1/3)}return{r:255*r,g:255*i,b:255*s}}(e.h,r,s),a=!0,o="hsl"),e.hasOwnProperty("a")&&(n=e.a));return n=zd(n),{ok:a,format:e.format||o,r:Math.min(255,Math.max(t.r,0)),g:Math.min(255,Math.max(t.g,0)),b:Math.min(255,Math.max(t.b,0)),a:n}}(e);this._originalInput=e,this._r=n.r,this._g=n.g,this._b=n.b,this._a=n.a,this._roundA=Math.round(100*this._a)/100,this._format=t.format||n.format,this._gradientType=t.gradientType,this._r<1&&(this._r=Math.round(this._r)),this._g<1&&(this._g=Math.round(this._g)),this._b<1&&(this._b=Math.round(this._b)),this._ok=n.ok}function Td(e,t,n){e=Vd(e,255),t=Vd(t,255),n=Vd(n,255);var r,i,s=Math.max(e,t,n),a=Math.min(e,t,n),o=(s+a)/2;if(s==a)r=i=0;else{var l=s-a;switch(i=o>.5?l/(2-s-a):l/(s+a),s){case e:r=(t-n)/l+(t<n?6:0);break;case t:r=(n-e)/l+2;break;case n:r=(e-t)/l+4}r/=6}return{h:r,s:i,l:o}}function Sd(e,t,n){e=Vd(e,255),t=Vd(t,255),n=Vd(n,255);var r,i,s=Math.max(e,t,n),a=Math.min(e,t,n),o=s,l=s-a;if(i=0===s?0:l/s,s==a)r=0;else{switch(s){case e:r=(t-n)/l+(t<n?6:0);break;case t:r=(n-e)/l+2;break;case n:r=(e-t)/l+4}r/=6}return{h:r,s:i,v:o}}function Md(e,t,n,r){var i=[jd(Math.round(e).toString(16)),jd(Math.round(t).toString(16)),jd(Math.round(n).toString(16))];return r&&i[0].charAt(0)==i[0].charAt(1)&&i[1].charAt(0)==i[1].charAt(1)&&i[2].charAt(0)==i[2].charAt(1)?i[0].charAt(0)+i[1].charAt(0)+i[2].charAt(0):i.join("")}function wd(e,t,n,r){return[jd(Xd(r)),jd(Math.round(e).toString(16)),jd(Math.round(t).toString(16)),jd(Math.round(n).toString(16))].join("")}function Ed(e,t){t=0===t?0:t||10;var n=bd(e).toHsl();return n.s-=t/100,n.s=Gd(n.s),bd(n)}function Ad(e,t){t=0===t?0:t||10;var n=bd(e).toHsl();return n.s+=t/100,n.s=Gd(n.s),bd(n)}function Rd(e){return bd(e).desaturate(100)}function Cd(e,t){t=0===t?0:t||10;var n=bd(e).toHsl();return n.l+=t/100,n.l=Gd(n.l),bd(n)}function Nd(e,t){t=0===t?0:t||10;var n=bd(e).toRgb();return n.r=Math.max(0,Math.min(255,n.r-Math.round(-t/100*255))),n.g=Math.max(0,Math.min(255,n.g-Math.round(-t/100*255))),n.b=Math.max(0,Math.min(255,n.b-Math.round(-t/100*255))),bd(n)}function Pd(e,t){t=0===t?0:t||10;var n=bd(e).toHsl();return n.l-=t/100,n.l=Gd(n.l),bd(n)}function Ld(e,t){var n=bd(e).toHsl(),r=(n.h+t)%360;return n.h=r<0?360+r:r,bd(n)}function Dd(e){var t=bd(e).toHsl();return t.h=(t.h+180)%360,bd(t)}function Id(e,t){if(isNaN(t)||t<=0)throw new Error("Argument to polyad must be a positive number");for(var n=bd(e).toHsl(),r=[bd(e)],i=360/t,s=1;s<t;s++)r.push(bd({h:(n.h+s*i)%360,s:n.s,l:n.l}));return r}function Ud(e){var t=bd(e).toHsl(),n=t.h;return[bd(e),bd({h:(n+72)%360,s:t.s,l:t.l}),bd({h:(n+216)%360,s:t.s,l:t.l})]}function Od(e,t,n){t=t||6,n=n||30;var r=bd(e).toHsl(),i=360/n,s=[bd(e)];for(r.h=(r.h-(i*t>>1)+720)%360;--t;)r.h=(r.h+i)%360,s.push(bd(r));return s}function Fd(e,t){t=t||6;for(var n=bd(e).toHsv(),r=n.h,i=n.s,s=n.v,a=[],o=1/t;t--;)a.push(bd({h:r,s:i,v:s})),s=(s+o)%1;return a}bd.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var e=this.toRgb();return(299*e.r+587*e.g+114*e.b)/1e3},getLuminance:function(){var e,t,n,r=this.toRgb();return e=r.r/255,t=r.g/255,n=r.b/255,.2126*(e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4))+.7152*(t<=.03928?t/12.92:Math.pow((t+.055)/1.055,2.4))+.0722*(n<=.03928?n/12.92:Math.pow((n+.055)/1.055,2.4))},setAlpha:function(e){return this._a=zd(e),this._roundA=Math.round(100*this._a)/100,this},toHsv:function(){var e=Sd(this._r,this._g,this._b);return{h:360*e.h,s:e.s,v:e.v,a:this._a}},toHsvString:function(){var e=Sd(this._r,this._g,this._b),t=Math.round(360*e.h),n=Math.round(100*e.s),r=Math.round(100*e.v);return 1==this._a?"hsv("+t+", "+n+"%, "+r+"%)":"hsva("+t+", "+n+"%, "+r+"%, "+this._roundA+")"},toHsl:function(){var e=Td(this._r,this._g,this._b);return{h:360*e.h,s:e.s,l:e.l,a:this._a}},toHslString:function(){var e=Td(this._r,this._g,this._b),t=Math.round(360*e.h),n=Math.round(100*e.s),r=Math.round(100*e.l);return 1==this._a?"hsl("+t+", "+n+"%, "+r+"%)":"hsla("+t+", "+n+"%, "+r+"%, "+this._roundA+")"},toHex:function(e){return Md(this._r,this._g,this._b,e)},toHexString:function(e){return"#"+this.toHex(e)},toHex8:function(e){return function(e,t,n,r,i){var s=[jd(Math.round(e).toString(16)),jd(Math.round(t).toString(16)),jd(Math.round(n).toString(16)),jd(Xd(r))];if(i&&s[0].charAt(0)==s[0].charAt(1)&&s[1].charAt(0)==s[1].charAt(1)&&s[2].charAt(0)==s[2].charAt(1)&&s[3].charAt(0)==s[3].charAt(1))return s[0].charAt(0)+s[1].charAt(0)+s[2].charAt(0)+s[3].charAt(0);return s.join("")}(this._r,this._g,this._b,this._a,e)},toHex8String:function(e){return"#"+this.toHex8(e)},toRgb:function(){return{r:Math.round(this._r),g:Math.round(this._g),b:Math.round(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+Math.round(this._r)+", "+Math.round(this._g)+", "+Math.round(this._b)+")":"rgba("+Math.round(this._r)+", "+Math.round(this._g)+", "+Math.round(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:Math.round(100*Vd(this._r,255))+"%",g:Math.round(100*Vd(this._g,255))+"%",b:Math.round(100*Vd(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+Math.round(100*Vd(this._r,255))+"%, "+Math.round(100*Vd(this._g,255))+"%, "+Math.round(100*Vd(this._b,255))+"%)":"rgba("+Math.round(100*Vd(this._r,255))+"%, "+Math.round(100*Vd(this._g,255))+"%, "+Math.round(100*Vd(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":!(this._a<1)&&(kd[Md(this._r,this._g,this._b,!0)]||!1)},toFilter:function(e){var t="#"+wd(this._r,this._g,this._b,this._a),n=t,r=this._gradientType?"GradientType = 1, ":"";if(e){var i=bd(e);n="#"+wd(i._r,i._g,i._b,i._a)}return"progid:DXImageTransform.Microsoft.gradient("+r+"startColorstr="+t+",endColorstr="+n+")"},toString:function(e){var t=!!e;e=e||this._format;var n=!1,r=this._a<1&&this._a>=0;return t||!r||"hex"!==e&&"hex6"!==e&&"hex3"!==e&&"hex4"!==e&&"hex8"!==e&&"name"!==e?("rgb"===e&&(n=this.toRgbString()),"prgb"===e&&(n=this.toPercentageRgbString()),"hex"!==e&&"hex6"!==e||(n=this.toHexString()),"hex3"===e&&(n=this.toHexString(!0)),"hex4"===e&&(n=this.toHex8String(!0)),"hex8"===e&&(n=this.toHex8String()),"name"===e&&(n=this.toName()),"hsl"===e&&(n=this.toHslString()),"hsv"===e&&(n=this.toHsvString()),n||this.toHexString()):"name"===e&&0===this._a?this.toName():this.toRgbString()},clone:function(){return bd(this.toString())},_applyModification:function(e,t){var n=e.apply(null,[this].concat([].slice.call(t)));return this._r=n._r,this._g=n._g,this._b=n._b,this.setAlpha(n._a),this},lighten:function(){return this._applyModification(Cd,arguments)},brighten:function(){return this._applyModification(Nd,arguments)},darken:function(){return this._applyModification(Pd,arguments)},desaturate:function(){return this._applyModification(Ed,arguments)},saturate:function(){return this._applyModification(Ad,arguments)},greyscale:function(){return this._applyModification(Rd,arguments)},spin:function(){return this._applyModification(Ld,arguments)},_applyCombination:function(e,t){return e.apply(null,[this].concat([].slice.call(t)))},analogous:function(){return this._applyCombination(Od,arguments)},complement:function(){return this._applyCombination(Dd,arguments)},monochromatic:function(){return this._applyCombination(Fd,arguments)},splitcomplement:function(){return this._applyCombination(Ud,arguments)},triad:function(){return this._applyCombination(Id,[3])},tetrad:function(){return this._applyCombination(Id,[4])}},bd.fromRatio=function(e,t){if("object"==vd(e)){var n={};for(var r in e)e.hasOwnProperty(r)&&(n[r]="a"===r?e[r]:Wd(e[r]));e=n}return bd(e,t)},bd.equals=function(e,t){return!(!e||!t)&&bd(e).toRgbString()==bd(t).toRgbString()},bd.random=function(){return bd.fromRatio({r:Math.random(),g:Math.random(),b:Math.random()})},bd.mix=function(e,t,n){n=0===n?0:n||50;var r=bd(e).toRgb(),i=bd(t).toRgb(),s=n/100;return bd({r:(i.r-r.r)*s+r.r,g:(i.g-r.g)*s+r.g,b:(i.b-r.b)*s+r.b,a:(i.a-r.a)*s+r.a})},
|
|
3
3
|
// <http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef (WCAG Version 2)
|
|
4
4
|
// Analyze the 2 colors and returns the color contrast defined by (WCAG Version 2)
|
|
5
|
-
bd.readability=function(e,t){var n=bd(e),r=bd(t);return(Math.max(n.getLuminance(),r.getLuminance())+.05)/(Math.min(n.getLuminance(),r.getLuminance())+.05)},bd.isReadable=function(e,t,n){var r,i,s=bd.readability(e,t);switch(i=!1,(r=function(e){var t,n;t=((e=e||{level:"AA",size:"small"}).level||"AA").toUpperCase(),n=(e.size||"small").toLowerCase(),"AA"!==t&&"AAA"!==t&&(t="AA");"small"!==n&&"large"!==n&&(n="small");return{level:t,size:n}}(n)).level+r.size){case"AAsmall":case"AAAlarge":i=s>=4.5;break;case"AAlarge":i=s>=3;break;case"AAAsmall":i=s>=7}return i},bd.mostReadable=function(e,t,n){var r,i,s,a,o=null,l=0;i=(n=n||{}).includeFallbackColors,s=n.level,a=n.size;for(var u=0;u<t.length;u++)(r=bd.readability(e,t[u]))>l&&(l=r,o=bd(t[u]));return bd.isReadable(e,o,{level:s,size:a})||!i?o:(n.includeFallbackColors=!1,bd.mostReadable(e,["#fff","#000"],n))};var Bd=bd.names={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"0ff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"00f",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",burntsienna:"ea7e5d",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"0ff",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:"f0f",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:"663399",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"},kd=bd.hexNames=function(e){var t={};for(var n in e)e.hasOwnProperty(n)&&(t[e[n]]=n);return t}(Bd);function zd(e){return e=parseFloat(e),(isNaN(e)||e<0||e>1)&&(e=1),e}function Vd(e,t){(function(e){return"string"==typeof e&&-1!=e.indexOf(".")&&1===parseFloat(e)})(e)&&(e="100%");var n=function(e){return"string"==typeof e&&-1!=e.indexOf("%")}(e);return e=Math.min(t,Math.max(0,parseFloat(e))),n&&(e=parseInt(e*t,10)/100),Math.abs(e-t)<1e-6?1:e%t/parseFloat(t)}function Gd(e){return Math.min(1,Math.max(0,e))}function Hd(e){return parseInt(e,16)}function jd(e){return 1==e.length?"0"+e:""+e}function Wd(e){return e<=1&&(e=100*e+"%"),e}function Xd(e){return Math.round(255*parseFloat(e)).toString(16)}function qd(e){return Hd(e)/255}var $d,Yd,Kd,Qd=(Yd="[\\s|\\(]+("+($d="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)")+")[,|\\s]+("+$d+")[,|\\s]+("+$d+")\\s*\\)?",Kd="[\\s|\\(]+("+$d+")[,|\\s]+("+$d+")[,|\\s]+("+$d+")[,|\\s]+("+$d+")\\s*\\)?",{CSS_UNIT:new RegExp($d),rgb:new RegExp("rgb"+Yd),rgba:new RegExp("rgba"+Kd),hsl:new RegExp("hsl"+Yd),hsla:new RegExp("hsla"+Kd),hsv:new RegExp("hsv"+Yd),hsva:new RegExp("hsva"+Kd),hex3:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex6:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,hex4:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex8:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/});function Zd(e){return!!Qd.CSS_UNIT.exec(e)}function Jd(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function ep(e,t,n){if("function"==typeof e?e===t:e.has(t))return arguments.length<3?t:n;throw new TypeError("Private element is not present on this object")}function tp(e,t,n){return t=cp(t),function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,dp()?Reflect.construct(t,n||[],cp(e).constructor):t.apply(e,n))}function np(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function rp(e,t){return e.get(ep(e,t))}function ip(e,t,n){(function(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")})(e,t),t.set(e,n)}function sp(e,t,n){return e.set(ep(e,t),n),n}function ap(e,t,n){if(dp())return Reflect.construct.apply(null,arguments);var r=[null];return r.push.apply(r,t),new(e.bind.apply(e,r))}function op(e,t,n){return t&&function(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,vp(r.key),r)}}(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function lp(e,t,n){return(t=vp(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function up(){return up="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,n){var r=function(e,t){for(;!{}.hasOwnProperty.call(e,t)&&null!==(e=cp(e)););return e}(e,t);if(r){var i=Object.getOwnPropertyDescriptor(r,t);return i.get?i.get.call(arguments.length<3?e:n):i.value}},up.apply(null,arguments)}function cp(e){return cp=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},cp(e)}function hp(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&fp(e,t)}function dp(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(dp=function(){return!!e})()}function pp(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function fp(e,t){return fp=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},fp(e,t)}function mp(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,s,a,o=[],l=!0,u=!1;try{if(s=(n=n.call(e)).next,0===t);else for(;!(l=(r=s.call(n)).done)&&(o.push(r.value),o.length!==t);l=!0);}catch(e){u=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(u)throw i}}return o}}(e,t)||xp(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 gp(e,t,n,r){var i=up(cp(e.prototype),t,n);return"function"==typeof i?function(e){return i.apply(n,e)}:i}function _p(e){return function(e){if(Array.isArray(e))return Jd(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||xp(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 vp(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t);if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}function yp(e){return yp="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},yp(e)}function xp(e,t){if(e){if("string"==typeof e)return Jd(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Jd(e,t):void 0}}var bp=function(e){e instanceof Array?e.forEach(bp):(e.map&&e.map.dispose(),e.dispose())},Tp=function(e){e.geometry&&e.geometry.dispose(),e.material&&bp(e.material),e.texture&&e.texture.dispose(),e.children&&e.children.forEach(Tp)},Sp=function(e){for(;e.children.length;){var t=e.children[0];e.remove(t),Tp(t)}},Mp=new WeakMap,wp=new WeakMap,Ep=function(e){function t(e){var n,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=r.dataBindAttr,s=void 0===i?"__data":i,a=r.objBindAttr,o=void 0===a?"__threeObj":a;return np(this,t),lp(n=tp(this,t),"scene",void 0),ip(n,Mp,void 0),ip(n,wp,void 0),n.scene=e,sp(Mp,n,s),sp(wp,n,o),n.onRemoveObj(function(){}),n}return hp(t,e),op(t,[{key:"onCreateObj",value:function(e){var n=this;return gp(t,"onCreateObj",this)([function(t){var r=e(t);return t[rp(wp,n)]=r,r[rp(Mp,n)]=t,n.scene.add(r),r}]),this}},{key:"onRemoveObj",value:function(e){var n=this;return gp(t,"onRemoveObj",this)([function(r,i){var s=gp(t,"getData",n)([r]);e(r,i),n.scene.remove(r),Sp(r),delete s[rp(wp,n)]}]),this}}])}(fd),Ap=function(e){return isNaN(e)?parseInt(bd(e).toHex(),16):e},Rp=function(e){return isNaN(e)?bd(e).getAlpha():1},Cp=function e(){var t=new qh,n=[],r=[],i=gd;function s(e){let s=t.get(e);if(void 0===s){if(i!==gd)return i;t.set(e,s=n.push(e)-1)}return r[s%r.length]}return s.domain=function(e){if(!arguments.length)return n.slice();n=[],t=new qh;for(const r of e)t.has(r)||t.set(r,n.push(r)-1);return s},s.range=function(e){return arguments.length?(r=Array.from(e),s):r.slice()},s.unknown=function(e){return arguments.length?(i=e,s):i},s.copy=function(){return e(n,r).unknown(i)},md.apply(s,arguments),s}(_d);function Np(e,t,n){t&&"string"==typeof n&&e.filter(function(e){return!e[n]}).forEach(function(e){e[n]=Cp(t(e))})}var Pp=window.THREE?window.THREE:{Group:Ci,Mesh:di,MeshLambertMaterial:Ls,Color:Nr,BufferGeometry:ei,BufferAttribute:Gr,Matrix4:Bn,Vector3:Ut,SphereGeometry:Ms,CylinderGeometry:ls,TubeGeometry:ws,ConeGeometry:us,Line:class extends hr{constructor(e=new ei,t=new Ki){super(),this.isLine=!0,this.type="Line",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}computeLineDistances(){const e=this.geometry;if(null===e.index){const t=e.attributes.position,n=[0];for(let e=1,r=t.count;e<r;e++)Qi.fromBufferAttribute(t,e-1),Zi.fromBufferAttribute(t,e),n[e]=n[e-1],n[e]+=Qi.distanceTo(Zi);e.setAttribute("lineDistance",new Xr(n,1))}else console.warn("THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast(e,t){const n=this.geometry,r=this.matrixWorld,i=e.params.Line.threshold,s=n.drawRange;if(null===n.boundingSphere&&n.computeBoundingSphere(),ts.copy(n.boundingSphere),ts.applyMatrix4(r),ts.radius+=i,!1===e.ray.intersectsSphere(ts))return;Ji.copy(r).invert(),es.copy(e.ray).applyMatrix4(Ji);const a=i/((this.scale.x+this.scale.y+this.scale.z)/3),o=a*a,l=this.isLineSegments?2:1,u=n.index,c=n.attributes.position;if(null!==u){const n=Math.max(0,s.start),r=Math.min(u.count,s.start+s.count);for(let i=n,s=r-1;i<s;i+=l){const n=u.getX(i),r=u.getX(i+1),s=is(this,e,es,o,n,r,i);s&&t.push(s)}if(this.isLineLoop){const i=u.getX(r-1),s=u.getX(n),a=is(this,e,es,o,i,s,r-1);a&&t.push(a)}}else{const n=Math.max(0,s.start),r=Math.min(c.count,s.start+s.count);for(let i=n,s=r-1;i<s;i+=l){const n=is(this,e,es,o,i,i+1,i);n&&t.push(n)}if(this.isLineLoop){const i=is(this,e,es,o,r-1,n,r-1);i&&t.push(i)}}}updateMorphTargets(){const e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){const n=e[t[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e<t;e++){const t=n[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}},LineBasicMaterial:Ki,QuadraticBezierCurve3:bs,CubicBezierCurve3:xs,Box3:hn},Lp={graph:jc,forcelayout:gh},Dp=(new Pp.BufferGeometry).setAttribute?"setAttribute":"addAttribute",Ip=(new Pp.BufferGeometry).applyMatrix4?"applyMatrix4":"applyMatrix",Up=Wh({props:{jsonUrl:{onChange:function(e,t){var n=this;e&&!t.fetchingJson&&(t.fetchingJson=!0,t.onLoading(),fetch(e).then(function(e){return e.json()}).then(function(e){t.fetchingJson=!1,t.onFinishLoading(e),n.graphData(e)}))},triggerUpdate:!1},graphData:{default:{nodes:[],links:[]},onChange:function(e,t){t.engineRunning=!1}},numDimensions:{default:3,onChange:function(e,t){var n=t.d3ForceLayout.force("charge");function r(e,t){e.forEach(function(e){delete e[t],delete e["v".concat(t)]})}n&&n.strength(e>2?-60:-30),e<3&&r(t.graphData.nodes,"z"),e<2&&r(t.graphData.nodes,"y")}},dagMode:{onChange:function(e,t){!e&&"d3"===t.forceEngine&&(t.graphData.nodes||[]).forEach(function(e){return e.fx=e.fy=e.fz=void 0})}},dagLevelDistance:{},dagNodeFilter:{default:function(e){return!0}},onDagError:{triggerUpdate:!1},nodeRelSize:{default:4},nodeId:{default:"id"},nodeVal:{default:"val"},nodeResolution:{default:8},nodeColor:{default:"color"},nodeAutoColorBy:{},nodeOpacity:{default:.75},nodeVisibility:{default:!0},nodeThreeObject:{},nodeThreeObjectExtend:{default:!1},nodePositionUpdate:{triggerUpdate:!1},linkSource:{default:"source"},linkTarget:{default:"target"},linkVisibility:{default:!0},linkColor:{default:"color"},linkAutoColorBy:{},linkOpacity:{default:.2},linkWidth:{},linkResolution:{default:6},linkCurvature:{default:0,triggerUpdate:!1},linkCurveRotation:{default:0,triggerUpdate:!1},linkMaterial:{},linkThreeObject:{},linkThreeObjectExtend:{default:!1},linkPositionUpdate:{triggerUpdate:!1},linkDirectionalArrowLength:{default:0},linkDirectionalArrowColor:{},linkDirectionalArrowRelPos:{default:.5,triggerUpdate:!1},linkDirectionalArrowResolution:{default:8},linkDirectionalParticles:{default:0},linkDirectionalParticleSpeed:{default:.01,triggerUpdate:!1},linkDirectionalParticleOffset:{default:0,triggerUpdate:!1},linkDirectionalParticleWidth:{default:.5},linkDirectionalParticleColor:{},linkDirectionalParticleResolution:{default:4},linkDirectionalParticleThreeObject:{},forceEngine:{default:"d3"},d3AlphaMin:{default:0},d3AlphaDecay:{default:.0228,triggerUpdate:!1,onChange:function(e,t){t.d3ForceLayout.alphaDecay(e)}},d3AlphaTarget:{default:0,triggerUpdate:!1,onChange:function(e,t){t.d3ForceLayout.alphaTarget(e)}},d3VelocityDecay:{default:.4,triggerUpdate:!1,onChange:function(e,t){t.d3ForceLayout.velocityDecay(e)}},ngraphPhysics:{default:{timeStep:20,gravity:-1.2,theta:.8,springLength:30,springCoefficient:8e-4,dragCoefficient:.02}},warmupTicks:{default:0,triggerUpdate:!1},cooldownTicks:{default:1/0,triggerUpdate:!1},cooldownTime:{default:15e3,triggerUpdate:!1},onLoading:{default:function(){},triggerUpdate:!1},onFinishLoading:{default:function(){},triggerUpdate:!1},onUpdate:{default:function(){},triggerUpdate:!1},onFinishUpdate:{default:function(){},triggerUpdate:!1},onEngineTick:{default:function(){},triggerUpdate:!1},onEngineStop:{default:function(){},triggerUpdate:!1}},methods:{refresh:function(e){return e._flushObjects=!0,e._rerender(),this},d3Force:function(e,t,n){return void 0===n?e.d3ForceLayout.force(t):(e.d3ForceLayout.force(t,n),this)},d3ReheatSimulation:function(e){return e.d3ForceLayout.alpha(1),this.resetCountdown(),this},resetCountdown:function(e){return e.cntTicks=0,e.startTickTime=new Date,e.engineRunning=!0,this},tickFrame:function(e){var t,n,r,i,s,a="ngraph"!==e.forceEngine;return e.engineRunning&&function(){++e.cntTicks>e.cooldownTicks||new Date-e.startTickTime>e.cooldownTime||a&&e.d3AlphaMin>0&&e.d3ForceLayout.alpha()<e.d3AlphaMin?(e.engineRunning=!1,e.onEngineStop()):(e.layout[a?"tick":"step"](),e.onEngineTick());var t=Xh(e.nodeThreeObjectExtend);e.nodeDataMapper.entries().forEach(function(n){var r=mp(n,2),i=r[0],s=r[1];if(s){var o=a?i:e.layout.getNodePosition(i[e.nodeId]),l=t(i);e.nodePositionUpdate&&e.nodePositionUpdate(l?s.children[0]:s,{x:o.x,y:o.y,z:o.z},i)&&!l||(s.position.x=o.x,s.position.y=o.y||0,s.position.z=o.z||0)}});var n=Xh(e.linkWidth),r=Xh(e.linkCurvature),i=Xh(e.linkCurveRotation),s=Xh(e.linkThreeObjectExtend);function o(t){var n=a?t:e.layout.getLinkPosition(e.layout.graph.getLink(t.source,t.target).id),s=n[a?"source":"from"],o=n[a?"target":"to"];if(s&&o&&s.hasOwnProperty("x")&&o.hasOwnProperty("x")){var l=r(t);if(l){var u,c=new Pp.Vector3(s.x,s.y||0,s.z||0),h=new Pp.Vector3(o.x,o.y||0,o.z||0),d=c.distanceTo(h),p=i(t);if(d>0){var f=o.x-s.x,m=o.y-s.y||0,g=(new Pp.Vector3).subVectors(h,c),_=g.clone().multiplyScalar(l).cross(0!==f||0!==m?new Pp.Vector3(0,0,1):new Pp.Vector3(0,1,0)).applyAxisAngle(g.normalize(),p).add((new Pp.Vector3).addVectors(c,h).divideScalar(2));u=new Pp.QuadraticBezierCurve3(c,_,h)}else{var v=70*l,y=-p,x=y+Math.PI/2;u=new Pp.CubicBezierCurve3(c,new Pp.Vector3(v*Math.cos(x),v*Math.sin(x),0).add(c),new Pp.Vector3(v*Math.cos(y),v*Math.sin(y),0).add(c),h)}t.__curve=u}else t.__curve=null}}e.linkDataMapper.entries().forEach(function(t){var r=mp(t,2),i=r[0],l=r[1];if(l){var u=a?i:e.layout.getLinkPosition(e.layout.graph.getLink(i.source,i.target).id),c=u[a?"source":"from"],h=u[a?"target":"to"];if(c&&h&&c.hasOwnProperty("x")&&h.hasOwnProperty("x")){o(i);var d=s(i);if(!e.linkPositionUpdate||!e.linkPositionUpdate(d?l.children[1]:l,{start:{x:c.x,y:c.y,z:c.z},end:{x:h.x,y:h.y,z:h.z}},i)||d){var p=30,f=i.__curve,m=l.children.length?l.children[0]:l;if("Line"===m.type){if(f){var g=f.getPoints(p);m.geometry.getAttribute("position").array.length!==3*g.length&&m.geometry[Dp]("position",new Pp.BufferAttribute(new Float32Array(3*g.length),3)),m.geometry.setFromPoints(g)}else{var _=m.geometry.getAttribute("position");_&&_.array&&6===_.array.length||m.geometry[Dp]("position",_=new Pp.BufferAttribute(new Float32Array(6),3)),_.array[0]=c.x,_.array[1]=c.y||0,_.array[2]=c.z||0,_.array[3]=h.x,_.array[4]=h.y||0,_.array[5]=h.z||0,_.needsUpdate=!0}m.geometry.computeBoundingSphere()}else if("Mesh"===m.type)if(f){m.geometry.type.match(/^Tube(Buffer)?Geometry$/)||(m.position.set(0,0,0),m.rotation.set(0,0,0),m.scale.set(1,1,1));var v=Math.ceil(10*n(i))/10/2,y=new Pp.TubeGeometry(f,p,v,e.linkResolution,!1);m.geometry.dispose(),m.geometry=y}else{if(!m.geometry.type.match(/^Cylinder(Buffer)?Geometry$/)){var x=Math.ceil(10*n(i))/10/2,b=new Pp.CylinderGeometry(x,x,1,e.linkResolution,1,!1);b[Ip]((new Pp.Matrix4).makeTranslation(0,.5,0)),b[Ip]((new Pp.Matrix4).makeRotationX(Math.PI/2)),m.geometry.dispose(),m.geometry=b}var T=new Pp.Vector3(c.x,c.y||0,c.z||0),S=new Pp.Vector3(h.x,h.y||0,h.z||0),M=T.distanceTo(S);m.position.x=T.x,m.position.y=T.y,m.position.z=T.z,m.scale.z=M,m.parent.localToWorld(S),m.lookAt(S)}}}}})}(),t=Xh(e.linkDirectionalArrowRelPos),n=Xh(e.linkDirectionalArrowLength),r=Xh(e.nodeVal),e.arrowDataMapper.entries().forEach(function(i){var s=mp(i,2),o=s[0],l=s[1];if(l){var u=a?o:e.layout.getLinkPosition(e.layout.graph.getLink(o.source,o.target).id),c=u[a?"source":"from"],h=u[a?"target":"to"];if(c&&h&&c.hasOwnProperty("x")&&h.hasOwnProperty("x")){var d=Math.cbrt(Math.max(0,r(c)||1))*e.nodeRelSize,p=Math.cbrt(Math.max(0,r(h)||1))*e.nodeRelSize,f=n(o),m=t(o),g=o.__curve?function(e){return o.__curve.getPoint(e)}:function(e){var t=function(e,t,n,r){return t[e]+(n[e]-t[e])*r||0};return{x:t("x",c,h,e),y:t("y",c,h,e),z:t("z",c,h,e)}},_=o.__curve?o.__curve.getLength():Math.sqrt(["x","y","z"].map(function(e){return Math.pow((h[e]||0)-(c[e]||0),2)}).reduce(function(e,t){return e+t},0)),v=d+f+(_-d-p-f)*m,y=g(v/_),x=g((v-f)/_);["x","y","z"].forEach(function(e){return l.position[e]=x[e]});var b=ap(Pp.Vector3,_p(["x","y","z"].map(function(e){return y[e]})));l.parent.localToWorld(b),l.lookAt(b)}}}),i=Xh(e.linkDirectionalParticleSpeed),s=Xh(e.linkDirectionalParticleOffset),e.graphData.links.forEach(function(t){var n=e.particlesDataMapper.getObj(t),r=n&&n.children,o=t.__singleHopPhotonsObj&&t.__singleHopPhotonsObj.children;if(o&&o.length||r&&r.length){var l=a?t:e.layout.getLinkPosition(e.layout.graph.getLink(t.source,t.target).id),u=l[a?"source":"from"],c=l[a?"target":"to"];if(u&&c&&u.hasOwnProperty("x")&&c.hasOwnProperty("x")){var h=i(t),d=Math.abs(s(t)),p=t.__curve?function(e){return t.__curve.getPoint(e)}:function(e){var t=function(e,t,n,r){return t[e]+(n[e]-t[e])*r||0};return{x:t("x",u,c,e),y:t("y",u,c,e),z:t("z",u,c,e)}};[].concat(_p(r||[]),_p(o||[])).forEach(function(e,t){var n="singleHopPhotons"===e.parent.__linkThreeObjType;if(e.hasOwnProperty("__progressRatio")||(e.__progressRatio=n?0:(t+d)/r.length),e.__progressRatio+=h,e.__progressRatio>=1){if(n)return e.parent.remove(e),void Sp(e);e.__progressRatio=e.__progressRatio%1}var i=e.__progressRatio,s=p(i);"SphereGeometry"!==e.geometry.type&&e.lookAt(s.x,s.y,s.z),["x","y","z"].forEach(function(t){return e.position[t]=s[t]})})}}}),this},emitParticle:function(e,t){if(t&&e.graphData.links.includes(t)){if(!t.__singleHopPhotonsObj){var n=new Pp.Group;n.__linkThreeObjType="singleHopPhotons",t.__singleHopPhotonsObj=n,e.graphScene.add(n)}var r=Xh(e.linkDirectionalParticleThreeObject)(t);if(r&&e.linkDirectionalParticleThreeObject===r&&(r=r.clone()),!r){var i=Xh(e.linkDirectionalParticleWidth),s=Math.ceil(10*i(t))/10/2,a=e.linkDirectionalParticleResolution,o=new Pp.SphereGeometry(s,a,a),l=Xh(e.linkColor),u=Xh(e.linkDirectionalParticleColor)(t)||l(t)||"#f0f0f0",c=new Pp.Color(Ap(u)),h=3*e.linkOpacity,d=new Pp.MeshLambertMaterial({color:c,transparent:!0,opacity:h});r=new Pp.Mesh(o,d)}t.__singleHopPhotonsObj.add(r)}return this},getGraphBbox:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(){return!0};if(!e.initialised)return null;var n=function e(n){var r=[];if(n.geometry){n.geometry.computeBoundingBox();var i=new Pp.Box3;i.copy(n.geometry.boundingBox).applyMatrix4(n.matrixWorld),r.push(i)}return r.concat.apply(r,_p((n.children||[]).filter(function(e){return!e.hasOwnProperty("__graphObjType")||"node"===e.__graphObjType&&t(e.__data)}).map(e)))}(e.graphScene);return n.length?Object.assign.apply(Object,_p(["x","y","z"].map(function(e){return lp({},e,[Qh(n,function(t){return t.min[e]}),Kh(n,function(t){return t.max[e]})])}))):null}},stateInit:function(){return{d3ForceLayout:Ic().force("link",tc()).force("charge",Uc()).force("center",wu()).force("dagRadial",null).stop(),engineRunning:!1}},init:function(e,t){t.graphScene=e,t.nodeDataMapper=new Ep(e,{objBindAttr:"__threeObj"}),t.linkDataMapper=new Ep(e,{objBindAttr:"__lineObj"}),t.arrowDataMapper=new Ep(e,{objBindAttr:"__arrowObj"}),t.particlesDataMapper=new Ep(e,{objBindAttr:"__photonsObj"})},update:function(e,t){var n=function(e){return e.some(function(e){return t.hasOwnProperty(e)})};if(e.engineRunning=!1,"function"==typeof e.onUpdate&&e.onUpdate(),null!==e.nodeAutoColorBy&&n(["nodeAutoColorBy","graphData","nodeColor"])&&Np(e.graphData.nodes,Xh(e.nodeAutoColorBy),e.nodeColor),null!==e.linkAutoColorBy&&n(["linkAutoColorBy","graphData","linkColor"])&&Np(e.graphData.links,Xh(e.linkAutoColorBy),e.linkColor),e._flushObjects||n(["graphData","nodeThreeObject","nodeThreeObjectExtend","nodeVal","nodeColor","nodeVisibility","nodeRelSize","nodeResolution","nodeOpacity"])){var r=Xh(e.nodeThreeObject),i=Xh(e.nodeThreeObjectExtend),s=Xh(e.nodeVal),a=Xh(e.nodeColor),o=Xh(e.nodeVisibility),l={},u={};(e._flushObjects||n(["nodeThreeObject","nodeThreeObjectExtend"]))&&e.nodeDataMapper.clear(),e.nodeDataMapper.onCreateObj(function(t){var n,s=r(t),a=i(t);return s&&e.nodeThreeObject===s&&(s=s.clone()),s&&!a?n=s:((n=new Pp.Mesh).__graphDefaultObj=!0,s&&a&&n.add(s)),n.__graphObjType="node",n}).onUpdateObj(function(t,n){if(t.__graphDefaultObj){var r=s(n)||1,i=Math.cbrt(r)*e.nodeRelSize,o=e.nodeResolution;t.geometry.type.match(/^Sphere(Buffer)?Geometry$/)&&t.geometry.parameters.radius===i&&t.geometry.parameters.widthSegments===o||(l.hasOwnProperty(r)||(l[r]=new Pp.SphereGeometry(i,o,o)),t.geometry.dispose(),t.geometry=l[r]);var c=a(n),h=new Pp.Color(Ap(c||"#ffffaa")),d=e.nodeOpacity*Rp(c);"MeshLambertMaterial"===t.material.type&&t.material.color.equals(h)&&t.material.opacity===d||(u.hasOwnProperty(c)||(u[c]=new Pp.MeshLambertMaterial({color:h,transparent:!0,opacity:d})),t.material.dispose(),t.material=u[c])}}).digest(e.graphData.nodes.filter(o))}if(e._flushObjects||n(["graphData","linkThreeObject","linkThreeObjectExtend","linkMaterial","linkColor","linkWidth","linkVisibility","linkResolution","linkOpacity","linkDirectionalArrowLength","linkDirectionalArrowColor","linkDirectionalArrowResolution","linkDirectionalParticles","linkDirectionalParticleWidth","linkDirectionalParticleColor","linkDirectionalParticleResolution","linkDirectionalParticleThreeObject"])){var c=Xh(e.linkThreeObject),h=Xh(e.linkThreeObjectExtend),d=Xh(e.linkMaterial),p=Xh(e.linkVisibility),f=Xh(e.linkColor),m=Xh(e.linkWidth),g={},_={},v={},y=e.graphData.links.filter(p);if((e._flushObjects||n(["linkThreeObject","linkThreeObjectExtend","linkWidth"]))&&e.linkDataMapper.clear(),e.linkDataMapper.onRemoveObj(function(e){var t=e.__data&&e.__data.__singleHopPhotonsObj;t&&(t.parent.remove(t),Sp(t),delete e.__data.__singleHopPhotonsObj)}).onCreateObj(function(t){var n,r,i=c(t),s=h(t);if(i&&e.linkThreeObject===i&&(i=i.clone()),!i||s)if(!!m(t))n=new Pp.Mesh;else{var a=new Pp.BufferGeometry;a[Dp]("position",new Pp.BufferAttribute(new Float32Array(6),3)),n=new Pp.Line(a)}return i?s?((r=new Pp.Group).__graphDefaultObj=!0,r.add(n),r.add(i)):r=i:(r=n).__graphDefaultObj=!0,r.renderOrder=10,r.__graphObjType="link",r}).onUpdateObj(function(t,n){if(t.__graphDefaultObj){var r=t.children.length?t.children[0]:t,i=Math.ceil(10*m(n))/10,s=!!i;if(s){var a=i/2,o=e.linkResolution;if(!r.geometry.type.match(/^Cylinder(Buffer)?Geometry$/)||r.geometry.parameters.radiusTop!==a||r.geometry.parameters.radialSegments!==o){if(!g.hasOwnProperty(i)){var l=new Pp.CylinderGeometry(a,a,1,o,1,!1);l[Ip]((new Pp.Matrix4).makeTranslation(0,.5,0)),l[Ip]((new Pp.Matrix4).makeRotationX(Math.PI/2)),g[i]=l}r.geometry.dispose(),r.geometry=g[i]}}var u=d(n);if(u)r.material=u;else{var c=f(n),h=new Pp.Color(Ap(c||"#f0f0f0")),p=e.linkOpacity*Rp(c),y=s?"MeshLambertMaterial":"LineBasicMaterial";if(r.material.type!==y||!r.material.color.equals(h)||r.material.opacity!==p){var x=s?_:v;x.hasOwnProperty(c)||(x[c]=new Pp[y]({color:h,transparent:p<1,opacity:p,depthWrite:p>=1})),r.material.dispose(),r.material=x[c]}}}}).digest(y),e.linkDirectionalArrowLength||t.hasOwnProperty("linkDirectionalArrowLength")){var x=Xh(e.linkDirectionalArrowLength),b=Xh(e.linkDirectionalArrowColor);e.arrowDataMapper.onCreateObj(function(){var e=new Pp.Mesh(void 0,new Pp.MeshLambertMaterial({transparent:!0}));return e.__linkThreeObjType="arrow",e}).onUpdateObj(function(t,n){var r=x(n),i=e.linkDirectionalArrowResolution;if(!t.geometry.type.match(/^Cone(Buffer)?Geometry$/)||t.geometry.parameters.height!==r||t.geometry.parameters.radialSegments!==i){var s=new Pp.ConeGeometry(.25*r,r,i);s.translate(0,r/2,0),s.rotateX(Math.PI/2),t.geometry.dispose(),t.geometry=s}var a=b(n)||f(n)||"#f0f0f0";t.material.color=new Pp.Color(Ap(a)),t.material.opacity=3*e.linkOpacity*Rp(a)}).digest(y.filter(x))}if(e.linkDirectionalParticles||t.hasOwnProperty("linkDirectionalParticles")){var T=Xh(e.linkDirectionalParticles),S=Xh(e.linkDirectionalParticleWidth),M=Xh(e.linkDirectionalParticleColor),w=Xh(e.linkDirectionalParticleThreeObject),E={},A={};e.particlesDataMapper.onCreateObj(function(){var e=new Pp.Group;return e.__linkThreeObjType="photons",e.__photonDataMapper=new Ep(e),e}).onUpdateObj(function(t,n){var r,i,s=!!t.children.length&&t.children[0],a=w(n);if(a)r=a.geometry,i=a.material;else{var o=Math.ceil(10*S(n))/10/2,l=e.linkDirectionalParticleResolution;s&&s.geometry.parameters.radius===o&&s.geometry.parameters.widthSegments===l?r=s.geometry:(A.hasOwnProperty(o)||(A[o]=new Pp.SphereGeometry(o,l,l)),r=A[o]);var u=M(n)||f(n)||"#f0f0f0",c=new Pp.Color(Ap(u)),h=3*e.linkOpacity;s&&s.material.color.equals(c)&&s.material.opacity===h?i=s.material:(E.hasOwnProperty(u)||(E[u]=new Pp.MeshLambertMaterial({color:c,transparent:!0,opacity:h})),i=E[u])}s&&(s.geometry!==r&&s.geometry.dispose(),s.material!==i&&s.material.dispose());var d=Math.round(Math.abs(T(n)));t.__photonDataMapper.id(function(e){return e.idx}).onCreateObj(function(){return new Pp.Mesh(r,i)}).onUpdateObj(function(e){e.geometry=r,e.material=i}).digest(_p(new Array(d)).map(function(e,t){return{idx:t}}))}).digest(y.filter(T))}}if(e._flushObjects=!1,n(["graphData","nodeId","linkSource","linkTarget","numDimensions","forceEngine","dagMode","dagNodeFilter","dagLevelDistance"])){e.engineRunning=!1,e.graphData.links.forEach(function(t){t.source=t[e.linkSource],t.target=t[e.linkTarget]});var R,C="ngraph"!==e.forceEngine;if(C){(R=e.d3ForceLayout).stop().alpha(1).numDimensions(e.numDimensions).nodes(e.graphData.nodes);var N=e.d3ForceLayout.force("link");N&&N.id(function(t){return t[e.nodeId]}).links(e.graphData.links);var P=e.dagMode&&function(e,t){var n=e.nodes,r=e.links,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},s=i.nodeFilter,a=void 0===s?function(){return!0}:s,o=i.onLoopError,l=void 0===o?function(e){throw"Invalid DAG structure! Found cycle in node path: ".concat(e.join(" -> "),".")}:o,u={};n.forEach(function(e){return u[t(e)]={data:e,out:[],depth:-1,skip:!a(e)}}),r.forEach(function(e){var n=e.source,r=e.target,i=l(n),s=l(r);if(!u.hasOwnProperty(i))throw"Missing source node with id: ".concat(i);if(!u.hasOwnProperty(s))throw"Missing target node with id: ".concat(s);var a=u[i],o=u[s];function l(e){return"object"===yp(e)?t(e):e}a.out.push(o)});var c=[];return function e(n){for(var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=function(){var s=n[a];if(-1!==r.indexOf(s)){var o=[].concat(_p(r.slice(r.indexOf(s))),[s]).map(function(e){return t(e.data)});return c.some(function(e){return e.length===o.length&&e.every(function(e,t){return e===o[t]})})||(c.push(o),l(o)),1}i>s.depth&&(s.depth=i,e(s.out,[].concat(_p(r),[s]),i+(s.skip?0:1)))},a=0,o=n.length;a<o;a++)s()}(Object.values(u)),Object.assign.apply(Object,[{}].concat(_p(Object.entries(u).filter(function(e){return!mp(e,2)[1].skip}).map(function(e){var t=mp(e,2);return lp({},t[0],t[1].depth)}))))}(e.graphData,function(t){return t[e.nodeId]},{nodeFilter:e.dagNodeFilter,onLoopError:e.onDagError||void 0}),L=Math.max.apply(Math,_p(Object.values(P||[]))),D=e.dagLevelDistance||e.graphData.nodes.length/(L||1)*2*(-1!==["radialin","radialout"].indexOf(e.dagMode)?.7:1);if(["lr","rl","td","bu","zin","zout"].includes(t.dagMode)){var I=["lr","rl"].includes(t.dagMode)?"fx":["td","bu"].includes(t.dagMode)?"fy":"fz";e.graphData.nodes.filter(e.dagNodeFilter).forEach(function(e){return delete e[I]})}if(["lr","rl","td","bu","zin","zout"].includes(e.dagMode)){var U=["rl","td","zout"].includes(e.dagMode),O=["lr","rl"].includes(e.dagMode)?"fx":["td","bu"].includes(e.dagMode)?"fy":"fz";e.graphData.nodes.filter(e.dagNodeFilter).forEach(function(t){return t[O]=function(t){return(P[t[e.nodeId]]-L/2)*D*(U?-1:1)}(t)})}e.d3ForceLayout.force("dagRadial",-1!==["radialin","radialout"].indexOf(e.dagMode)?function(e,t,n,r){var i,s,a,o,l=Qu(.1);function u(e){for(var l=0,u=i.length;l<u;++l){var c=i[l],h=c.x-t||1e-6,d=(c.y||0)-n||1e-6,p=(c.z||0)-r||1e-6,f=Math.sqrt(h*h+d*d+p*p),m=(o[l]-f)*a[l]*e/f;c.vx+=h*m,s>1&&(c.vy+=d*m),s>2&&(c.vz+=p*m)}}function c(){if(i){var t,n=i.length;for(a=new Array(n),o=new Array(n),t=0;t<n;++t)o[t]=+e(i[t],t,i),a[t]=isNaN(o[t])?0:+l(i[t],t,i)}}return"function"!=typeof e&&(e=Qu(+e)),null==t&&(t=0),null==n&&(n=0),null==r&&(r=0),u.initialize=function(e,...t){i=e,s=t.find(e=>[1,2,3].includes(e))||2,c()},u.strength=function(e){return arguments.length?(l="function"==typeof e?e:Qu(+e),c(),u):l},u.radius=function(t){return arguments.length?(e="function"==typeof t?t:Qu(+t),c(),u):e},u.x=function(e){return arguments.length?(t=+e,u):t},u.y=function(e){return arguments.length?(n=+e,u):n},u.z=function(e){return arguments.length?(r=+e,u):r},u}(function(t){var n=P[t[e.nodeId]]||-1;return("radialin"===e.dagMode?L-n:n)*D}).strength(function(t){return e.dagNodeFilter(t)?1:0}):null)}else{var F=Lp.graph();e.graphData.nodes.forEach(function(t){F.addNode(t[e.nodeId])}),e.graphData.links.forEach(function(e){F.addLink(e.source,e.target)}),R=Lp.forcelayout(F,function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?pp(Object(n),!0).forEach(function(t){lp(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):pp(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}({dimensions:e.numDimensions},e.ngraphPhysics)),R.graph=F}for(var B=0;B<e.warmupTicks&&!(C&&e.d3AlphaMin>0&&e.d3ForceLayout.alpha()<e.d3AlphaMin);B++)R[C?"tick":"step"]();e.layout=R,this.resetCountdown()}e.engineRunning=!0,e.onFinishUpdate()}});var Op=function(e){var t=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=function(n){function r(){var n;np(this,r);for(var i=arguments.length,s=new Array(i),a=0;a<i;a++)s[a]=arguments[a];return(n=tp(this,r,[].concat(s))).__kapsuleInstance=ap(e,[].concat(_p(t?[n]:[]),s)),n}return hp(r,n),op(r)}(arguments.length>1&&void 0!==arguments[1]?arguments[1]:Object);return Object.keys(e()).forEach(function(e){return n.prototype[e]=function(){var t,n=(t=this.__kapsuleInstance)[e].apply(t,arguments);return n===this.__kapsuleInstance?this:n}}),n}(Up,(window.THREE?window.THREE:{Group:Ci}).Group,!0);const Fp=["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"];class Bp{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=!0===e.object.isSkinnedMesh,this.refreshUniforms=Fp,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:n,material:r,object:i}=e;if(t={material:this.getMaterialData(r),geometry:{id:n.id,attributes:this.getAttributesData(n.attributes),indexVersion:n.index?n.index.version:null,drawRange:{start:n.drawRange.start,count:n.drawRange.count}},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),t.material.transmission>0){const{width:n,height:r}=e.context;t.bufferWidth=n,t.bufferHeight=r}this.renderObjects.set(e,t)}return t}getAttributesData(e){const t={};for(const n in e){const r=e[n];t[n]={version:r.version}}return t}containsNode(e){const t=e.material;for(const e in t)if(t[e]&&t[e].isNode)return!0;return null!==e.renderer.overrideNodes.modelViewMatrix||null!==e.renderer.overrideNodes.modelNormalViewMatrix}getMaterialData(e){const t={};for(const n of this.refreshUniforms){const r=e[n];null!=r&&("object"==typeof r&&void 0!==r.clone?!0===r.isTexture?t[n]={id:r.id,version:r.version}:t[n]=r.clone():t[n]=r)}return t}equals(e){const{object:t,material:n,geometry:r}=e,i=this.getRenderObjectData(e);if(!0!==i.worldMatrix.equals(t.matrixWorld))return i.worldMatrix.copy(t.matrixWorld),!1;const s=i.material;for(const e in s){const t=s[e],r=n[e];if(void 0!==t.equals){if(!1===t.equals(r))return t.copy(r),!1}else if(!0===r.isTexture){if(t.id!==r.id||t.version!==r.version)return t.id=r.id,t.version=r.version,!1}else if(t!==r)return s[e]=r,!1}if(s.transmission>0){const{width:t,height:n}=e.context;if(i.bufferWidth!==t||i.bufferHeight!==n)return i.bufferWidth=t,i.bufferHeight=n,!1}const a=i.geometry,o=r.attributes,l=a.attributes,u=Object.keys(l),c=Object.keys(o);if(a.id!==r.id)return a.id=r.id,!1;if(u.length!==c.length)return i.geometry.attributes=this.getAttributesData(o),!1;for(const e of u){const t=l[e],n=o[e];if(void 0===n)return delete l[e],!1;if(t.version!==n.version)return t.version=n.version,!1}const h=r.index,d=a.indexVersion,p=h?h.version:null;if(d!==p)return a.indexVersion=p,!1;if(a.drawRange.start!==r.drawRange.start||a.drawRange.count!==r.drawRange.count)return a.drawRange.start=r.drawRange.start,a.drawRange.count=r.drawRange.count,!1;if(i.morphTargetInfluences){let e=!1;for(let n=0;n<i.morphTargetInfluences.length;n++)i.morphTargetInfluences[n]!==t.morphTargetInfluences[n]&&(e=!0);if(e)return!0}return i.center&&!1===i.center.equals(t.center)?(i.center.copy(t.center),!0):(null!==e.bundle&&(i.version=e.bundle.version),!0)}needsRefresh(e,t){if(this.hasNode||this.hasAnimation||this.firstInitialization(e)||this.needsVelocity(t.renderer))return!0;const{renderId:n}=t;if(this.renderId!==n)return this.renderId=n,!0;const r=!0===e.object.static,i=null!==e.bundle&&!0===e.bundle.static&&this.getRenderObjectData(e).version===e.bundle.version;if(r||i)return!1;return!0!==this.equals(e)}}function kp(e,t=0){let n=3735928559^t,r=1103547991^t;if(e instanceof Array)for(let t,i=0;i<e.length;i++)t=e[i],n=Math.imul(n^t,2654435761),r=Math.imul(r^t,1597334677);else for(let t,i=0;i<e.length;i++)t=e.charCodeAt(i),n=Math.imul(n^t,2654435761),r=Math.imul(r^t,1597334677);return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}const zp=e=>kp(e),Vp=(...e)=>kp(e);function Gp(e,t=!1){const n=[];!0===e.isNode&&(n.push(e.id),e=e.getSelf());for(const{property:r,childNode:i}of Hp(e))n.push(kp(r.slice(0,-4)),i.getCacheKey(t));return kp(n)}function*Hp(e,t=!1){for(const n in e){if(!0===n.startsWith("_"))continue;const r=e[n];if(!0===Array.isArray(r))for(let e=0;e<r.length;e++){const i=r[e];i&&(!0===i.isNode||t&&"function"==typeof i.toJSON)&&(yield{property:n,index:e,childNode:i})}else if(r&&!0===r.isNode)yield{property:n,childNode:r};else if("object"==typeof r)for(const e in r){const i=r[e];i&&(!0===i.isNode||t&&"function"==typeof i.toJSON)&&(yield{property:n,index:e,childNode:i})}}}const jp=new Map([[1,"float"],[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),Wp=new WeakMap;function Xp(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 qp(e,...t){const n=e?e.slice(-4):void 0;return 1===t.length&&("vec2"===n?t=[t[0],t[0]]:"vec3"===n?t=[t[0],t[0],t[0]]:"vec4"===n&&(t=[t[0],t[0],t[0],t[0]])),"color"===e?new Nr(...t):"vec2"===n?new Dt(...t):"vec3"===n?new Ut(...t):"vec4"===n?new an(...t):"mat2"===n?new _a(...t):"mat3"===n?new Bt(...t):"mat4"===n?new Bn(...t):"bool"===e?t[0]||!1:"float"===e||"int"===e||"uint"===e?t[0]||0:"string"===e?t[0]||"":"ArrayBuffer"===e?(r=t[0],Uint8Array.from(atob(r),e=>e.charCodeAt(0)).buffer):null;var r}function $p(e){let t=Wp.get(e);return void 0===t&&(t={},Wp.set(e,t)),t}const Yp="vertex",Kp="none",Qp="frame",Zp="render",Jp="object",ef="readOnly",tf="writeOnly",nf="readWrite",rf=["setup","analyze","generate"],sf=["fragment","vertex","compute"],af=["x","y","z","w"],of={analyze:"setup",generate:"analyze"};let lf=0;class uf extends bt{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=Kp,this.updateBeforeType=Kp,this.updateAfterType=Kp,this.uuid=Lt.generateUUID(),this.version=0,this.global=!1,this.parents=!1,this.isNode=!0,this._cacheKey=null,this._cacheKeyVersion=0,Object.defineProperty(this,"id",{value:lf++})}set needsUpdate(e){!0===e&&this.version++}get type(){return this.constructor.type}onUpdate(e,t){return this.updateType=t,this.update=e.bind(this.getSelf()),this}onFrameUpdate(e){return this.onUpdate(e,Qp)}onRenderUpdate(e){return this.onUpdate(e,Zp)}onObjectUpdate(e){return this.onUpdate(e,Jp)}onReference(e){return this.updateReference=e.bind(this.getSelf()),this}getSelf(){return this.self||this}updateReference(){return this}isGlobal(){return this.global}*getChildren(){for(const{childNode:e}of Hp(this))yield e}dispose(){this.dispatchEvent({type:"dispose"})}traverse(e){e(this);for(const t of this.getChildren())t.traverse(e)}getCacheKey(e=!1){return!0!==(e=e||this.version!==this._cacheKeyVersion)&&null!==this._cacheKey||(this._cacheKey=Vp(Gp(this,e),this.customCacheKey()),this._cacheKeyVersion=this.version),this._cacheKey}customCacheKey(){return 0}getScope(){return this}getHash(){return this.uuid}getUpdateType(){return this.updateType}getUpdateBeforeType(){return this.updateBeforeType}getUpdateAfterType(){return this.updateAfterType}getElementType(e){const t=this.getNodeType(e);return e.getElementType(t)}getMemberType(){return"void"}getNodeType(e){const t=e.getNodeProperties(this);return t.outputNode?t.outputNode.getNodeType(e):this.nodeType}getShared(e){const t=this.getHash(e);return e.getNodeFromHash(t)||this}setup(e){const t=e.getNodeProperties(this);let n=0;for(const e of this.getChildren())t["node"+n++]=e;return t.outputNode||null}analyze(e,t=null){const n=e.increaseUsage(this);if(!0===this.parents){const n=e.getDataFromNode(this,"any");n.stages=n.stages||{},n.stages[e.shaderStage]=n.stages[e.shaderStage]||[],n.stages[e.shaderStage].push(t)}if(1===n){const t=e.getNodeProperties(this);for(const n of Object.values(t))n&&!0===n.isNode&&n.build(e,this)}}generate(e,t){const{outputNode:n}=e.getNodeProperties(this);if(n&&!0===n.isNode)return n.build(e,t)}updateBefore(){console.warn("Abstract function.")}updateAfter(){console.warn("Abstract function.")}update(){console.warn("Abstract function.")}build(e,t=null){const n=this.getShared(e);if(this!==n)return n.build(e,t);const r=e.getDataFromNode(this);r.buildStages=r.buildStages||{},r.buildStages[e.buildStage]=!0;const i=of[e.buildStage];if(i&&!0!==r.buildStages[i]){const t=e.getBuildStage();e.setBuildStage(i),this.build(e),e.setBuildStage(t)}e.addNode(this),e.addChain(this);let s=null;const a=e.getBuildStage();if("setup"===a){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 n of Object.values(t))if(n&&!0===n.isNode){if(!0===n.parents){const t=e.getNodeProperties(n);t.parents=t.parents||[],t.parents.push(this)}n.build(e)}}s=t.outputNode}else if("analyze"===a)this.analyze(e,t);else if("generate"===a){if(1===this.generate.length){const n=this.getNodeType(e),r=e.getDataFromNode(this);s=r.snippet,void 0===s?void 0===r.generated?(r.generated=!0,s=this.generate(e)||"",r.snippet=s):(console.warn("THREE.Node: Recursion detected.",this),s="/* Recursion detected. */"):void 0!==r.flowCodes&&void 0!==e.context.nodeBlock&&e.addFlowCodeHierarchy(this,e.context.nodeBlock),s=e.format(s,n,t)}else s=this.generate(e,t)||""}return e.removeChain(this),e.addSequentialNode(this),s}getSerializeChildren(){return Hp(this)}serialize(e){const t=this.getSerializeChildren(),n={};for(const{property:r,index:i,childNode:s}of t)void 0!==i?(void 0===n[r]&&(n[r]=Number.isInteger(i)?[]:{}),n[r][i]=s.toJSON(e.meta).uuid):n[r]=s.toJSON(e.meta).uuid;Object.keys(n).length>0&&(e.inputNodes=n)}deserialize(e){if(void 0!==e.inputNodes){const t=e.meta.nodes;for(const n in e.inputNodes)if(Array.isArray(e.inputNodes[n])){const r=[];for(const i of e.inputNodes[n])r.push(t[i]);this[n]=r}else if("object"==typeof e.inputNodes[n]){const r={};for(const i in e.inputNodes[n]){const s=e.inputNodes[n][i];r[i]=t[s]}this[n]=r}else{const r=e.inputNodes[n];this[n]=t[r]}}}toJSON(e){const{uuid:t,type:n}=this,r=void 0===e||"string"==typeof e;r&&(e={textures:{},images:{},nodes:{}});let i=e.nodes[t];function s(e){const t=[];for(const n in e){const r=e[n];delete r.metadata,t.push(r)}return t}if(void 0===i&&(i={uuid:t,type:n,meta:e,metadata:{version:4.7,type:"Node",generator:"Node.toJSON"}},!0!==r&&(e.nodes[i.uuid]=i),this.serialize(i),delete i.meta),r){const t=s(e.textures),n=s(e.images),r=s(e.nodes);t.length>0&&(i.textures=t),n.length>0&&(i.images=n),r.length>0&&(i.nodes=r)}return i}}class cf extends uf{static get type(){return"ArrayElementNode"}constructor(e,t){super(),this.node=e,this.indexNode=t,this.isArrayElementNode=!0}getNodeType(e){return this.node.getElementType(e)}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 hf extends uf{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}getNodeType(e){const t=this.node.getNodeType(e);let n=null;for(const r of this.convertTo.split("|"))null!==n&&e.getTypeLength(t)!==e.getTypeLength(r)||(n=r);return n}serialize(e){super.serialize(e),e.convertTo=this.convertTo}deserialize(e){super.deserialize(e),this.convertTo=e.convertTo}generate(e,t){const n=this.node,r=this.getNodeType(e),i=n.build(e,r);return e.format(i,r,t)}}class df extends uf{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 n=e.getVectorType(this.getNodeType(e,t)),r=e.getDataFromNode(this);if(void 0!==r.propertyName)return e.format(r.propertyName,n,t);if("void"!==n&&"void"!==t&&this.hasDependencies(e)){const i=super.build(e,n),s=e.getVarFromNode(this,null,n),a=e.getPropertyName(s);return e.addLineFlowCode(`${a} = ${i}`,this),r.snippet=i,r.propertyName=a,e.format(r.propertyName,n,t)}}return super.build(e,t)}}class pf extends df{static get type(){return"JoinNode"}constructor(e=[],t=null){super(t),this.nodes=e}getNodeType(e){return null!==this.nodeType?e.getVectorType(this.nodeType):e.getTypeFromLength(this.nodes.reduce((t,n)=>t+e.getTypeLength(n.getNodeType(e)),0))}generate(e,t){const n=this.getNodeType(e),r=e.getTypeLength(n),i=this.nodes,s=e.getComponentType(n),a=[];let o=0;for(const t of i){if(o>=r){console.error(`THREE.TSL: Length of parameters exceeds maximum length of function '${n}()' type.`);break}let i,l=t.getNodeType(e),u=e.getTypeLength(l);o+u>r&&(console.error(`THREE.TSL: Length of '${n}()' data exceeds maximum length of output type.`),u=r-o,l=e.getTypeFromLength(u)),o+=u,i=t.build(e,l);const c=e.getComponentType(l);c!==s&&(i=e.format(i,c,s)),a.push(i)}const l=`${e.getType(n)}( ${a.join(", ")} )`;return e.format(l,n,t)}}const ff=af.join("");class mf extends uf{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(af.indexOf(t)+1,e);return e}getComponentType(e){return e.getComponentType(this.node.getNodeType(e))}getNodeType(e){return e.getTypeFromLength(this.components.length,this.getComponentType(e))}generate(e,t){const n=this.node,r=e.getTypeLength(n.getNodeType(e));let i=null;if(r>1){let s=null;this.getVectorLength()>=r&&(s=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));const a=n.build(e,s);i=this.components.length===r&&this.components===ff.slice(0,this.components.length)?e.format(a,s,t):e.format(`${a}.${this.components}`,this.getNodeType(e),t)}else i=n.build(e,t);return i}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}}class gf extends df{static get type(){return"SetNode"}constructor(e,t,n){super(),this.sourceNode=e,this.components=t,this.targetNode=n}getNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{sourceNode:t,components:n,targetNode:r}=this,i=this.getNodeType(e),s=e.getComponentType(r.getNodeType(e)),a=e.getTypeFromLength(n.length,s),o=r.build(e,a),l=t.build(e,i),u=e.getTypeLength(i),c=[];for(let e=0;e<u;e++){const t=af[e];t===n[0]?(c.push(o),e+=n.length-1):c.push(l+"."+t)}return`${e.getType(i)}( ${c.join(", ")} )`}}class _f extends df{static get type(){return"FlipNode"}constructor(e,t){super(),this.sourceNode=e,this.components=t}getNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{components:t,sourceNode:n}=this,r=this.getNodeType(e),i=n.build(e),s=e.getVarFromNode(this),a=e.getPropertyName(s);e.addLineFlowCode(a+" = "+i,this);const o=e.getTypeLength(r),l=[];let u=0;for(let e=0;e<o;e++){const n=af[e];n===t[u]?(l.push("1.0 - "+a+"."+n),u++):l.push(a+"."+n)}return`${e.getType(r)}( ${l.join(", ")} )`}}class vf extends uf{static get type(){return"InputNode"}constructor(e,t=null){super(t),this.isInputNode=!0,this.value=e,this.precision=null}getNodeType(){return null===this.nodeType?Xp(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=Xp(this.value),e.nodeType=this.nodeType,"ArrayBuffer"===e.valueType&&(e.value=function(e){let t="";const n=new Uint8Array(e);for(let e=0;e<n.length;e++)t+=String.fromCharCode(n[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)?qp(e.valueType,...e.value):e.value,this.precision=e.precision||null,this.value&&this.value.fromArray&&(this.value=this.value.fromArray(e.value))}generate(){console.warn("Abstract function.")}}const yf=/float|u?int/;class xf extends vf{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 n=this.getNodeType(e);return yf.test(n)&&yf.test(t)?e.generateConst(t,this.value):e.format(this.generateConst(e),n,t)}}class bf extends uf{static get type(){return"MemberNode"}constructor(e,t){super(),this.node=e,this.property=t,this.isMemberNode=!0}getNodeType(e){return this.node.getMemberType(e,this.property)}generate(e){return this.node.build(e)+"."+this.property}}let Tf=null;const Sf=new Map;function Mf(e,t){if(Sf.has(e))console.warn(`THREE.TSL: Redefinition of method chaining '${e}'.`);else{if("function"!=typeof t)throw new Error(`THREE.TSL: Node element ${e} is not a function`);Sf.set(e,t)}}const wf=e=>e.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"),Ef=e=>wf(e).split("").sort().join(""),Af={setup(e,t){const n=t.shift();return e(Qf(n),...t)},get(e,t,n){if("string"==typeof t&&void 0===e[t]){if(!0!==e.isStackNode&&"assign"===t)return(...e)=>(Tf.assign(n,...e),n);if(Sf.has(t)){const r=Sf.get(t);return e.isStackNode?(...e)=>n.add(r(...e)):(...e)=>r(n,...e)}if("self"===t)return e;if(t.endsWith("Assign")&&Sf.has(t.slice(0,t.length-6))){const r=Sf.get(t.slice(0,t.length-6));return e.isStackNode?(...e)=>n.assign(e[0],r(...e)):(...e)=>n.assign(r(n,...e))}if(!0===/^[xyzwrgbastpq]{1,4}$/.test(t))return t=wf(t),Kf(new mf(n,t));if(!0===/^set[XYZWRGBASTPQ]{1,4}$/.test(t))return t=Ef(t.slice(3).toLowerCase()),n=>Kf(new gf(e,t,Kf(n)));if(!0===/^flip[XYZWRGBASTPQ]{1,4}$/.test(t))return t=Ef(t.slice(4).toLowerCase()),()=>Kf(new _f(Kf(e),t));if("width"===t||"height"===t||"depth"===t)return"width"===t?t="x":"height"===t?t="y":"depth"===t&&(t="z"),Kf(new mf(e,t));if(!0===/^\d+$/.test(t))return Kf(new cf(n,new xf(Number(t),"uint")));if(!0===/^get$/.test(t))return e=>Kf(new bf(n,e))}return Reflect.get(e,t,n)},set:(e,t,n,r)=>"string"!=typeof t||void 0!==e[t]||!0!==/^[xyzwrgbastpq]{1,4}$/.test(t)&&"width"!==t&&"height"!==t&&"depth"!==t&&!0!==/^\d+$/.test(t)?Reflect.set(e,t,n,r):(r[t].assign(n),!0)},Rf=new WeakMap,Cf=new WeakMap,Nf=function(e,t=null){for(const n in e)e[n]=Kf(e[n],t);return e},Pf=function(e,t=null){const n=e.length;for(let r=0;r<n;r++)e[r]=Kf(e[r],t);return e},Lf=function(e,t=null,n=null,r=null){const i=e=>Kf(null!==r?Object.assign(e,r):e);let s,a,o,l=t;function u(t){let n;return n=l?/[a-z]/i.test(l)?l+"()":l:e.type,void 0!==a&&t.length<a?(console.error(`THREE.TSL: "${n}" parameter length is less than minimum required.`),t.concat(new Array(a-t.length).fill(0))):void 0!==o&&t.length>o?(console.error(`THREE.TSL: "${n}" parameter length exceeds limit.`),t.slice(0,o)):t}return null===t?s=(...t)=>i(new e(...Zf(u(t)))):null!==n?(n=Kf(n),s=(...r)=>i(new e(t,...Zf(u(r)),n))):s=(...n)=>i(new e(t,...Zf(u(n)))),s.setParameterLength=(...e)=>(1===e.length?a=o=e[0]:2===e.length&&([a,o]=e),s),s.setName=e=>(l=e,s),s},Df=function(e,...t){return Kf(new e(...Zf(t)))};class If extends uf{constructor(e,t){super(),this.shaderNode=e,this.inputNodes=t,this.isShaderCallNodeInternal=!0}getNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}getMemberType(e,t){return this.getOutputNode(e).getMemberType(e,t)}call(e){const{shaderNode:t,inputNodes:n}=this,r=e.getNodeProperties(t),i=e.getClosestSubBuild(t.subBuilds)||"",s=i||"default";if(r[s])return r[s];const a=e.subBuildFn;e.subBuildFn=i;let o=null;if(t.layout){let r=Cf.get(e.constructor);void 0===r&&(r=new WeakMap,Cf.set(e.constructor,r));let i=r.get(t);void 0===i&&(i=Kf(e.buildFunctionNode(t)),r.set(t,i)),e.addInclude(i),o=Kf(i.call(n))}else{const r=t.jsFunc,i=null!==n||r.length>1?r(n||[],e):r(e);o=Kf(i)}return e.subBuildFn=a,t.once&&(r[s]=o),o}setupOutput(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}getOutputNode(e){const t=e.getNodeProperties(this),n=e.getSubBuildOutput(this);return t[n]=t[n]||this.setupOutput(e),t[n].subBuild=e.getClosestSubBuild(this),t[n]}build(e,t=null){let n=null;const r=e.getBuildStage(),i=e.getNodeProperties(this),s=e.getSubBuildOutput(this),a=this.getOutputNode(e);if("setup"===r){const t=e.getSubBuildProperty("initialized",this);if(!0!==i[t]&&(i[t]=!0,i[s]=this.getOutputNode(e),i[s].build(e),this.shaderNode.subBuilds))for(const t of e.chaining){const n=e.getDataFromNode(t,"any");n.subBuilds=n.subBuilds||new Set;for(const e of this.shaderNode.subBuilds)n.subBuilds.add(e)}n=i[s]}else"analyze"===r?a.build(e,t):"generate"===r&&(n=a.build(e,t)||"");return n}}class Uf extends uf{constructor(e,t){super(t),this.jsFunc=e,this.layout=null,this.global=!0,this.once=!1}setLayout(e){return this.layout=e,this}call(e=null){return Qf(e),Kf(new If(this,e))}setup(){return this.call()}}const Of=[!1,!0],Ff=[0,1,2,3],Bf=[-1,-2],kf=[.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],zf=new Map;for(const e of Of)zf.set(e,new xf(e));const Vf=new Map;for(const e of Ff)Vf.set(e,new xf(e,"uint"));const Gf=new Map([...Vf].map(e=>new xf(e.value,"int")));for(const e of Bf)Gf.set(e,new xf(e,"int"));const Hf=new Map([...Gf].map(e=>new xf(e.value)));for(const e of kf)Hf.set(e,new xf(e));for(const e of kf)Hf.set(-e,new xf(-e));const jf={bool:zf,uint:Vf,ints:Gf,float:Hf},Wf=new Map([...zf,...Hf]),Xf=(e,t)=>Wf.has(e)?Wf.get(e):!0===e.isNode?e:new xf(e,t),qf=function(e,t=null){return(...n)=>{if((0===n.length||!["bool","float","int","uint"].includes(e)&&n.every(e=>"object"!=typeof e))&&(n=[qp(e,...n)]),1===n.length&&null!==t&&t.has(n[0]))return Kf(t.get(n[0]));if(1===n.length){const t=Xf(n[0],e);return t.nodeType===e?Kf(t):Kf(new hf(t,e))}const r=n.map(e=>Xf(e));return Kf(new pf(r,e))}},$f=e=>"object"==typeof e&&null!==e?e.value:e;function Yf(e,t){return new Proxy(new Uf(e,t),Af)}const Kf=(e,t=null)=>function(e,t=null){const n=Xp(e);if("node"===n){let t=Rf.get(e);return void 0===t&&(t=new Proxy(e,Af),Rf.set(e,t),Rf.set(t,t)),t}return null===t&&("float"===n||"boolean"===n)||n&&"shader"!==n&&"string"!==n?Kf(Xf(e,t)):"shader"===n?e.isFn?e:nm(e):e}(e,t),Qf=(e,t=null)=>new Nf(e,t),Zf=(e,t=null)=>new Pf(e,t),Jf=(...e)=>new Lf(...e),em=(...e)=>new Df(...e);let tm=0;const nm=(e,t=null)=>{let n=null;null!==t&&("object"==typeof t?n=t.return:("string"==typeof t?n=t:console.error("THREE.TSL: Invalid layout type."),t=null));const r=new Yf(e,n),i=(...e)=>{let t;Qf(e);t=e[0]&&(e[0].isNode||Object.getPrototypeOf(e[0])!==Object.prototype)?[...e]:e[0];const i=r.call(t);return"void"===n&&i.toStack(),i};if(i.shaderNode=r,i.id=r.id,i.isFn=!0,i.getNodeType=(...e)=>r.getNodeType(...e),i.getCacheKey=(...e)=>r.getCacheKey(...e),i.setLayout=e=>(r.setLayout(e),i),i.once=(e=null)=>(r.once=!0,r.subBuilds=e,i),null!==t){if("object"!=typeof t.inputs){const e={name:"fn"+tm++,type:n,inputs:[]};for(const n in t)"return"!==n&&e.inputs.push({name:n,type:t[n]});t=e}i.setLayout(t)}return i},rm=e=>{Tf=e},im=()=>Tf,sm=(...e)=>Tf.If(...e);function am(e){return Tf&&Tf.add(e),e}Mf("toStack",am);const om=new qf("color"),lm=new qf("float",jf.float),um=new qf("int",jf.ints),cm=new qf("uint",jf.uint),hm=new qf("bool",jf.bool),dm=new qf("vec2"),pm=new qf("ivec2"),fm=new qf("uvec2"),mm=new qf("bvec2"),gm=new qf("vec3"),_m=new qf("ivec3"),vm=new qf("uvec3"),ym=new qf("bvec3"),xm=new qf("vec4"),bm=new qf("ivec4"),Tm=new qf("uvec4"),Sm=new qf("bvec4"),Mm=new qf("mat2"),wm=new qf("mat3"),Em=new qf("mat4");Mf("toColor",om),Mf("toFloat",lm),Mf("toInt",um),Mf("toUint",cm),Mf("toBool",hm),Mf("toVec2",dm),Mf("toIVec2",pm),Mf("toUVec2",fm),Mf("toBVec2",mm),Mf("toVec3",gm),Mf("toIVec3",_m),Mf("toUVec3",vm),Mf("toBVec3",ym),Mf("toVec4",xm),Mf("toIVec4",bm),Mf("toUVec4",Tm),Mf("toBVec4",Sm),Mf("toMat2",Mm),Mf("toMat3",wm),Mf("toMat4",Em);Mf("element",Jf(cf).setParameterLength(2)),Mf("convert",(e,t)=>Kf(new hf(Kf(e),t))),Mf("append",e=>(console.warn("THREE.TSL: .append() has been renamed to .toStack()."),am(e)));class Am extends uf{static get type(){return"PropertyNode"}constructor(e,t=null,n=!1){super(e),this.name=t,this.varying=n,this.isPropertyNode=!0,this.global=!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 Rm=(e,t)=>Kf(new Am(e,t)),Cm=(e,t)=>Kf(new Am(e,t,!0)),Nm=em(Am,"vec4","DiffuseColor"),Pm=em(Am,"vec3","EmissiveColor"),Lm=em(Am,"float","Roughness"),Dm=em(Am,"float","Metalness"),Im=em(Am,"float","Clearcoat"),Um=em(Am,"float","ClearcoatRoughness"),Om=em(Am,"vec3","Sheen"),Fm=em(Am,"float","SheenRoughness"),Bm=em(Am,"float","Iridescence"),km=em(Am,"float","IridescenceIOR"),zm=em(Am,"float","IridescenceThickness"),Vm=em(Am,"float","AlphaT"),Gm=em(Am,"float","Anisotropy"),Hm=em(Am,"vec3","AnisotropyT"),jm=em(Am,"vec3","AnisotropyB"),Wm=em(Am,"color","SpecularColor"),Xm=em(Am,"float","SpecularF90"),qm=em(Am,"float","Shininess"),$m=em(Am,"vec4","Output"),Ym=em(Am,"float","dashSize"),Km=em(Am,"float","gapSize"),Qm=em(Am,"float","IOR"),Zm=em(Am,"float","Transmission"),Jm=em(Am,"float","Thickness"),eg=em(Am,"float","AttenuationDistance"),tg=em(Am,"color","AttenuationColor"),ng=em(Am,"float","Dispersion");class rg extends uf{static get type(){return"UniformGroupNode"}constructor(e,t=!1,n=1){super("string"),this.name=e,this.shared=t,this.order=n,this.isUniformGroup=!0}serialize(e){super.serialize(e),e.name=this.name,e.version=this.version,e.shared=this.shared}deserialize(e){super.deserialize(e),this.name=e.name,this.version=e.version,this.shared=e.shared}}const ig=e=>new rg(e),sg=(e,t=0)=>new rg(e,!0,t),ag=sg("frame"),og=sg("render"),lg=ig("object");class ug extends vf{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=lg}label(e){return this.name=e,this}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}onUpdate(e,t){const n=this.getSelf();return e=e.bind(n),super.onUpdate(t=>{const r=e(t,n);void 0!==r&&(this.value=r)},t)}generate(e,t){const n=this.getNodeType(e),r=this.getUniformHash(e);let i=e.getNodeFromHash(r);void 0===i&&(e.setHashNode(this,r),i=this);const s=i.getInputType(e),a=e.getUniformFromNode(i,s,e.shaderStage,this.name||e.context.label),o=e.getPropertyName(a);return void 0!==e.context.label&&delete e.context.label,e.format(o,n,t)}}const cg=(e,t)=>{const n=(e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null)(t||e),r=e&&!0===e.isNode?e.node&&e.node.value||e.value:e;return Kf(new ug(r,n))};class hg extends df{static get type(){return"ArrayNode"}constructor(e,t,n=null){super(e),this.count=t,this.values=n,this.isArrayNode=!0}getNodeType(e){return null===this.nodeType&&(this.nodeType=this.values[0].getNodeType(e)),this.nodeType}getElementType(e){return this.getNodeType(e)}generate(e){const t=this.getNodeType(e);return e.generateArray(t,this.count,this.values)}}Mf("toArray",(e,t)=>((...e)=>{let t;if(1===e.length){const n=e[0];t=new hg(null,n.length,n)}else{const n=e[0],r=e[1];t=new hg(n,r)}return Kf(t)})(Array(t).fill(e)));class dg extends df{static get type(){return"AssignNode"}constructor(e,t){super(),this.targetNode=e,this.sourceNode=t,this.isAssignNode=!0}hasDependencies(){return!1}getNodeType(e,t){return"void"!==t?this.targetNode.getNodeType(e):"void"}needsSplitAssign(e){const{targetNode:t}=this;if(!1===e.isAvailable("swizzleAssign")&&t.isSplitNode&&t.components.length>1){const n=e.getTypeLength(t.node.getNodeType(e));return af.join("").slice(0,n)!==t.components}return!1}setup(e){const{targetNode:t,sourceNode:n}=this,r=e.getNodeProperties(this);r.sourceNode=n,r.targetNode=t.context({assign:!0})}generate(e,t){const{targetNode:n,sourceNode:r}=e.getNodeProperties(this),i=this.needsSplitAssign(e),s=n.getNodeType(e),a=n.build(e),o=r.build(e,s),l=r.getNodeType(e),u=e.getDataFromNode(this);let c;if(!0===u.initialized)"void"!==t&&(c=a);else if(i){const r=e.getVarFromNode(this,null,s),i=e.getPropertyName(r);e.addLineFlowCode(`${i} = ${o}`,this);const l=n.node,u=l.node.context({assign:!0}).build(e);for(let t=0;t<l.components.length;t++){const n=l.components[t];e.addLineFlowCode(`${u}.${n} = ${i}[ ${t} ]`,this)}"void"!==t&&(c=a)}else c=`${a} = ${o}`,"void"!==t&&"void"!==l||(e.addLineFlowCode(c,this),"void"!==t&&(c=a));return u.initialized=!0,e.format(c,s,t)}}Mf("assign",Jf(dg).setParameterLength(2));class pg extends df{static get type(){return"FunctionCallNode"}constructor(e=null,t={}){super(),this.functionNode=e,this.parameters=t}setParameters(e){return this.parameters=e,this}getParameters(){return this.parameters}getNodeType(e){return this.functionNode.getNodeType(e)}generate(e){const t=[],n=this.functionNode,r=n.getInputs(e),i=this.parameters,s=(t,n)=>{const r=n.type;let i;return i="pointer"===r?"&"+t.build(e):t.build(e,r),i};if(Array.isArray(i)){if(i.length>r.length)console.error("THREE.TSL: The number of provided parameters exceeds the expected number of inputs in 'Fn()'."),i.length=r.length;else if(i.length<r.length)for(console.error("THREE.TSL: The number of provided parameters is less than the expected number of inputs in 'Fn()'.");i.length<r.length;)i.push(lm(0));for(let e=0;e<i.length;e++)t.push(s(i[e],r[e]))}else for(const e of r){const n=i[e.name];void 0!==n?t.push(s(n,e)):(console.error(`THREE.TSL: Input '${e.name}' not found in 'Fn()'.`),t.push(s(lm(0),e)))}return`${n.build(e,"property")}( ${t.join(", ")} )`}}Mf("call",(e,...t)=>(t=t.length>1||t[0]&&!0===t[0].isNode?Zf(t):Qf(t[0]),Kf(new pg(Kf(e),t))));const fg={"==":"equal","!=":"notEqual","<":"lessThan",">":"greaterThan","<=":"lessThanEqual",">=":"greaterThanEqual","%":"mod"};class mg extends df{static get type(){return"OperatorNode"}constructor(e,t,n,...r){if(super(),r.length>0){let i=new mg(e,t,n);for(let t=0;t<r.length-1;t++)i=new mg(e,i,r[t]);t=i,n=r[r.length-1]}this.op=e,this.aNode=t,this.bNode=n,this.isOperatorNode=!0}getOperatorMethod(e,t){return e.getMethod(fg[this.op],t)}getNodeType(e){const t=this.op,n=this.aNode,r=this.bNode,i=n.getNodeType(e),s=r?r.getNodeType(e):null;if("void"===i||"void"===s)return"void";if("%"===t)return i;if("~"===t||"&"===t||"|"===t||"^"===t||">>"===t||"<<"===t)return e.getIntegerType(i);if("!"===t||"&&"===t||"||"===t||"^^"===t)return"bool";if("=="===t||"!="===t||"<"===t||">"===t||"<="===t||">="===t){const t=Math.max(e.getTypeLength(i),e.getTypeLength(s));return t>1?`bvec${t}`:"bool"}if(e.isMatrix(i)){if("float"===s)return i;if(e.isVector(s))return e.getVectorFromMatrix(i);if(e.isMatrix(s))return i}else if(e.isMatrix(s)){if("float"===i)return s;if(e.isVector(i))return e.getVectorFromMatrix(s)}return e.getTypeLength(s)>e.getTypeLength(i)?s:i}generate(e,t){const n=this.op,{aNode:r,bNode:i}=this,s=this.getNodeType(e);let a=null,o=null;"void"!==s?(a=r.getNodeType(e),o=i?i.getNodeType(e):null,"<"===n||">"===n||"<="===n||">="===n||"=="===n||"!="===n?e.isVector(a)?o=a:e.isVector(o)?a=o:a!==o&&(a=o="float"):">>"===n||"<<"===n?(a=s,o=e.changeComponentType(o,"uint")):"%"===n?(a=s,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=s):a=e.isMatrix(o)?"float"===a?"float":e.isVector(a)?e.getVectorFromMatrix(o):o=s:o=s):a=o=s;const l=r.build(e,a),u=i?i.build(e,o):null,c=e.getFunctionOperator(n);if("void"!==t){const r=e.renderer.coordinateSystem===yt;if("=="===n||"!="===n||"<"===n||">"===n||"<="===n||">="===n)return r&&e.isVector(a)?e.format(`${this.getOperatorMethod(e,t)}( ${l}, ${u} )`,s,t):e.format(`( ${l} ${n} ${u} )`,s,t);if("%"===n)return e.isInteger(o)?e.format(`( ${l} % ${u} )`,s,t):e.format(`${this.getOperatorMethod(e,s)}( ${l}, ${u} )`,s,t);if("!"===n||"~"===n)return e.format(`(${n}${l})`,a,t);if(c)return e.format(`${c}( ${l}, ${u} )`,s,t);if(e.isMatrix(a)&&"float"===o)return e.format(`( ${u} ${n} ${l} )`,s,t);if("float"===a&&e.isMatrix(o))return e.format(`${l} ${n} ${u}`,s,t);{let i=`( ${l} ${n} ${u} )`;return!r&&"bool"===s&&e.isVector(a)&&e.isVector(o)&&(i=`all${i}`),e.format(i,s,t)}}if("void"!==a)return c?e.format(`${c}( ${l}, ${u} )`,s,t):e.isMatrix(a)&&"float"===o?e.format(`${u} ${n} ${l}`,s,t):e.format(`${l} ${n} ${u}`,s,t)}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const gg=Jf(mg,"+").setParameterLength(2,1/0).setName("add"),_g=Jf(mg,"-").setParameterLength(2,1/0).setName("sub"),vg=Jf(mg,"*").setParameterLength(2,1/0).setName("mul"),yg=Jf(mg,"/").setParameterLength(2,1/0).setName("div"),xg=Jf(mg,"%").setParameterLength(2).setName("mod"),bg=Jf(mg,"==").setParameterLength(2).setName("equal"),Tg=Jf(mg,"!=").setParameterLength(2).setName("notEqual"),Sg=Jf(mg,"<").setParameterLength(2).setName("lessThan"),Mg=Jf(mg,">").setParameterLength(2).setName("greaterThan"),wg=Jf(mg,"<=").setParameterLength(2).setName("lessThanEqual"),Eg=Jf(mg,">=").setParameterLength(2).setName("greaterThanEqual"),Ag=Jf(mg,"&&").setParameterLength(2,1/0).setName("and"),Rg=Jf(mg,"||").setParameterLength(2,1/0).setName("or"),Cg=Jf(mg,"!").setParameterLength(1).setName("not"),Ng=Jf(mg,"^^").setParameterLength(2).setName("xor"),Pg=Jf(mg,"&").setParameterLength(2).setName("bitAnd"),Lg=Jf(mg,"~").setParameterLength(2).setName("bitNot"),Dg=Jf(mg,"|").setParameterLength(2).setName("bitOr"),Ig=Jf(mg,"^").setParameterLength(2).setName("bitXor"),Ug=Jf(mg,"<<").setParameterLength(2).setName("shiftLeft"),Og=Jf(mg,">>").setParameterLength(2).setName("shiftRight"),Fg=nm(([e])=>(e.addAssign(1),e)),Bg=nm(([e])=>(e.subAssign(1),e)),kg=nm(([e])=>{const t=um(e).toConst();return e.addAssign(1),t}),zg=nm(([e])=>{const t=um(e).toConst();return e.subAssign(1),t});Mf("add",gg),Mf("sub",_g),Mf("mul",vg),Mf("div",yg),Mf("mod",xg),Mf("equal",bg),Mf("notEqual",Tg),Mf("lessThan",Sg),Mf("greaterThan",Mg),Mf("lessThanEqual",wg),Mf("greaterThanEqual",Eg),Mf("and",Ag),Mf("or",Rg),Mf("not",Cg),Mf("xor",Ng),Mf("bitAnd",Pg),Mf("bitNot",Lg),Mf("bitOr",Dg),Mf("bitXor",Ig),Mf("shiftLeft",Ug),Mf("shiftRight",Og),Mf("incrementBefore",Fg),Mf("decrementBefore",Bg),Mf("increment",kg),Mf("decrement",zg);Mf("modInt",(e,t)=>(console.warn('THREE.TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.'),xg(um(e),um(t))));class Vg extends df{static get type(){return"MathNode"}constructor(e,t,n=null,r=null){if(super(),(e===Vg.MAX||e===Vg.MIN)&&arguments.length>3){let i=new Vg(e,t,n);for(let t=2;t<arguments.length-1;t++)i=new Vg(e,i,arguments[t]);t=i,n=arguments[arguments.length-1],r=null}this.method=e,this.aNode=t,this.bNode=n,this.cNode=r,this.isMathNode=!0}getInputType(e){const t=this.aNode.getNodeType(e),n=this.bNode?this.bNode.getNodeType(e):null,r=this.cNode?this.cNode.getNodeType(e):null,i=e.isMatrix(t)?0:e.getTypeLength(t),s=e.isMatrix(n)?0:e.getTypeLength(n),a=e.isMatrix(r)?0:e.getTypeLength(r);return i>s&&i>a?t:s>a?n:a>i?r:t}getNodeType(e){const t=this.method;return t===Vg.LENGTH||t===Vg.DISTANCE||t===Vg.DOT?"float":t===Vg.CROSS?"vec3":t===Vg.ALL||t===Vg.ANY?"bool":t===Vg.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):this.getInputType(e)}setup(e){const{aNode:t,bNode:n,method:r}=this;let i=null;if(r===Vg.ONE_MINUS)i=_g(1,t);else if(r===Vg.RECIPROCAL)i=yg(1,t);else if(r===Vg.DIFFERENCE)i=c_(_g(t,n));else if(r===Vg.TRANSFORM_DIRECTION){let r=t,s=n;e.isMatrix(r.getNodeType(e))?s=xm(gm(s),0):r=xm(gm(r),0);const a=vg(r,s).xyz;i=n_(a)}return null!==i?i:super.setup(e)}generate(e,t){if(e.getNodeProperties(this).outputNode)return super.generate(e,t);let n=this.method;const r=this.getNodeType(e),i=this.getInputType(e),s=this.aNode,a=this.bNode,o=this.cNode,l=e.renderer.coordinateSystem;if(n===Vg.NEGATE)return e.format("( - "+s.build(e,i)+" )",r,t);{const u=[];return n===Vg.CROSS?u.push(s.build(e,r),a.build(e,r)):l===yt&&n===Vg.STEP?u.push(s.build(e,1===e.getTypeLength(s.getNodeType(e))?"float":i),a.build(e,i)):l!==yt||n!==Vg.MIN&&n!==Vg.MAX?n===Vg.REFRACT?u.push(s.build(e,i),a.build(e,i),o.build(e,"float")):n===Vg.MIX?u.push(s.build(e,i),a.build(e,i),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":i)):(l===xt&&n===Vg.ATAN&&null!==a&&(n="atan2"),"fragment"===e.shaderStage||n!==Vg.DFDX&&n!==Vg.DFDY||(console.warn(`THREE.TSL: '${n}' is not supported in the ${e.shaderStage} stage.`),n="/*"+n+"*/"),u.push(s.build(e,i)),null!==a&&u.push(a.build(e,i)),null!==o&&u.push(o.build(e,i))):u.push(s.build(e,i),a.build(e,1===e.getTypeLength(a.getNodeType(e))?"float":i)),e.format(`${e.getMethod(n,r)}( ${u.join(", ")} )`,r,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}Vg.ALL="all",Vg.ANY="any",Vg.RADIANS="radians",Vg.DEGREES="degrees",Vg.EXP="exp",Vg.EXP2="exp2",Vg.LOG="log",Vg.LOG2="log2",Vg.SQRT="sqrt",Vg.INVERSE_SQRT="inversesqrt",Vg.FLOOR="floor",Vg.CEIL="ceil",Vg.NORMALIZE="normalize",Vg.FRACT="fract",Vg.SIN="sin",Vg.COS="cos",Vg.TAN="tan",Vg.ASIN="asin",Vg.ACOS="acos",Vg.ATAN="atan",Vg.ABS="abs",Vg.SIGN="sign",Vg.LENGTH="length",Vg.NEGATE="negate",Vg.ONE_MINUS="oneMinus",Vg.DFDX="dFdx",Vg.DFDY="dFdy",Vg.ROUND="round",Vg.RECIPROCAL="reciprocal",Vg.TRUNC="trunc",Vg.FWIDTH="fwidth",Vg.TRANSPOSE="transpose",Vg.BITCAST="bitcast",Vg.EQUALS="equals",Vg.MIN="min",Vg.MAX="max",Vg.STEP="step",Vg.REFLECT="reflect",Vg.DISTANCE="distance",Vg.DIFFERENCE="difference",Vg.DOT="dot",Vg.CROSS="cross",Vg.POW="pow",Vg.TRANSFORM_DIRECTION="transformDirection",Vg.MIX="mix",Vg.CLAMP="clamp",Vg.REFRACT="refract",Vg.SMOOTHSTEP="smoothstep",Vg.FACEFORWARD="faceforward";const Gg=lm(1e-6),Hg=lm(Math.PI),jg=Jf(Vg,Vg.ALL).setParameterLength(1),Wg=Jf(Vg,Vg.ANY).setParameterLength(1),Xg=Jf(Vg,Vg.RADIANS).setParameterLength(1),qg=Jf(Vg,Vg.DEGREES).setParameterLength(1),$g=Jf(Vg,Vg.EXP).setParameterLength(1),Yg=Jf(Vg,Vg.EXP2).setParameterLength(1),Kg=Jf(Vg,Vg.LOG).setParameterLength(1),Qg=Jf(Vg,Vg.LOG2).setParameterLength(1),Zg=Jf(Vg,Vg.SQRT).setParameterLength(1),Jg=Jf(Vg,Vg.INVERSE_SQRT).setParameterLength(1),e_=Jf(Vg,Vg.FLOOR).setParameterLength(1),t_=Jf(Vg,Vg.CEIL).setParameterLength(1),n_=Jf(Vg,Vg.NORMALIZE).setParameterLength(1),r_=Jf(Vg,Vg.FRACT).setParameterLength(1),i_=Jf(Vg,Vg.SIN).setParameterLength(1),s_=Jf(Vg,Vg.COS).setParameterLength(1),a_=Jf(Vg,Vg.TAN).setParameterLength(1),o_=Jf(Vg,Vg.ASIN).setParameterLength(1),l_=Jf(Vg,Vg.ACOS).setParameterLength(1),u_=Jf(Vg,Vg.ATAN).setParameterLength(1,2),c_=Jf(Vg,Vg.ABS).setParameterLength(1),h_=Jf(Vg,Vg.SIGN).setParameterLength(1),d_=Jf(Vg,Vg.LENGTH).setParameterLength(1),p_=Jf(Vg,Vg.NEGATE).setParameterLength(1),f_=Jf(Vg,Vg.ONE_MINUS).setParameterLength(1),m_=Jf(Vg,Vg.DFDX).setParameterLength(1),g_=Jf(Vg,Vg.DFDY).setParameterLength(1),__=Jf(Vg,Vg.ROUND).setParameterLength(1),v_=Jf(Vg,Vg.RECIPROCAL).setParameterLength(1),y_=Jf(Vg,Vg.TRUNC).setParameterLength(1),x_=Jf(Vg,Vg.FWIDTH).setParameterLength(1),b_=Jf(Vg,Vg.TRANSPOSE).setParameterLength(1),T_=Jf(Vg,Vg.MIN).setParameterLength(2,1/0),S_=Jf(Vg,Vg.MAX).setParameterLength(2,1/0),M_=Jf(Vg,Vg.STEP).setParameterLength(2),w_=Jf(Vg,Vg.REFLECT).setParameterLength(2),E_=Jf(Vg,Vg.DISTANCE).setParameterLength(2),A_=Jf(Vg,Vg.DIFFERENCE).setParameterLength(2),R_=Jf(Vg,Vg.DOT).setParameterLength(2),C_=Jf(Vg,Vg.CROSS).setParameterLength(2),N_=Jf(Vg,Vg.POW).setParameterLength(2),P_=Jf(Vg,Vg.POW,2).setParameterLength(1),L_=Jf(Vg,Vg.POW,3).setParameterLength(1),D_=Jf(Vg,Vg.POW,4).setParameterLength(1),I_=Jf(Vg,Vg.TRANSFORM_DIRECTION).setParameterLength(2),U_=e=>R_(e,e),O_=Jf(Vg,Vg.MIX).setParameterLength(3),F_=(e,t=0,n=1)=>Kf(new Vg(Vg.CLAMP,Kf(e),Kf(t),Kf(n))),B_=e=>F_(e),k_=Jf(Vg,Vg.REFRACT).setParameterLength(3),z_=Jf(Vg,Vg.SMOOTHSTEP).setParameterLength(3),V_=Jf(Vg,Vg.FACEFORWARD).setParameterLength(3),G_=nm(([e])=>{const t=R_(e.xy,dm(12.9898,78.233)),n=xg(t,Hg);return r_(i_(n).mul(43758.5453))});Mf("all",jg),Mf("any",Wg),Mf("equals",(e,t)=>(console.warn('THREE.TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"'),bg(e,t))),Mf("radians",Xg),Mf("degrees",qg),Mf("exp",$g),Mf("exp2",Yg),Mf("log",Kg),Mf("log2",Qg),Mf("sqrt",Zg),Mf("inverseSqrt",Jg),Mf("floor",e_),Mf("ceil",t_),Mf("normalize",n_),Mf("fract",r_),Mf("sin",i_),Mf("cos",s_),Mf("tan",a_),Mf("asin",o_),Mf("acos",l_),Mf("atan",u_),Mf("abs",c_),Mf("sign",h_),Mf("length",d_),Mf("lengthSq",U_),Mf("negate",p_),Mf("oneMinus",f_),Mf("dFdx",m_),Mf("dFdy",g_),Mf("round",__),Mf("reciprocal",v_),Mf("trunc",y_),Mf("fwidth",x_),Mf("atan2",(e,t)=>(console.warn('THREE.TSL: "atan2" is overloaded. Use "atan" instead.'),u_(e,t))),Mf("min",T_),Mf("max",S_),Mf("step",(e,t)=>M_(t,e)),Mf("reflect",w_),Mf("distance",E_),Mf("dot",R_),Mf("cross",C_),Mf("pow",N_),Mf("pow2",P_),Mf("pow3",L_),Mf("pow4",D_),Mf("transformDirection",I_),Mf("mix",(e,t,n)=>O_(t,n,e)),Mf("clamp",F_),Mf("refract",k_),Mf("smoothstep",(e,t,n)=>z_(t,n,e)),Mf("faceForward",V_),Mf("difference",A_),Mf("saturate",B_),Mf("cbrt",e=>vg(h_(e),N_(c_(e),1/3))),Mf("transpose",b_),Mf("rand",G_);class H_ extends uf{static get type(){return"ConditionalNode"}constructor(e,t,n=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=n}getNodeType(e){const{ifNode:t,elseNode:n}=e.getNodeProperties(this);if(void 0===t)return this.setup(e),this.getNodeType(e);const r=t.getNodeType(e);if(null!==n){const t=n.getNodeType(e);if(e.getTypeLength(t)>e.getTypeLength(r))return t}return r}setup(e){const t=this.condNode.cache(),n=this.ifNode.cache(),r=this.elseNode?this.elseNode.cache():null,i=e.context.nodeBlock;e.getDataFromNode(n).parentNodeBlock=i,null!==r&&(e.getDataFromNode(r).parentNodeBlock=i);const s=e.getNodeProperties(this);s.condNode=t,s.ifNode=n.context({nodeBlock:n}),s.elseNode=r?r.context({nodeBlock:r}):null}generate(e,t){const n=this.getNodeType(e),r=e.getDataFromNode(this);if(void 0!==r.nodeProperty)return r.nodeProperty;const{condNode:i,ifNode:s,elseNode:a}=e.getNodeProperties(this),o=e.currentFunctionNode,l="void"!==t,u=l?Rm(n).build(e):"";r.nodeProperty=u;const c=i.build(e,"bool");e.addFlowCode(`\n${e.tab}if ( ${c} ) {\n\n`).addFlowTab();let h=s.build(e,n);if(h&&(l?h=u+" = "+h+";":(h="return "+h+";",null===o&&(console.warn("THREE.TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values."),h="// "+h))),e.removeFlowTab().addFlowCode(e.tab+"\t"+h+"\n\n"+e.tab+"}"),null!==a){e.addFlowCode(" else {\n\n").addFlowTab();let t=a.build(e,n);t&&(l?t=u+" = "+t+";":(t="return "+t+";",null===o&&(console.warn("THREE.TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values."),t="// "+t))),e.removeFlowTab().addFlowCode(e.tab+"\t"+t+"\n\n"+e.tab+"}\n\n")}else e.addFlowCode("\n\n");return e.format(u,n,t)}}const j_=Jf(H_).setParameterLength(2,3);Mf("select",j_);class W_ extends uf{static get type(){return"ContextNode"}constructor(e,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}getNodeType(e){return this.node.getNodeType(e)}analyze(e){const t=e.getContext();e.setContext({...e.context,...this.value}),this.node.build(e),e.setContext(t)}setup(e){const t=e.getContext();e.setContext({...e.context,...this.value}),this.node.build(e),e.setContext(t)}generate(e,t){const n=e.getContext();e.setContext({...e.context,...this.value});const r=this.node.build(e,t);return e.setContext(n),r}}const X_=Jf(W_).setParameterLength(1,2);Mf("context",X_),Mf("label",(e,t)=>X_(e,{label:t}));class q_ extends uf{static get type(){return"VarNode"}constructor(e,t=null,n=!1){super(),this.node=e,this.name=t,this.global=!0,this.isVarNode=!0,this.readOnly=n,this.parents=!0}getMemberType(e,t){return this.node.getMemberType(e,t)}getElementType(e){return this.node.getElementType(e)}getNodeType(e){return this.node.getNodeType(e)}generate(e){const{node:t,name:n,readOnly:r}=this,{renderer:i}=e,s=!0===i.backend.isWebGPUBackend;let a=!1,o=!1;r&&(a=e.isDeterministic(t),o=s?r:a);const l=e.getVectorType(this.getNodeType(e)),u=t.build(e,l),c=e.getVarFromNode(this,n,l,void 0,o),h=e.getPropertyName(c);let d=h;if(o)if(s)d=a?`const ${h}`:`let ${h}`;else{const n=e.getArrayCount(t);d=`const ${e.getVar(c.type,h,n)}`}return e.addLineFlowCode(`${d} = ${u}`,this),h}}const $_=Jf(q_);Mf("toVar",(e,t=null)=>$_(e,t).toStack()),Mf("toConst",(e,t=null)=>$_(e,t,!0).toStack());Mf("temp",e=>(console.warn('TSL: "temp( node )" is deprecated. Use "Var( node )" or "node.toVar()" instead.'),$_(e)));class Y_ extends uf{static get type(){return"SubBuild"}constructor(e,t,n=null){super(n),this.node=e,this.name=t,this.isSubBuildNode=!0}getNodeType(e){if(null!==this.nodeType)return this.nodeType;e.addSubBuild(this.name);const t=this.node.getNodeType(e);return e.removeSubBuild(),t}build(e,...t){e.addSubBuild(this.name);const n=this.node.build(e,...t);return e.removeSubBuild(),n}}const K_=(e,t,n=null)=>Kf(new Y_(Kf(e),t,n));class Q_ extends uf{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=e,this.name=t,this.isVaryingNode=!0,this.interpolationType=null,this.interpolationSampling=null,this.global=!0}setInterpolation(e,t=null){return this.interpolationType=e,this.interpolationSampling=t,this}getHash(e){return this.name||super.getHash(e)}getNodeType(e){return this.node.getNodeType(e)}setupVarying(e){const t=e.getNodeProperties(this);let n=t.varying;if(void 0===n){const r=this.name,i=this.getNodeType(e),s=this.interpolationType,a=this.interpolationSampling;t.varying=n=e.getVaryingFromNode(this,r,i,s,a),t.node=K_(this.node,"VERTEX")}return n.needsInterpolation||(n.needsInterpolation="fragment"===e.shaderStage),n}setup(e){this.setupVarying(e),e.flowNodeFromShaderStage(Yp,this.node)}analyze(e){this.setupVarying(e),e.flowNodeFromShaderStage(Yp,this.node)}generate(e){const t=e.getSubBuildProperty("property",e.currentStack),n=e.getNodeProperties(this),r=this.setupVarying(e);if(void 0===n[t]){const i=this.getNodeType(e),s=e.getPropertyName(r,Yp);e.flowNodeFromShaderStage(Yp,n.node,i,s),n[t]=s}return e.getPropertyName(r)}}const Z_=Jf(Q_).setParameterLength(1,2);Mf("toVarying",Z_),Mf("toVertexStage",e=>Z_(e)),Mf("varying",(...e)=>(console.warn("THREE.TSL: .varying() has been renamed to .toVarying()."),Z_(...e))),Mf("vertexStage",(...e)=>(console.warn("THREE.TSL: .vertexStage() has been renamed to .toVertexStage()."),Z_(...e)));const J_=nm(([e])=>{const t=e.mul(.9478672986).add(.0521327014).pow(2.4),n=e.mul(.0773993808),r=e.lessThanEqual(.04045);return O_(t,n,r)}).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),ev=nm(([e])=>{const t=e.pow(.41666).mul(1.055).sub(.055),n=e.mul(12.92),r=e.lessThanEqual(.0031308);return O_(t,n,r)}).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),tv="WorkingColorSpace";class nv extends df{static get type(){return"ColorSpaceNode"}constructor(e,t,n){super("vec4"),this.colorNode=e,this.source=t,this.target=n}resolveColorSpace(e,t){return t===tv?$t.workingColorSpace:"OutputColorSpace"===t?e.context.outputColorSpace||e.renderer.outputColorSpace:t}setup(e){const{colorNode:t}=this,n=this.resolveColorSpace(e,this.source),r=this.resolveColorSpace(e,this.target);let i=t;return!1!==$t.enabled&&n!==r&&n&&r?($t.getTransfer(n)===at&&(i=xm(J_(i.rgb),i.a)),$t.getPrimaries(n)!==$t.getPrimaries(r)&&(i=xm(wm($t._getMatrix(new Bt,n,r)).mul(i.rgb),i.a)),$t.getTransfer(r)===at&&(i=xm(ev(i.rgb),i.a)),i):i}}const rv=(e,t)=>Kf(new nv(Kf(e),t,tv));Mf("workingToColorSpace",(e,t)=>Kf(new nv(Kf(e),tv,t))),Mf("colorSpaceToWorking",rv);let iv=class extends cf{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),n=this.referenceNode.getNodeType(),r=this.getNodeType();return e.format(t,n,r)}};class sv extends uf{static get type(){return"ReferenceBaseNode"}constructor(e,t,n=null,r=null){super(),this.property=e,this.uniformType=t,this.object=n,this.count=r,this.properties=e.split("."),this.reference=n,this.node=null,this.group=null,this.updateType=Jp}setGroup(e){return this.group=e,this}element(e){return Kf(new iv(this,Kf(e)))}setNodeType(e){const t=cg(null,e).getSelf();null!==this.group&&t.setGroup(this.group),this.node=t}getNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let n=e[t[0]];for(let e=1;e<t.length;e++)n=n[t[e]];return n}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 av extends sv{static get type(){return"RendererReferenceNode"}constructor(e,t,n=null){super(e,t,n),this.renderer=n,this.setGroup(og)}updateReference(e){return this.reference=null!==this.renderer?this.renderer:e.renderer,this.reference}}const ov=(e,t,n=null)=>Kf(new av(e,t,n));class lv extends df{static get type(){return"ToneMappingNode"}constructor(e,t=uv,n=null){super("vec3"),this.toneMapping=e,this.exposureNode=t,this.colorNode=n}customCacheKey(){return Vp(this.toneMapping)}setup(e){const t=this.colorNode||e.context.color,n=this.toneMapping;if(0===n)return t;let r=null;const i=e.renderer.library.getToneMappingFunction(n);return null!==i?r=xm(i(t.rgb,this.exposureNode),t.a):(console.error("ToneMappingNode: Unsupported Tone Mapping configuration.",n),r=t),r}}const uv=ov("toneMappingExposure","float");Mf("toneMapping",(e,t,n)=>((e,t,n)=>Kf(new lv(e,Kf(t),Kf(n))))(t,n,e));class cv extends vf{static get type(){return"BufferAttributeNode"}constructor(e,t=null,n=0,r=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=n,this.bufferOffset=r,this.usage=gt,this.instanced=!1,this.attribute=null,this.global=!0,e&&!0===e.isBufferAttribute&&(this.attribute=e,this.usage=e.usage,this.instanced=e.isInstancedBufferAttribute)}getHash(e){if(0===this.bufferStride&&0===this.bufferOffset){let t=e.globalCache.getData(this.value);return void 0===t&&(t={node:this},e.globalCache.setData(this.value,t)),t.node.uuid}return this.uuid}getNodeType(e){return null===this.bufferType&&(this.bufferType=e.getTypeFromAttribute(this.attribute)),this.bufferType}setup(e){if(null!==this.attribute)return;const t=this.getNodeType(e),n=this.value,r=e.getTypeLength(t),i=this.bufferStride||r,s=this.bufferOffset,a=!0===n.isInterleavedBuffer?n:new Di(n,i),o=new Ui(a,r,s);a.setUsage(this.usage),this.attribute=o,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){const t=this.getNodeType(e),n=e.getBufferAttributeFromNode(this,t),r=e.getPropertyName(n);let i=null;if("vertex"===e.shaderStage||"compute"===e.shaderStage)this.name=r,i=r;else{i=Z_(this).build(e,t)}return i}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}}const hv=(e,t=null,n=0,r=0)=>Kf(new cv(e,t,n,r)),dv=(e,t=null,n=0,r=0)=>hv(e,t,n,r).setInstanced(!0),pv=(e,t=null,n=0,r=0)=>((e,t=null,n=0,r=0)=>hv(e,t,n,r).setUsage(_t))(e,t,n,r).setInstanced(!0);Mf("toAttribute",e=>hv(e.value));class fv extends uf{static get type(){return"ComputeNode"}constructor(e,t,n=[64]){super("void"),this.isComputeNode=!0,this.computeNode=e,this.count=t,this.workgroupSize=n,this.dispatchCount=0,this.version=1,this.name="",this.updateBeforeType=Jp,this.onInitFunction=null,this.updateDispatchCount()}dispose(){this.dispatchEvent({type:"dispose"})}label(e){return this.name=e,this}updateDispatchCount(){const{count:e,workgroupSize:t}=this;let n=t[0];for(let e=1;e<t.length;e++)n*=t[e];this.dispatchCount=Math.ceil(e/n)}onInit(e){return this.onInitFunction=e,this}updateBefore({renderer:e}){e.compute(this)}setup(e){const t=this.computeNode.build(e);if(t){e.getNodeProperties(this).outputComputeNode=t.outputNode,t.outputNode=null}return t}generate(e,t){const{shaderStage:n}=e;if("compute"===n){const t=this.computeNode.build(e,"void");""!==t&&e.addLineFlowCode(t,this)}else{const n=e.getNodeProperties(this).outputComputeNode;if(n)return n.build(e,t)}}}Mf("compute",(e,t,n)=>Kf(new fv(Kf(e),t,n)));class mv extends uf{static get type(){return"CacheNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isCacheNode=!0}getNodeType(e){const t=e.getCache(),n=e.getCacheFromNode(this,this.parent);e.setCache(n);const r=this.node.getNodeType(e);return e.setCache(t),r}build(e,...t){const n=e.getCache(),r=e.getCacheFromNode(this,this.parent);e.setCache(r);const i=this.node.build(e,...t);return e.setCache(n),i}}const gv=(e,t)=>Kf(new mv(Kf(e),t));Mf("cache",gv);class _v extends uf{static get type(){return"BypassNode"}constructor(e,t){super(),this.isBypassNode=!0,this.outputNode=e,this.callNode=t}getNodeType(e){return this.outputNode.getNodeType(e)}generate(e){const t=this.callNode.build(e,"void");return""!==t&&e.addLineFlowCode(t,this),this.outputNode.build(e)}}Mf("bypass",Jf(_v).setParameterLength(2));class vv extends uf{static get type(){return"RemapNode"}constructor(e,t,n,r=lm(0),i=lm(1)){super(),this.node=e,this.inLowNode=t,this.inHighNode=n,this.outLowNode=r,this.outHighNode=i,this.doClamp=!0}setup(){const{node:e,inLowNode:t,inHighNode:n,outLowNode:r,outHighNode:i,doClamp:s}=this;let a=e.sub(t).div(n.sub(t));return!0===s&&(a=a.clamp()),a.mul(i.sub(r)).add(r)}}const yv=Jf(vv,null,null,{doClamp:!1}).setParameterLength(3,5),xv=Jf(vv).setParameterLength(3,5);Mf("remap",yv),Mf("remapClamp",xv);class bv extends uf{static get type(){return"ExpressionNode"}constructor(e="",t="void"){super(t),this.snippet=e}generate(e,t){const n=this.getNodeType(e),r=this.snippet;if("void"!==n)return e.format(r,n,t);e.addLineFlowCode(r,this)}}const Tv=Jf(bv).setParameterLength(1,2);Mf("discard",e=>(e?j_(e,Tv("discard")):Tv("discard")).toStack());class Sv extends df{static get type(){return"RenderOutputNode"}constructor(e,t,n){super("vec4"),this.colorNode=e,this.toneMapping=t,this.outputColorSpace=n,this.isRenderOutputNode=!0}setup({context:e}){let t=this.colorNode||e.color;const n=(null!==this.toneMapping?this.toneMapping:e.toneMapping)||0,r=(null!==this.outputColorSpace?this.outputColorSpace:e.outputColorSpace)||nt;return 0!==n&&(t=t.toneMapping(n)),r!==nt&&r!==$t.workingColorSpace&&(t=t.workingToColorSpace(r)),t}}Mf("renderOutput",(e,t=null,n=null)=>Kf(new Sv(Kf(e),t,n)));class Mv extends df{static get type(){return"DebugNode"}constructor(e,t=null){super(),this.node=e,this.callback=t}getNodeType(e){return this.node.getNodeType(e)}setup(e){return this.node.build(e)}analyze(e){return this.node.build(e)}generate(e){const t=this.callback,n=this.node.build(e),r="--- TSL debug - "+e.shaderStage+" shader ---",i="-".repeat(r.length);let s="";return s+="// #"+r+"#\n",s+=e.flow.code.replace(/^\t/gm,"")+"\n",s+="/* ... */ "+n+" /* ... */\n",s+="// #"+i+"#\n",null!==t?t(e,s):console.log(s),n}}Mf("debug",(e,t=null)=>Kf(new Mv(Kf(e),t)));class wv extends uf{static get type(){return"AttributeNode"}constructor(e,t=null){super(t),this.global=!0,this._attributeName=e}getHash(e){return this.getAttributeName(e)}getNodeType(e){let t=this.nodeType;if(null===t){const n=this.getAttributeName(e);if(e.hasGeometryAttribute(n)){const r=e.geometry.getAttribute(n);t=e.getTypeFromAttribute(r)}else t="float"}return t}setAttributeName(e){return this._attributeName=e,this}getAttributeName(){return this._attributeName}generate(e){const t=this.getAttributeName(e),n=this.getNodeType(e);if(!0===e.hasGeometryAttribute(t)){const r=e.geometry.getAttribute(t),i=e.getTypeFromAttribute(r),s=e.getAttribute(t,i);if("vertex"===e.shaderStage)return e.format(s.name,i,n);return Z_(this).build(e,n)}return console.warn(`AttributeNode: Vertex attribute "${t}" not found on geometry.`),e.generateConst(n)}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 Ev=(e,t=null)=>Kf(new wv(e,t)),Av=(e=0)=>Ev("uv"+(e>0?e:""),"vec2");class Rv extends uf{static get type(){return"TextureSizeNode"}constructor(e,t=null){super("uvec2"),this.isTextureSizeNode=!0,this.textureNode=e,this.levelNode=t}generate(e,t){const n=this.textureNode.build(e,"property"),r=null===this.levelNode?"0":this.levelNode.build(e,"int");return e.format(`${e.getMethod("textureDimensions")}( ${n}, ${r} )`,this.getNodeType(e),t)}}const Cv=Jf(Rv).setParameterLength(1,2);class Nv extends ug{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=Qp}get textureNode(){return this._textureNode}get texture(){return this._textureNode.value}update(){const e=this.texture,t=e.images,n=t&&t.length>0?t[0]&&t[0].image||t[0]:e.image;if(n&&void 0!==n.width){const{width:e,height:t}=n;this.value=Math.log2(Math.max(e,t))}}}const Pv=Jf(Nv).setParameterLength(1),Lv=new sn;class Dv extends ug{static get type(){return"TextureNode"}constructor(e=Lv,t=null,n=null,r=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=n,this.biasNode=r,this.compareNode=null,this.depthNode=null,this.gradNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=Kp,this.referenceNode=null,this._value=e,this._matrixUniform=null,this.setUpdateMatrix(null===t)}set value(e){this.referenceNode?this.referenceNode.value=e:this._value=e}get value(){return this.referenceNode?this.referenceNode.value:this._value}getUniformHash(){return this.value.uuid}getNodeType(){return!0===this.value.isDepthTexture?"float":this.value.type===oe?"uvec4":this.value.type===ae?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return Av(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return null===this._matrixUniform&&(this._matrixUniform=cg(this.value.matrix)),this._matrixUniform.mul(gm(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this.updateType=e?Jp:Kp,this}setupUV(e,t){const n=this.value;return e.isFlipY()&&(n.image instanceof ImageBitmap&&!0===n.flipY||!0===n.isRenderTargetTexture||!0===n.isFramebufferTexture||!0===n.isDepthTexture)&&(t=this.sampler?t.flipY():t.setY(um(Cv(this,this.levelNode).y).sub(t.y).sub(1))),t}setup(e){const t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;const n=this.value;if(!n||!0!==n.isTexture)throw new Error("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().");let r=this.uvNode;null!==r&&!0!==e.context.forceUVContext||!e.context.getUV||(r=e.context.getUV(this,e)),r||(r=this.getDefaultUV()),!0===this.updateMatrix&&(r=this.getTransformedUV(r)),r=this.setupUV(e,r);let i=this.levelNode;null===i&&e.context.getTextureLevel&&(i=e.context.getTextureLevel(this)),t.uvNode=r,t.levelNode=i,t.biasNode=this.biasNode,t.compareNode=this.compareNode,t.gradNode=this.gradNode,t.depthNode=this.depthNode}generateUV(e,t){return t.build(e,!0===this.sampler?"vec2":"ivec2")}generateSnippet(e,t,n,r,i,s,a,o){const l=this.value;let u;return u=r?e.generateTextureLevel(l,t,n,r,s):i?e.generateTextureBias(l,t,n,i,s):o?e.generateTextureGrad(l,t,n,o,s):a?e.generateTextureCompare(l,t,n,a,s):!1===this.sampler?e.generateTextureLoad(l,t,n,s):e.generateTexture(l,t,n,s),u}generate(e,t){const n=this.value,r=e.getNodeProperties(this),i=super.generate(e,"property");if(/^sampler/.test(t))return i+"_sampler";if(e.isReference(t))return i;{const s=e.getDataFromNode(this);let a=s.propertyName;if(void 0===a){const{uvNode:t,levelNode:n,biasNode:o,compareNode:l,depthNode:u,gradNode:c}=r,h=this.generateUV(e,t),d=n?n.build(e,"float"):null,p=o?o.build(e,"float"):null,f=u?u.build(e,"int"):null,m=l?l.build(e,"float"):null,g=c?[c[0].build(e,"vec2"),c[1].build(e,"vec2")]:null,_=e.getVarFromNode(this);a=e.getPropertyName(_);const v=this.generateSnippet(e,i,h,d,p,f,m,g);e.addLineFlowCode(`${a} = ${v}`,this),s.snippet=v,s.propertyName=a}let o=a;const l=this.getNodeType(e);return e.needsToWorkingColorSpace(n)&&(o=rv(Tv(o,l),n.colorSpace).setup(e).build(e,l)),e.format(o,l,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}uv(e){return console.warn("THREE.TextureNode: .uv() has been renamed. Use .sample() instead."),this.sample(e)}sample(e){const t=this.clone();return t.uvNode=Kf(e),t.referenceNode=this.getSelf(),Kf(t)}blur(e){const t=this.clone();t.biasNode=Kf(e).mul(Pv(t)),t.referenceNode=this.getSelf();const n=t.value;return!1===t.generateMipmaps&&(n&&!1===n.generateMipmaps||n.minFilter===K||n.magFilter===K)&&(console.warn("THREE.TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture."),t.biasNode=null),Kf(t)}level(e){const t=this.clone();return t.levelNode=Kf(e),t.referenceNode=this.getSelf(),Kf(t)}size(e){return Cv(this,e)}bias(e){const t=this.clone();return t.biasNode=Kf(e),t.referenceNode=this.getSelf(),Kf(t)}compare(e){const t=this.clone();return t.compareNode=Kf(e),t.referenceNode=this.getSelf(),Kf(t)}grad(e,t){const n=this.clone();return n.gradNode=[Kf(e),Kf(t)],n.referenceNode=this.getSelf(),Kf(n)}depth(e){const t=this.clone();return t.depthNode=Kf(e),t.referenceNode=this.getSelf(),Kf(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()}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}}const Iv=Jf(Dv).setParameterLength(1,4).setName("texture"),Uv=(e=Lv,t=null,n=null,r=null)=>{let i;return e&&!0===e.isTextureNode?(i=Kf(e.clone()),i.referenceNode=e.getSelf(),null!==t&&(i.uvNode=Kf(t)),null!==n&&(i.levelNode=Kf(n)),null!==r&&(i.biasNode=Kf(r))):i=Iv(e,t,n,r),i},Ov=(...e)=>Uv(...e).setSampler(!1);class Fv extends ug{static get type(){return"BufferNode"}constructor(e,t,n=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=n}getElementType(e){return this.getNodeType(e)}getInputType(){return"buffer"}}const Bv=(e,t,n)=>Kf(new Fv(e,t,n));class kv extends cf{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),n=this.getNodeType(),r=this.node.getPaddedType();return e.format(t,r,n)}}class zv extends Fv{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=null===t?Xp(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=Zp,this.isArrayBufferNode=!0}getNodeType(){return this.paddedType}getElementType(){return this.elementType}getPaddedType(){const e=this.elementType;let t="vec4";return"mat2"===e?t="mat2":!0===/mat/.test(e)?t="mat4":"i"===e.charAt(0)?t="ivec4":"u"===e.charAt(0)&&(t="uvec4"),t}update(){const{array:e,value:t}=this,n=this.elementType;if("float"===n||"int"===n||"uint"===n)for(let n=0;n<e.length;n++){t[4*n]=e[n]}else if("color"===n)for(let n=0;n<e.length;n++){const r=4*n,i=e[n];t[r]=i.r,t[r+1]=i.g,t[r+2]=i.b||0}else if("mat2"===n)for(let n=0;n<e.length;n++){const r=4*n,i=e[n];t[r]=i.elements[0],t[r+1]=i.elements[1],t[r+2]=i.elements[2],t[r+3]=i.elements[3]}else if("mat3"===n)for(let n=0;n<e.length;n++){const r=16*n,i=e[n];t[r]=i.elements[0],t[r+1]=i.elements[1],t[r+2]=i.elements[2],t[r+4]=i.elements[3],t[r+5]=i.elements[4],t[r+6]=i.elements[5],t[r+8]=i.elements[6],t[r+9]=i.elements[7],t[r+10]=i.elements[8],t[r+15]=1}else if("mat4"===n)for(let n=0;n<e.length;n++){const r=16*n,i=e[n];for(let e=0;e<i.elements.length;e++)t[r+e]=i.elements[e]}else for(let n=0;n<e.length;n++){const r=4*n,i=e[n];t[r]=i.x,t[r+1]=i.y,t[r+2]=i.z||0,t[r+3]=i.w||0}}setup(e){const t=this.array.length,n=this.elementType;let r=Float32Array;const i=this.paddedType,s=e.getTypeLength(i);return"i"===n.charAt(0)&&(r=Int32Array),"u"===n.charAt(0)&&(r=Uint32Array),this.value=new r(t*s),this.bufferCount=t,this.bufferType=i,super.setup(e)}element(e){return Kf(new kv(this,Kf(e)))}}const Vv=(e,t)=>Kf(new zv(e,t));const Gv=Jf(class extends uf{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}}).setParameterLength(1),Hv=cg(0,"uint").label("u_cameraIndex").setGroup(sg("cameraIndex")).toVarying("v_cameraIndex"),jv=cg("float").label("cameraNear").setGroup(og).onRenderUpdate(({camera:e})=>e.near),Wv=cg("float").label("cameraFar").setGroup(og).onRenderUpdate(({camera:e})=>e.far),Xv=nm(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const n=[];for(const t of e.cameras)n.push(t.projectionMatrix);t=Vv(n).setGroup(og).label("cameraProjectionMatrices").element(e.isMultiViewCamera?Gv("gl_ViewID_OVR"):Hv).toVar("cameraProjectionMatrix")}else t=cg("mat4").label("cameraProjectionMatrix").setGroup(og).onRenderUpdate(({camera:e})=>e.projectionMatrix);return t}).once()(),qv=nm(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const n=[];for(const t of e.cameras)n.push(t.matrixWorldInverse);t=Vv(n).setGroup(og).label("cameraViewMatrices").element(e.isMultiViewCamera?Gv("gl_ViewID_OVR"):Hv).toVar("cameraViewMatrix")}else t=cg("mat4").label("cameraViewMatrix").setGroup(og).onRenderUpdate(({camera:e})=>e.matrixWorldInverse);return t}).once()(),$v=cg(new Ut).label("cameraPosition").setGroup(og).onRenderUpdate(({camera:e},t)=>t.value.setFromMatrixPosition(e.matrixWorld)),Yv=new Cn;class Kv extends uf{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=Jp,this.uniformNode=new ug(null)}getNodeType(){const e=this.scope;return e===Kv.WORLD_MATRIX?"mat4":e===Kv.POSITION||e===Kv.VIEW_POSITION||e===Kv.DIRECTION||e===Kv.SCALE?"vec3":e===Kv.RADIUS?"float":void 0}update(e){const t=this.object3d,n=this.uniformNode,r=this.scope;if(r===Kv.WORLD_MATRIX)n.value=t.matrixWorld;else if(r===Kv.POSITION)n.value=n.value||new Ut,n.value.setFromMatrixPosition(t.matrixWorld);else if(r===Kv.SCALE)n.value=n.value||new Ut,n.value.setFromMatrixScale(t.matrixWorld);else if(r===Kv.DIRECTION)n.value=n.value||new Ut,t.getWorldDirection(n.value);else if(r===Kv.VIEW_POSITION){const r=e.camera;n.value=n.value||new Ut,n.value.setFromMatrixPosition(t.matrixWorld),n.value.applyMatrix4(r.matrixWorldInverse)}else if(r===Kv.RADIUS){const r=e.object.geometry;null===r.boundingSphere&&r.computeBoundingSphere(),Yv.copy(r.boundingSphere).applyMatrix4(t.matrixWorld),n.value=Yv.radius}}generate(e){const t=this.scope;return t===Kv.WORLD_MATRIX?this.uniformNode.nodeType="mat4":t===Kv.POSITION||t===Kv.VIEW_POSITION||t===Kv.DIRECTION||t===Kv.SCALE?this.uniformNode.nodeType="vec3":t===Kv.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}}Kv.WORLD_MATRIX="worldMatrix",Kv.POSITION="position",Kv.SCALE="scale",Kv.VIEW_POSITION="viewPosition",Kv.DIRECTION="direction",Kv.RADIUS="radius";const Qv=Jf(Kv,Kv.POSITION).setParameterLength(1);class Zv extends Kv{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const Jv=em(Zv,Zv.WORLD_MATRIX),ey=cg(new Bt).onObjectUpdate(({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld)),ty=nm(e=>e.renderer.overrideNodes.modelViewMatrix||ny).once()().toVar("modelViewMatrix"),ny=qv.mul(Jv),ry=nm(e=>(e.context.isHighPrecisionModelViewMatrix=!0,cg("mat4").onObjectUpdate(({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld)))).once()().toVar("highpModelViewMatrix"),iy=nm(e=>{const t=e.context.isHighPrecisionModelViewMatrix;return cg("mat3").onObjectUpdate(({object:e,camera:n})=>(!0!==t&&e.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix)))}).once()().toVar("highpModelNormalViewMatrix"),sy=Ev("position","vec3"),ay=sy.toVarying("positionLocal"),oy=sy.toVarying("positionPrevious"),ly=nm(e=>Jv.mul(ay).xyz.toVarying(e.getSubBuildProperty("v_positionWorld")),"vec3").once(["POSITION"])(),uy=nm(()=>ay.transformDirection(Jv).toVarying("v_positionWorldDirection").normalize().toVar("positionWorldDirection"),"vec3").once(["POSITION"])(),cy=nm(e=>e.context.setupPositionView().toVarying("v_positionView"),"vec3").once(["POSITION"])(),hy=cy.negate().toVarying("v_positionViewDirection").normalize().toVar("positionViewDirection");class dy extends uf{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){if("fragment"!==e.shaderStage)return"true";const{renderer:t,material:n}=e;return t.coordinateSystem===yt&&1===n.side?"false":e.getFrontFacing()}}const py=lm(em(dy)).mul(2).sub(1),fy=nm(([e],{material:t})=>{const n=t.side;return 1===n?e=e.mul(-1):2===n&&(e=e.mul(py)),e}),my=Ev("normal","vec3"),gy=nm(e=>!1===e.geometry.hasAttribute("normal")?(console.warn('THREE.TSL: Vertex attribute "normal" not found on geometry.'),gm(0,1,0)):my,"vec3").once()().toVar("normalLocal"),_y=cy.dFdx().cross(cy.dFdy()).normalize().toVar("normalFlat"),vy=nm(e=>{let t;return t=!0===e.material.flatShading?_y:My(gy).toVarying("v_normalViewGeometry").normalize(),t},"vec3").once()().toVar("normalViewGeometry"),yy=nm(e=>{let t=vy.transformDirection(qv);return!0!==e.material.flatShading&&(t=t.toVarying("v_normalWorldGeometry")),t.normalize().toVar("normalWorldGeometry")},"vec3").once()(),xy=nm(({subBuildFn:e,material:t,context:n})=>{let r;return"NORMAL"===e||"VERTEX"===e?(r=vy,!0!==t.flatShading&&(r=fy(r))):r=n.setupNormal().context({getUV:null}),r},"vec3").once(["NORMAL","VERTEX"])().toVar("normalView"),by=xy.transformDirection(qv).toVar("normalWorld"),Ty=nm(({subBuildFn:e,context:t})=>{let n;return n="NORMAL"===e||"VERTEX"===e?xy:t.setupClearcoatNormal().context({getUV:null}),n},"vec3").once(["NORMAL","VERTEX"])().toVar("clearcoatNormalView"),Sy=nm(([e,t=Jv])=>{const n=wm(t),r=e.div(gm(n[0].dot(n[0]),n[1].dot(n[1]),n[2].dot(n[2])));return n.mul(r).xyz}),My=nm(([e],t)=>{const n=t.renderer.overrideNodes.modelNormalViewMatrix;if(null!==n)return n.transformDirection(e);const r=ey.mul(e);return qv.transformDirection(r)});nm(()=>(console.warn('THREE.TSL: "transformedNormalView" is deprecated. Use "normalView" instead.'),xy)).once(["NORMAL","VERTEX"])(),nm(()=>(console.warn('THREE.TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.'),by)).once(["NORMAL","VERTEX"])(),nm(()=>(console.warn('THREE.TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.'),Ty)).once(["NORMAL","VERTEX"])();const wy=new $n,Ey=new Bn,Ay=cg(0).onReference(({material:e})=>e).onObjectUpdate(({material:e})=>e.refractionRatio),Ry=cg(1).onReference(({material:e})=>e).onObjectUpdate(function({material:e,scene:t}){return e.envMap?e.envMapIntensity:t.environmentIntensity}),Cy=cg(new Bn).onReference(function(e){return e.material}).onObjectUpdate(function({material:e,scene:t}){const n=null!==t.environment&&null===e.envMap?t.environmentRotation:e.envMapRotation;return n?(wy.copy(n),Ey.makeRotationFromEuler(wy)):Ey.identity(),Ey}),Ny=hy.negate().reflect(xy),Py=hy.negate().refract(xy,Ay),Ly=Ny.transformDirection(qv).toVar("reflectVector"),Dy=Py.transformDirection(qv).toVar("reflectVector"),Iy=new Ai;class Uy extends Dv{static get type(){return"CubeTextureNode"}constructor(e,t=null,n=null,r=null){super(e,t,n,r),this.isCubeTextureNode=!0}getInputType(){return"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===G?Ly:e.mapping===H?Dy:(console.error('THREE.CubeTextureNode: Mapping "%s" not supported.',e.mapping),gm(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const n=this.value;return e.renderer.coordinateSystem!==xt&&n.isRenderTargetTexture||(t=gm(t.x.negate(),t.yz)),Cy.mul(t)}generateUV(e,t){return t.build(e,"vec3")}}const Oy=Jf(Uy).setParameterLength(1,4).setName("cubeTexture"),Fy=(e=Iy,t=null,n=null,r=null)=>{let i;return e&&!0===e.isCubeTextureNode?(i=Kf(e.clone()),i.referenceNode=e.getSelf(),null!==t&&(i.uvNode=Kf(t)),null!==n&&(i.levelNode=Kf(n)),null!==r&&(i.biasNode=Kf(r))):i=Oy(e,t,n,r),i};class By extends cf{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),n=this.referenceNode.getNodeType(),r=this.getNodeType();return e.format(t,n,r)}}class ky extends uf{static get type(){return"ReferenceNode"}constructor(e,t,n=null,r=null){super(),this.property=e,this.uniformType=t,this.object=n,this.count=r,this.properties=e.split("."),this.reference=n,this.node=null,this.group=null,this.name=null,this.updateType=Jp}element(e){return Kf(new By(this,Kf(e)))}setGroup(e){return this.group=e,this}label(e){return this.name=e,this}setNodeType(e){let t=null;t=null!==this.count?Bv(null,e,this.count):Array.isArray(this.getValueFromReference())?Vv(null,e):"texture"===e?Uv(null):"cubeTexture"===e?Fy(null):cg(null,e),null!==this.group&&t.setGroup(this.group),null!==this.name&&t.label(this.name),this.node=t.getSelf()}getNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let n=e[t[0]];for(let e=1;e<t.length;e++)n=n[t[e]];return n}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 zy=(e,t,n)=>Kf(new ky(e,t,n)),Vy=(e,t,n,r)=>Kf(new ky(e,t,r,n));class Gy extends ky{static get type(){return"MaterialReferenceNode"}constructor(e,t,n=null){super(e,t,n),this.material=n,this.isMaterialReferenceNode=!0}updateReference(e){return this.reference=null!==this.material?this.material:e.material,this.reference}}const Hy=(e,t,n=null)=>Kf(new Gy(e,t,n)),jy=Av(),Wy=cy.dFdx(),Xy=cy.dFdy(),qy=jy.dFdx(),$y=jy.dFdy(),Yy=xy,Ky=Xy.cross(Yy),Qy=Yy.cross(Wy),Zy=Ky.mul(qy.x).add(Qy.mul($y.x)),Jy=Ky.mul(qy.y).add(Qy.mul($y.y)),ex=Zy.dot(Zy).max(Jy.dot(Jy)),tx=ex.equal(0).select(0,ex.inverseSqrt()),nx=Zy.mul(tx).toVar("tangentViewFrame"),rx=Jy.mul(tx).toVar("bitangentViewFrame"),ix=nm(e=>(!1===e.geometry.hasAttribute("tangent")&&e.geometry.computeTangents(),Ev("tangent","vec4")))(),sx=ix.xyz.toVar("tangentLocal"),ax=nm(({subBuildFn:e,geometry:t,material:n})=>{let r;return r="VERTEX"===e||t.hasAttribute("tangent")?ty.mul(xm(sx,0)).xyz.toVarying("v_tangentView").normalize():nx,!0!==n.flatShading&&(r=fy(r)),r},"vec3").once(["NORMAL","VERTEX"])().toVar("tangentView"),ox=nm(([e,t],{subBuildFn:n,material:r})=>{let i=e.mul(ix.w).xyz;return"NORMAL"===n&&!0!==r.flatShading&&(i=i.toVarying(t)),i}).once(["NORMAL"]),lx=wm(ax,nm(({subBuildFn:e,geometry:t,material:n})=>{let r;return r="VERTEX"===e||t.hasAttribute("tangent")?ox(xy.cross(ax),"v_bitangentView").normalize():rx,!0!==n.flatShading&&(r=fy(r)),r},"vec3").once(["NORMAL","VERTEX"])().toVar("bitangentView"),xy).toVar("TBNViewMatrix"),ux=nm(()=>{let e=jm.cross(hy);return e=e.cross(jm).normalize(),e=O_(e,xy,Gm.mul(Lm.oneMinus()).oneMinus().pow2().pow2()).normalize(),e}).once()();class cx extends df{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=0}setup({material:e}){const{normalMapType:t,scaleNode:n}=this;let r=this.node.mul(2).sub(1);if(null!==n){let t=n;!0===e.flatShading&&(t=fy(t)),r=gm(r.xy.mul(t),r.z)}let i=null;return 1===t?i=My(r):0===t?i=lx.mul(r).normalize():(console.error(`THREE.NodeMaterial: Unsupported normal map type: ${t}`),i=xy),i}}const hx=Jf(cx).setParameterLength(1,2),dx=nm(({textureNode:e,bumpScale:t})=>{const n=t=>e.cache().context({getUV:e=>t(e.uvNode||Av()),forceUVContext:!0}),r=lm(n(e=>e));return dm(lm(n(e=>e.add(e.dFdx()))).sub(r),lm(n(e=>e.add(e.dFdy()))).sub(r)).mul(t)}),px=nm(e=>{const{surf_pos:t,surf_norm:n,dHdxy:r}=e,i=t.dFdx().normalize(),s=n,a=t.dFdy().normalize().cross(s),o=s.cross(i),l=i.dot(a).mul(py),u=l.sign().mul(r.x.mul(a).add(r.y.mul(o)));return l.abs().mul(n).sub(u).normalize()});class fx extends df{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=dx({textureNode:this.textureNode,bumpScale:e});return px({surf_pos:cy,surf_norm:xy,dHdxy:t})}}const mx=Jf(fx).setParameterLength(1,2),gx=new Map;class _x extends uf{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let n=gx.get(e);return void 0===n&&(n=Hy(e,t),gx.set(e,n)),n}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,n=this.scope;let r=null;if(n===_x.COLOR){const e=void 0!==t.color?this.getColor(n):gm();r=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(n===_x.OPACITY){const e=this.getFloat(n);r=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(n===_x.SPECULAR_STRENGTH)r=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture("specular").r:lm(1);else if(n===_x.SPECULAR_INTENSITY){const e=this.getFloat(n);r=t.specularIntensityMap&&!0===t.specularIntensityMap.isTexture?e.mul(this.getTexture(n).a):e}else if(n===_x.SPECULAR_COLOR){const e=this.getColor(n);r=t.specularColorMap&&!0===t.specularColorMap.isTexture?e.mul(this.getTexture(n).rgb):e}else if(n===_x.ROUGHNESS){const e=this.getFloat(n);r=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(n).g):e}else if(n===_x.METALNESS){const e=this.getFloat(n);r=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(n).b):e}else if(n===_x.EMISSIVE){const e=this.getFloat("emissiveIntensity"),i=this.getColor(n).mul(e);r=t.emissiveMap&&!0===t.emissiveMap.isTexture?i.mul(this.getTexture(n)):i}else if(n===_x.NORMAL)t.normalMap?(r=hx(this.getTexture("normal"),this.getCache("normalScale","vec2")),r.normalMapType=t.normalMapType):r=t.bumpMap?mx(this.getTexture("bump").r,this.getFloat("bumpScale")):xy;else if(n===_x.CLEARCOAT){const e=this.getFloat(n);r=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(n).r):e}else if(n===_x.CLEARCOAT_ROUGHNESS){const e=this.getFloat(n);r=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(n).r):e}else if(n===_x.CLEARCOAT_NORMAL)r=t.clearcoatNormalMap?hx(this.getTexture(n),this.getCache(n+"Scale","vec2")):xy;else if(n===_x.SHEEN){const e=this.getColor("sheenColor").mul(this.getFloat("sheen"));r=t.sheenColorMap&&!0===t.sheenColorMap.isTexture?e.mul(this.getTexture("sheenColor").rgb):e}else if(n===_x.SHEEN_ROUGHNESS){const e=this.getFloat(n);r=t.sheenRoughnessMap&&!0===t.sheenRoughnessMap.isTexture?e.mul(this.getTexture(n).a):e,r=r.clamp(.07,1)}else if(n===_x.ANISOTROPY)if(t.anisotropyMap&&!0===t.anisotropyMap.isTexture){const e=this.getTexture(n);r=Mm(eb.x,eb.y,eb.y.negate(),eb.x).mul(e.rg.mul(2).sub(dm(1)).normalize().mul(e.b))}else r=eb;else if(n===_x.IRIDESCENCE_THICKNESS){const e=zy("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const i=zy("0","float",t.iridescenceThicknessRange);r=e.sub(i).mul(this.getTexture(n).g).add(i)}else r=e}else if(n===_x.TRANSMISSION){const e=this.getFloat(n);r=t.transmissionMap?e.mul(this.getTexture(n).r):e}else if(n===_x.THICKNESS){const e=this.getFloat(n);r=t.thicknessMap?e.mul(this.getTexture(n).g):e}else if(n===_x.IOR)r=this.getFloat(n);else if(n===_x.LIGHT_MAP)r=this.getTexture(n).rgb.mul(this.getFloat("lightMapIntensity"));else if(n===_x.AO)r=this.getTexture(n).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1);else if(n===_x.LINE_DASH_OFFSET)r=t.dashOffset?this.getFloat(n):lm(0);else{const t=this.getNodeType(e);r=this.getCache(n,t)}return r}}_x.ALPHA_TEST="alphaTest",_x.COLOR="color",_x.OPACITY="opacity",_x.SHININESS="shininess",_x.SPECULAR="specular",_x.SPECULAR_STRENGTH="specularStrength",_x.SPECULAR_INTENSITY="specularIntensity",_x.SPECULAR_COLOR="specularColor",_x.REFLECTIVITY="reflectivity",_x.ROUGHNESS="roughness",_x.METALNESS="metalness",_x.NORMAL="normal",_x.CLEARCOAT="clearcoat",_x.CLEARCOAT_ROUGHNESS="clearcoatRoughness",_x.CLEARCOAT_NORMAL="clearcoatNormal",_x.EMISSIVE="emissive",_x.ROTATION="rotation",_x.SHEEN="sheen",_x.SHEEN_ROUGHNESS="sheenRoughness",_x.ANISOTROPY="anisotropy",_x.IRIDESCENCE="iridescence",_x.IRIDESCENCE_IOR="iridescenceIOR",_x.IRIDESCENCE_THICKNESS="iridescenceThickness",_x.IOR="ior",_x.TRANSMISSION="transmission",_x.THICKNESS="thickness",_x.ATTENUATION_DISTANCE="attenuationDistance",_x.ATTENUATION_COLOR="attenuationColor",_x.LINE_SCALE="scale",_x.LINE_DASH_SIZE="dashSize",_x.LINE_GAP_SIZE="gapSize",_x.LINE_WIDTH="linewidth",_x.LINE_DASH_OFFSET="dashOffset",_x.POINT_SIZE="size",_x.DISPERSION="dispersion",_x.LIGHT_MAP="light",_x.AO="ao";const vx=em(_x,_x.ALPHA_TEST),yx=em(_x,_x.COLOR),xx=em(_x,_x.SHININESS),bx=em(_x,_x.EMISSIVE),Tx=em(_x,_x.OPACITY),Sx=em(_x,_x.SPECULAR),Mx=em(_x,_x.SPECULAR_INTENSITY),wx=em(_x,_x.SPECULAR_COLOR),Ex=em(_x,_x.SPECULAR_STRENGTH),Ax=em(_x,_x.REFLECTIVITY),Rx=em(_x,_x.ROUGHNESS),Cx=em(_x,_x.METALNESS),Nx=em(_x,_x.NORMAL),Px=em(_x,_x.CLEARCOAT),Lx=em(_x,_x.CLEARCOAT_ROUGHNESS),Dx=em(_x,_x.CLEARCOAT_NORMAL),Ix=em(_x,_x.ROTATION),Ux=em(_x,_x.SHEEN),Ox=em(_x,_x.SHEEN_ROUGHNESS),Fx=em(_x,_x.ANISOTROPY),Bx=em(_x,_x.IRIDESCENCE),kx=em(_x,_x.IRIDESCENCE_IOR),zx=em(_x,_x.IRIDESCENCE_THICKNESS),Vx=em(_x,_x.TRANSMISSION),Gx=em(_x,_x.THICKNESS),Hx=em(_x,_x.IOR),jx=em(_x,_x.ATTENUATION_DISTANCE),Wx=em(_x,_x.ATTENUATION_COLOR),Xx=em(_x,_x.LINE_SCALE),qx=em(_x,_x.LINE_DASH_SIZE),$x=em(_x,_x.LINE_GAP_SIZE);_x.LINE_WIDTH;const Yx=em(_x,_x.LINE_DASH_OFFSET),Kx=em(_x,_x.POINT_SIZE),Qx=em(_x,_x.DISPERSION),Zx=em(_x,_x.LIGHT_MAP),Jx=em(_x,_x.AO),eb=cg(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))}),tb=nm(e=>e.context.setupModelViewProjection(),"vec4").once()().toVarying("v_modelViewProjection");class nb extends uf{static get type(){return"IndexNode"}constructor(e){super("uint"),this.scope=e,this.isIndexNode=!0}generate(e){const t=this.getNodeType(e),n=this.scope;let r,i;if(n===nb.VERTEX)r=e.getVertexIndex();else if(n===nb.INSTANCE)r=e.getInstanceIndex();else if(n===nb.DRAW)r=e.getDrawIndex();else if(n===nb.INVOCATION_LOCAL)r=e.getInvocationLocalIndex();else if(n===nb.INVOCATION_SUBGROUP)r=e.getInvocationSubgroupIndex();else{if(n!==nb.SUBGROUP)throw new Error("THREE.IndexNode: Unknown scope: "+n);r=e.getSubgroupIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)i=r;else{i=Z_(this).build(e,t)}return i}}nb.VERTEX="vertex",nb.INSTANCE="instance",nb.SUBGROUP="subgroup",nb.INVOCATION_LOCAL="invocationLocal",nb.INVOCATION_SUBGROUP="invocationSubgroup",nb.DRAW="draw";const rb=em(nb,nb.VERTEX),ib=em(nb,nb.INSTANCE);nb.SUBGROUP,nb.INVOCATION_SUBGROUP,nb.INVOCATION_LOCAL;const sb=em(nb,nb.DRAW);class ab extends uf{static get type(){return"InstanceNode"}constructor(e,t,n=null){super("void"),this.count=e,this.instanceMatrix=t,this.instanceColor=n,this.instanceMatrixNode=null,this.instanceColorNode=null,this.updateType=Qp,this.buffer=null,this.bufferColor=null}setup(e){const{count:t,instanceMatrix:n,instanceColor:r}=this;let{instanceMatrixNode:i,instanceColorNode:s}=this;if(null===i){if(t<=1e3)i=Bv(n.array,"mat4",Math.max(t,1)).element(ib);else{const e=new ha(n.array,16,1);this.buffer=e;const t=n.usage===_t?pv:dv,r=[t(e,"vec4",16,0),t(e,"vec4",16,4),t(e,"vec4",16,8),t(e,"vec4",16,12)];i=Em(...r)}this.instanceMatrixNode=i}if(r&&null===s){const e=new Bi(r.array,3),t=r.usage===_t?pv:dv;this.bufferColor=e,s=gm(t(e,"vec3",3,0)),this.instanceColorNode=s}const a=i.mul(ay).xyz;if(ay.assign(a),e.hasGeometryAttribute("normal")){const e=Sy(gy,i);gy.assign(e)}null!==this.instanceColorNode&&Cm("vec3","vInstanceColor").assign(this.instanceColorNode)}update(){this.instanceMatrix.usage!==_t&&null!==this.buffer&&this.instanceMatrix.version!==this.buffer.version&&(this.buffer.version=this.instanceMatrix.version),this.instanceColor&&this.instanceColor.usage!==_t&&null!==this.bufferColor&&this.instanceColor.version!==this.bufferColor.version&&(this.bufferColor.version=this.instanceColor.version)}}class ob extends ab{static get type(){return"InstancedMeshNode"}constructor(e){const{count:t,instanceMatrix:n,instanceColor:r}=e;super(t,n,r),this.instancedMesh=e}}const lb=Jf(ob).setParameterLength(1);class ub extends uf{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=ib:this.batchingIdNode=sb);const t=nm(([e])=>{const t=um(Cv(Ov(this.batchMesh._indirectTexture),0).x),n=um(e).mod(t),r=um(e).div(t);return Ov(this.batchMesh._indirectTexture,pm(n,r)).x}).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]}),n=t(um(this.batchingIdNode)),r=this.batchMesh._matricesTexture,i=um(Cv(Ov(r),0).x),s=lm(n).mul(4).toInt().toVar(),a=s.mod(i),o=s.div(i),l=Em(Ov(r,pm(a,o)),Ov(r,pm(a.add(1),o)),Ov(r,pm(a.add(2),o)),Ov(r,pm(a.add(3),o))),u=this.batchMesh._colorsTexture;if(null!==u){const e=nm(([e])=>{const t=um(Cv(Ov(u),0).x),n=e,r=n.mod(t),i=n.div(t);return Ov(u,pm(r,i)).rgb}).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]}),t=e(n);Cm("vec3","vBatchColor").assign(t)}const c=wm(l);ay.assign(l.mul(ay));const h=gy.div(gm(c[0].dot(c[0]),c[1].dot(c[1]),c[2].dot(c[2]))),d=c.mul(h).xyz;gy.assign(d),e.hasGeometryAttribute("tangent")&&sx.mulAssign(c)}}const cb=Jf(ub).setParameterLength(1),hb=new WeakMap;class db extends uf{static get type(){return"SkinningNode"}constructor(e){super("void"),this.skinnedMesh=e,this.updateType=Jp,this.skinIndexNode=Ev("skinIndex","uvec4"),this.skinWeightNode=Ev("skinWeight","vec4"),this.bindMatrixNode=zy("bindMatrix","mat4"),this.bindMatrixInverseNode=zy("bindMatrixInverse","mat4"),this.boneMatricesNode=Vy("skeleton.boneMatrices","mat4",e.skeleton.bones.length),this.positionNode=ay,this.toPositionNode=ay,this.previousBoneMatricesNode=null}getSkinnedPosition(e=this.boneMatricesNode,t=this.positionNode){const{skinIndexNode:n,skinWeightNode:r,bindMatrixNode:i,bindMatrixInverseNode:s}=this,a=e.element(n.x),o=e.element(n.y),l=e.element(n.z),u=e.element(n.w),c=i.mul(t),h=gg(a.mul(r.x).mul(c),o.mul(r.y).mul(c),l.mul(r.z).mul(c),u.mul(r.w).mul(c));return s.mul(h).xyz}getSkinnedNormal(e=this.boneMatricesNode,t=gy){const{skinIndexNode:n,skinWeightNode:r,bindMatrixNode:i,bindMatrixInverseNode:s}=this,a=e.element(n.x),o=e.element(n.y),l=e.element(n.z),u=e.element(n.w);let c=gg(r.x.mul(a),r.y.mul(o),r.z.mul(l),r.w.mul(u));return c=s.mul(c).mul(i),c.transformDirection(t).xyz}getPreviousSkinnedPosition(e){const t=e.object;return null===this.previousBoneMatricesNode&&(t.skeleton.previousBoneMatrices=new Float32Array(t.skeleton.boneMatrices),this.previousBoneMatricesNode=Vy("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,oy)}needsPreviousBoneMatrices(e){const t=e.renderer.getMRT();return t&&t.has("velocity")||!0===$p(e.object).useVelocity}setup(e){this.needsPreviousBoneMatrices(e)&&oy.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(this.toPositionNode&&this.toPositionNode.assign(t),e.hasGeometryAttribute("normal")){const t=this.getSkinnedNormal();gy.assign(t),e.hasGeometryAttribute("tangent")&&sx.assign(t)}return t}generate(e,t){if("void"!==t)return super.generate(e,t)}update(e){const t=e.object&&e.object.skeleton?e.object.skeleton:this.skinnedMesh.skeleton;hb.get(t)!==e.frameId&&(hb.set(t,e.frameId),null!==this.previousBoneMatricesNode&&t.previousBoneMatrices.set(t.boneMatrices),t.update())}}class pb extends uf{static get type(){return"LoopNode"}constructor(e=[]){super(),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 n={};for(let e=0,t=this.params.length-1;e<t;e++){const t=this.params[e],r=!0!==t.isNode&&t.name||this.getVarName(e),i=!0!==t.isNode&&t.type||"int";n[r]=Tv(r,i)}const r=e.addStack();t.returnsNode=this.params[this.params.length-1](n,e),t.stackNode=r;const i=this.params[0];return!0!==i.isNode&&"function"==typeof i.update&&(t.updateNode=nm(this.params[0].update)(n)),e.removeStack(),t}getNodeType(e){const{returnsNode:t}=this.getProperties(e);return t?t.getNodeType(e):"void"}setup(e){this.getProperties(e)}generate(e){const t=this.getProperties(e),n=this.params,r=t.stackNode;for(let r=0,i=n.length-1;r<i;r++){const i=n[r];let s,a=!1,o=null,l=null,u=null,c=null,h=null,d=null;if(i.isNode?"bool"===i.getNodeType(e)?(a=!0,c="bool",l=i.build(e,c)):(c="int",u=this.getVarName(r),o="0",l=i.build(e,c),h="<"):(c=i.type||"int",u=i.name||this.getVarName(r),o=i.start,l=i.end,h=i.condition,d=i.update,"number"==typeof o?o=e.generateConst(c,o):o&&o.isNode&&(o=o.build(e,c)),"number"==typeof l?l=e.generateConst(c,l):l&&l.isNode&&(l=l.build(e,c)),void 0!==o&&void 0===l?(o+=" - 1",l="0",h=">="):void 0!==l&&void 0===o&&(o="0",h="<"),void 0===h&&(h=Number(o)>Number(l)?">=":"<")),a)s=`while ( ${l} )`;else{const n={start:o,end:l},r=n.start,i=n.end;let a;const p=()=>h.includes("<")?"+=":"-=";if(null!=d)switch(typeof d){case"function":a=e.flowStagesNode(t.updateNode,"void").code.replace(/\t|;/g,"");break;case"number":a=u+" "+p()+" "+e.generateConst(c,d);break;case"string":a=u+" "+d;break;default:d.isNode?a=u+" "+p()+" "+d.build(e):(console.error("THREE.TSL: 'Loop( { update: ... } )' is not a function, string or number."),a="break /* invalid update */")}else d="int"===c||"uint"===c?h.includes("<")?"++":"--":p()+" 1.",a=u+" "+d;s=`for ( ${e.getVar(c,u)+" = "+r}; ${u+" "+h+" "+i}; ${a} )`}e.addFlowCode((0===r?"\n":"")+e.tab+s+" {\n\n").addFlowTab()}const i=r.build(e,"void"),s=t.returnsNode?t.returnsNode.build(e):"";e.removeFlowTab().addFlowCode("\n"+e.tab+i);for(let t=0,n=this.params.length-1;t<n;t++)e.addFlowCode((0===t?"":e.tab)+"}\n\n").removeFlowTab();return e.addFlowTab(),s}}const fb=(...e)=>Kf(new pb(Zf(e,"int"))).toStack(),mb=new WeakMap,gb=new an,_b=nm(({bufferMap:e,influence:t,stride:n,width:r,depth:i,offset:s})=>{const a=um(rb).mul(n).add(s),o=a.div(r),l=a.sub(o.mul(r));return Ov(e,pm(l,o)).depth(i).xyz.mul(t)});class vb extends uf{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=cg(1),this.updateType=Jp}setup(e){const{geometry:t}=e,n=void 0!==t.morphAttributes.position,r=t.hasAttribute("normal")&&void 0!==t.morphAttributes.normal,i=t.morphAttributes.position||t.morphAttributes.normal||t.morphAttributes.color,s=void 0!==i?i.length:0,{texture:a,stride:o,size:l}=function(e){const t=void 0!==e.morphAttributes.position,n=void 0!==e.morphAttributes.normal,r=void 0!==e.morphAttributes.color,i=e.morphAttributes.position||e.morphAttributes.normal||e.morphAttributes.color,s=void 0!==i?i.length:0;let a=mb.get(e);if(void 0===a||a.count!==s){void 0!==a&&a.texture.dispose();const o=e.morphAttributes.position||[],l=e.morphAttributes.normal||[],u=e.morphAttributes.color||[];let c=0;!0===t&&(c=1),!0===n&&(c=2),!0===r&&(c=3);let h=e.attributes.position.count*c,d=1;const p=4096;h>p&&(d=Math.ceil(h/p),h=p);const f=new Float32Array(h*d*4*s),m=new un(f,h,d,s);m.type=le,m.needsUpdate=!0;const g=4*c;for(let v=0;v<s;v++){const y=o[v],x=l[v],b=u[v],T=h*d*4*v;for(let S=0;S<y.count;S++){const M=S*g;!0===t&&(gb.fromBufferAttribute(y,S),f[T+M+0]=gb.x,f[T+M+1]=gb.y,f[T+M+2]=gb.z,f[T+M+3]=0),!0===n&&(gb.fromBufferAttribute(x,S),f[T+M+4]=gb.x,f[T+M+5]=gb.y,f[T+M+6]=gb.z,f[T+M+7]=0),!0===r&&(gb.fromBufferAttribute(b,S),f[T+M+8]=gb.x,f[T+M+9]=gb.y,f[T+M+10]=gb.z,f[T+M+11]=4===b.itemSize?gb.w:1)}}function _(){m.dispose(),mb.delete(e),e.removeEventListener("dispose",_)}a={count:s,texture:m,stride:c,size:new Dt(h,d)},mb.set(e,a),e.addEventListener("dispose",_)}return a}(t);!0===n&&ay.mulAssign(this.morphBaseInfluence),!0===r&&gy.mulAssign(this.morphBaseInfluence);const u=um(l.width);fb(s,({i:e})=>{const t=lm(0).toVar();this.mesh.count>1&&null!==this.mesh.morphTexture&&void 0!==this.mesh.morphTexture?t.assign(Ov(this.mesh.morphTexture,pm(um(e).add(1),um(ib))).r):t.assign(zy("morphTargetInfluences","float").element(e).toVar()),sm(t.notEqual(0),()=>{!0===n&&ay.addAssign(_b({bufferMap:a,influence:t,stride:o,width:u,depth:e,offset:um(0)})),!0===r&&gy.addAssign(_b({bufferMap:a,influence:t,stride:o,width:u,depth:e,offset:um(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 yb=Jf(vb).setParameterLength(1);class xb extends uf{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class bb extends xb{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class Tb extends W_{static get type(){return"LightingContextNode"}constructor(e,t=null,n=null,r=null){super(e),this.lightingModel=t,this.backdropNode=n,this.backdropAlphaNode=r,this._value=null}getContext(){const{backdropNode:e,backdropAlphaNode:t}=this,n={directDiffuse:gm().toVar("directDiffuse"),directSpecular:gm().toVar("directSpecular"),indirectDiffuse:gm().toVar("indirectDiffuse"),indirectSpecular:gm().toVar("indirectSpecular")};return{radiance:gm().toVar("radiance"),irradiance:gm().toVar("irradiance"),iblIrradiance:gm().toVar("iblIrradiance"),ambientOcclusion:lm(1).toVar("ambientOcclusion"),reflectedLight:n,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 Sb=Jf(Tb);class Mb extends xb{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}let wb,Eb;class Ab extends uf{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this.isViewportNode=!0}getNodeType(){return this.scope===Ab.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=Kp;return this.scope!==Ab.SIZE&&this.scope!==Ab.VIEWPORT||(e=Zp),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===Ab.VIEWPORT?null!==t?Eb.copy(t.viewport):(e.getViewport(Eb),Eb.multiplyScalar(e.getPixelRatio())):null!==t?(wb.width=t.width,wb.height=t.height):e.getDrawingBufferSize(wb)}setup(){const e=this.scope;let t=null;return t=e===Ab.SIZE?cg(wb||(wb=new Dt)):e===Ab.VIEWPORT?cg(Eb||(Eb=new an)):dm(Nb.div(Cb)),t}generate(e){if(this.scope===Ab.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const n=e.getNodeProperties(Cb).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${n}.y - ${t}.y )`}return t}return super.generate(e)}}Ab.COORDINATE="coordinate",Ab.VIEWPORT="viewport",Ab.SIZE="size",Ab.UV="uv";const Rb=em(Ab,Ab.UV),Cb=em(Ab,Ab.SIZE),Nb=em(Ab,Ab.COORDINATE),Pb=em(Ab,Ab.VIEWPORT);Pb.zw,Pb.xy;const Lb=new Dt;class Db extends Dv{static get type(){return"ViewportTextureNode"}constructor(e=Rb,t=null,n=null){null===n&&((n=new as).minFilter=te),super(n,e,t),this.generateMipmaps=!1,this.isOutputTextureNode=!0,this.updateBeforeType=Qp}updateBefore(e){const t=e.renderer;t.getDrawingBufferSize(Lb);const n=this.value;n.image.width===Lb.width&&n.image.height===Lb.height||(n.image.width=Lb.width,n.image.height=Lb.height,n.needsUpdate=!0);const r=n.generateMipmaps;n.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(n),n.generateMipmaps=r}clone(){const e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}}const Ib=Jf(Db,null,null,{generateMipmaps:!0}).setParameterLength(0,3);let Ub=null;class Ob extends Db{static get type(){return"ViewportDepthTextureNode"}constructor(e=Rb,t=null){null===Ub&&(Ub=new os),super(e,t,Ub)}}const Fb=Jf(Ob).setParameterLength(0,2);class Bb extends uf{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===Bb.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,n=this.valueNode;let r=null;if(t===Bb.DEPTH_BASE)null!==n&&(r=Hb().assign(n));else if(t===Bb.DEPTH)r=e.isPerspectiveCamera?zb(cy.z,jv,Wv):kb(cy.z,jv,Wv);else if(t===Bb.LINEAR_DEPTH)if(null!==n)if(e.isPerspectiveCamera){const e=Vb(n,jv,Wv);r=kb(e,jv,Wv)}else r=n;else r=kb(cy.z,jv,Wv);return r}}Bb.DEPTH_BASE="depthBase",Bb.DEPTH="depth",Bb.LINEAR_DEPTH="linearDepth";const kb=(e,t,n)=>e.add(t).div(t.sub(n)),zb=(e,t,n)=>t.add(e).mul(n).div(n.sub(t).mul(e)),Vb=(e,t,n)=>t.mul(n).div(n.sub(t).mul(e).sub(n)),Gb=(e,t,n)=>{t=t.max(1e-6).toVar();const r=Qg(e.negate().div(t)),i=Qg(n.div(t));return r.div(i)},Hb=Jf(Bb,Bb.DEPTH_BASE),jb=em(Bb,Bb.DEPTH);Fb(),jb.assign=e=>Hb(e);class Wb extends uf{static get type(){return"ClippingNode"}constructor(e=Wb.DEFAULT){super(),this.scope=e}setup(e){super.setup(e);const t=e.clippingContext,{intersectionPlanes:n,unionPlanes:r}=t;return this.hardwareClipping=e.material.hardwareClipping,this.scope===Wb.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(n,r):this.scope===Wb.HARDWARE?this.setupHardwareClipping(r,e):this.setupDefault(n,r)}setupAlphaToCoverage(e,t){return nm(()=>{const n=lm().toVar("distanceToPlane"),r=lm().toVar("distanceToGradient"),i=lm(1).toVar("clipOpacity"),s=t.length;if(!1===this.hardwareClipping&&s>0){const e=Vv(t);fb(s,({i:t})=>{const s=e.element(t);n.assign(cy.dot(s.xyz).negate().add(s.w)),r.assign(n.fwidth().div(2)),i.mulAssign(z_(r.negate(),r,n))})}const a=e.length;if(a>0){const t=Vv(e),s=lm(1).toVar("intersectionClipOpacity");fb(a,({i:e})=>{const i=t.element(e);n.assign(cy.dot(i.xyz).negate().add(i.w)),r.assign(n.fwidth().div(2)),s.mulAssign(z_(r.negate(),r,n).oneMinus())}),i.mulAssign(s.oneMinus())}Nm.a.mulAssign(i),Nm.a.equal(0).discard()})()}setupDefault(e,t){return nm(()=>{const n=t.length;if(!1===this.hardwareClipping&&n>0){const e=Vv(t);fb(n,({i:t})=>{const n=e.element(t);cy.dot(n.xyz).greaterThan(n.w).discard()})}const r=e.length;if(r>0){const t=Vv(e),n=hm(!0).toVar("clipped");fb(r,({i:e})=>{const r=t.element(e);n.assign(cy.dot(r.xyz).greaterThan(r.w).and(n))}),n.discard()}})()}setupHardwareClipping(e,t){const n=e.length;return t.enableHardwareClipping(n),nm(()=>{const r=Vv(e),i=Gv(t.getClipDistance());fb(n,({i:e})=>{const t=r.element(e),n=cy.dot(t.xyz).sub(t.w).negate();i.element(e).assign(n)})})()}}Wb.ALPHA_TO_COVERAGE="alphaToCoverage",Wb.DEFAULT="default",Wb.HARDWARE="hardware";const Xb=nm(([e])=>r_(vg(1e4,i_(vg(17,e.x).add(vg(.1,e.y)))).mul(gg(.1,c_(i_(vg(13,e.y).add(e.x))))))),qb=nm(([e])=>Xb(dm(Xb(e.xy),e.z))),$b=nm(([e])=>{const t=S_(d_(m_(e.xyz)),d_(g_(e.xyz))),n=lm(1).div(lm(.05).mul(t)).toVar("pixScale"),r=dm(Yg(e_(Qg(n))),Yg(t_(Qg(n)))),i=dm(qb(e_(r.x.mul(e.xyz))),qb(e_(r.y.mul(e.xyz)))),s=r_(Qg(n)),a=gg(vg(s.oneMinus(),i.x),vg(s,i.y)),o=T_(s,s.oneMinus()),l=gm(a.mul(a).div(vg(2,o).mul(_g(1,o))),a.sub(vg(.5,o)).div(_g(1,o)),_g(1,_g(1,a).mul(_g(1,a)).div(vg(2,o).mul(_g(1,o))))),u=a.lessThan(o.oneMinus()).select(a.lessThan(o).select(l.x,l.y),l.z);return F_(u,1e-6,1)}).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class Yb extends wv{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 n;return n=!0===e.hasGeometryAttribute(t)?super.generate(e):e.generateConst(this.nodeType,new an(1,1,1,1)),n}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const Kb=nm(([e])=>xm(e.rgb.mul(e.a),e.a),{color:"vec4",return:"vec4"});class Qb extends Dr{static get type(){return"NodeMaterial"}get type(){return this.constructor.type}set type(e){}constructor(){super(),this.isNodeMaterial=!0,this.fog=!0,this.lights=!1,this.hardwareClipping=!1,this.lightsNode=null,this.envNode=null,this.aoNode=null,this.colorNode=null,this.normalNode=null,this.opacityNode=null,this.backdropNode=null,this.backdropAlphaNode=null,this.alphaTestNode=null,this.maskNode=null,this.positionNode=null,this.geometryNode=null,this.depthNode=null,this.receivedShadowPositionNode=null,this.castShadowPositionNode=null,this.receivedShadowNode=null,this.castShadowNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null,Object.defineProperty(this,"shadowPositionNode",{get:()=>this.receivedShadowPositionNode,set:e=>{console.warn('THREE.NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".'),this.receivedShadowPositionNode=e}})}customProgramCacheKey(){return this.type+Gp(this)}build(e){this.setup(e)}setupObserver(e){return new Bp(e)}setup(e){e.context.setupNormal=()=>K_(this.setupNormal(e),"NORMAL","vec3"),e.context.setupPositionView=()=>this.setupPositionView(e),e.context.setupModelViewProjection=()=>this.setupModelViewProjection(e);const t=e.renderer,n=t.getRenderTarget();e.addStack();const r=K_(this.setupVertex(e),"VERTEX"),i=this.vertexNode||r;let s;e.stack.outputNode=i,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!==n?!0===n.depthBuffer&&this.setupDepth(e):!0===t.depth&&this.setupDepth(e)),null===this.fragmentNode){this.setupDiffuseColor(e),this.setupVariants(e);const r=this.setupLighting(e);null!==a&&e.stack.add(a);const i=xm(r,Nm.a).max(0);s=this.setupOutput(e,i),$m.assign(s);const o=null!==this.outputNode;if(o&&(s=this.outputNode),null!==n){const e=t.getMRT(),n=this.mrtNode;null!==e?(o&&$m.assign(s),s=e,null!==n&&(s=e.merge(n))):null!==n&&(s=n)}}else{let t=this.fragmentNode;!0!==t.isOutputStructNode&&(t=xm(t)),s=this.setupOutput(e,t)}e.stack.outputNode=s,e.addFlow("fragment",e.removeStack()),e.observer=this.setupObserver(e)}setupClipping(e){if(null===e.clippingContext)return null;const{unionPlanes:t,intersectionPlanes:n}=e.clippingContext;let r=null;if(t.length>0||n.length>0){const t=e.renderer.samples;this.alphaToCoverage&&t>1?r=Kf(new Wb(Wb.ALPHA_TO_COVERAGE)):e.stack.add(Kf(new Wb))}return r}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.add(Kf(new Wb(Wb.HARDWARE))),this.hardwareClipping=!0)}setupDepth(e){const{renderer:t,camera:n}=e;let r=this.depthNode;if(null===r){const e=t.getMRT();e&&e.has("depth")?r=e.get("depth"):!0===t.logarithmicDepthBuffer&&(r=n.isPerspectiveCamera?Gb(cy.z,jv,Wv):kb(cy.z,jv,Wv))}null!==r&&jb.assign(r).toStack()}setupPositionView(){return ty.mul(ay).xyz}setupModelViewProjection(){return Xv.mul(cy)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.vertex=e.removeStack(),tb}setupPosition(e){const{object:t,geometry:n}=e;var r;if((n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color)&&yb(t).toStack(),!0===t.isSkinnedMesh&&(r=t,Kf(new db(r))).toStack(),this.displacementMap){const e=Hy("displacementMap","texture"),t=Hy("displacementScale","float"),n=Hy("displacementBias","float");ay.addAssign(gy.normalize().mul(e.x.mul(t).add(n)))}return t.isBatchedMesh&&cb(t).toStack(),t.isInstancedMesh&&t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&lb(t).toStack(),null!==this.positionNode&&ay.assign(K_(this.positionNode,"POSITION","vec3")),ay}setupDiffuseColor({object:e,geometry:t}){null!==this.maskNode&&hm(this.maskNode).not().discard();let n=this.colorNode?xm(this.colorNode):yx;if(!0===this.vertexColors&&t.hasAttribute("color")&&(n=n.mul(((e=0)=>Kf(new Yb(e)))())),e.instanceColor){n=Cm("vec3","vInstanceColor").mul(n)}if(e.isBatchedMesh&&e._colorsTexture){n=Cm("vec3","vBatchColor").mul(n)}Nm.assign(n);const r=this.opacityNode?lm(this.opacityNode):Tx;Nm.a.assign(Nm.a.mul(r));let i=null;(null!==this.alphaTestNode||this.alphaTest>0)&&(i=null!==this.alphaTestNode?lm(this.alphaTestNode):vx,Nm.a.lessThanEqual(i).discard()),!0===this.alphaHash&&Nm.a.lessThan($b(ay)).discard();!1===this.transparent&&1===this.blending&&!1===this.alphaToCoverage?Nm.a.assign(1):null===i&&Nm.a.lessThanEqual(0).discard()}setupVariants(){}setupOutgoingLight(){return!0===this.lights?gm(0):Nm.rgb}setupNormal(){return this.normalNode?gm(this.normalNode):Nx}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?Hy("envMap","cubeTexture"):Hy("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new Mb(Zx)),t}setupLights(e){const t=[],n=this.setupEnvironment(e);n&&n.isLightingNode&&t.push(n);const r=this.setupLightMap(e);if(r&&r.isLightingNode&&t.push(r),null!==this.aoNode||e.material.aoMap){const e=null!==this.aoNode?this.aoNode:Jx;t.push(new bb(e))}let i=this.lightsNode||e.lightsNode;return t.length>0&&(i=e.renderer.lighting.createNode([...i.getLights(),...t])),i}setupLightingModel(){}setupLighting(e){const{material:t}=e,{backdropNode:n,backdropAlphaNode:r,emissiveNode:i}=this,s=!0===this.lights||null!==this.lightsNode?this.setupLights(e):null;let a=this.setupOutgoingLight(e);if(s&&s.getScope().hasLights){const t=this.setupLightingModel(e)||null;a=Sb(s,t,n,r)}else null!==n&&(a=gm(null!==r?O_(a,n,r):n));return(i&&!0===i.isNode||t.emissive&&!0===t.emissive.isColor)&&(Pm.assign(gm(i||bx)),a=a.add(Pm)),a}setupFog(e,t){const n=e.fogNode;return n&&($m.assign(t),t=xm(n)),t}setupPremultipliedAlpha(e,t){return Kb(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 n=e[t];void 0===this[t]&&(this[t]=n,n&&n.clone&&(this[t]=n.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 n=Dr.prototype.toJSON.call(this,e),r=Hp(this);n.inputNodes={};for(const{property:t,childNode:i}of r)n.inputNodes[t]=i.toJSON(e).uuid;function i(e){const t=[];for(const n in e){const r=e[n];delete r.metadata,t.push(r)}return t}if(t){const t=i(e.textures),r=i(e.images),s=i(e.nodes);t.length>0&&(n.textures=t),r.length>0&&(n.images=r),s.length>0&&(n.nodes=s)}return n}copy(e){return this.lightsNode=e.lightsNode,this.envNode=e.envNode,this.colorNode=e.colorNode,this.normalNode=e.normalNode,this.opacityNode=e.opacityNode,this.backdropNode=e.backdropNode,this.backdropAlphaNode=e.backdropAlphaNode,this.alphaTestNode=e.alphaTestNode,this.maskNode=e.maskNode,this.positionNode=e.positionNode,this.geometryNode=e.geometryNode,this.depthNode=e.depthNode,this.receivedShadowPositionNode=e.receivedShadowPositionNode,this.castShadowPositionNode=e.castShadowPositionNode,this.receivedShadowNode=e.receivedShadowNode,this.castShadowNode=e.castShadowNode,this.outputNode=e.outputNode,this.mrtNode=e.mrtNode,this.fragmentNode=e.fragmentNode,this.vertexNode=e.vertexNode,super.copy(e)}}const Zb=new Ki;class Jb extends Qb{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(Zb),this.setValues(e)}}const eT=new Os;class tT extends Qb{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(eT),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?lm(this.offsetNode):Yx,t=this.dashScaleNode?lm(this.dashScaleNode):Xx,n=this.dashSizeNode?lm(this.dashSizeNode):qx,r=this.gapSizeNode?lm(this.gapSizeNode):$x;Ym.assign(n),Km.assign(r);const i=Z_(Ev("lineDistance").mul(t));(e?i.add(e):i).mod(Ym.add(Km)).greaterThan(Ym).discard()}}const nT=new Ps;class rT extends Qb{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(nT),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?lm(this.opacityNode):Tx;Nm.assign(rv(xm(Kf(xy).mul(.5).add(.5),e),rt))}}const iT=nm(([e=uy])=>{const t=e.z.atan(e.x).mul(1/(2*Math.PI)).add(.5),n=e.y.clamp(-1,1).asin().mul(1/Math.PI).add(.5);return dm(t,n)});class sT extends Ri{constructor(e=1,t={}){super(e,t),this.isCubeRenderTarget=!0}fromEquirectangularTexture(e,t){const n=t.minFilter,r=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 i=new fi(5,5,5),s=iT(uy),a=new Qb;a.colorNode=Uv(t,s,0),a.side=1,a.blending=0;const o=new di(i,a),l=new Li;l.add(o),t.minFilter===te&&(t.minFilter=J);const u=new Ei(1,10,this),c=e.getMRT();return e.setMRT(null),u.update(e,l),e.setMRT(c),t.minFilter=n,t.currentGenerateMipmaps=r,o.geometry.dispose(),o.material.dispose(),this}}const aT=new WeakMap;class oT extends df{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=Fy(null);const t=new Ai;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=Zp}updateBefore(e){const{renderer:t,material:n}=e,r=this.envNode;if(r.isTextureNode||r.isMaterialReferenceNode){const e=r.isTextureNode?r.value:n[r.property];if(e&&e.isTexture){const n=e.mapping;if(n===j||n===W){if(aT.has(e)){const t=aT.get(e);uT(t,e.mapping),this._cubeTexture=t}else{const n=e.image;if(function(e){return null!=e&&e.height>0}(n)){const r=new sT(n.height);r.fromEquirectangularTexture(t,e),uT(r.texture,e.mapping),this._cubeTexture=r.texture,aT.set(e,r.texture),e.addEventListener("dispose",lT)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function lT(e){const t=e.target;t.removeEventListener("dispose",lT);const n=aT.get(t);void 0!==n&&(aT.delete(t),n.dispose())}function uT(e,t){t===j?e.mapping=G:t===W&&(e.mapping=H)}const cT=Jf(oT).setParameterLength(1);class hT extends xb{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=cT(this.envNode)}}class dT extends xb{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=lm(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class pT{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class fT extends pT{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,n=e.reflectedLight,r=e.irradianceLightMap;n.indirectDiffuse.assign(xm(0)),r?n.indirectDiffuse.addAssign(r):n.indirectDiffuse.addAssign(xm(1,1,1,0)),n.indirectDiffuse.mulAssign(t),n.indirectDiffuse.mulAssign(Nm.rgb)}finish(e){const{material:t,context:n}=e,r=n.outgoingLight,i=e.context.environment;if(i)switch(t.combine){case 0:r.rgb.assign(O_(r.rgb,r.rgb.mul(i.rgb),Ex.mul(Ax)));break;case 1:r.rgb.assign(O_(r.rgb,i.rgb,Ex.mul(Ax)));break;case 2:r.rgb.addAssign(i.rgb.mul(Ex.mul(Ax)));break;default:console.warn("THREE.BasicLightingModel: Unsupported .combine value:",t.combine)}}}const mT=new Ir;class gT extends Qb{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(mT),this.setValues(e)}setupNormal(){return fy(vy)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new hT(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new dT(Zx)),t}setupOutgoingLight(){return Nm.rgb}setupLightingModel(){return new fT}}const _T=nm(({f0:e,f90:t,dotVH:n})=>{const r=n.mul(-5.55473).sub(6.98316).mul(n).exp2();return e.mul(r.oneMinus()).add(t.mul(r))}),vT=nm(e=>e.diffuseColor.mul(1/Math.PI)),yT=nm(({dotNH:e})=>qm.mul(lm(.5)).add(1).mul(lm(1/Math.PI)).mul(e.pow(qm))),xT=nm(({lightDirection:e})=>{const t=e.add(hy).normalize(),n=xy.dot(t).clamp(),r=hy.dot(t).clamp(),i=_T({f0:Wm,f90:1,dotVH:r}),s=lm(.25),a=yT({dotNH:n});return i.mul(s).mul(a)});class bT extends fT{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:n}){const r=xy.dot(e).clamp().mul(t);n.directDiffuse.addAssign(r.mul(vT({diffuseColor:Nm.rgb}))),!0===this.specular&&n.directSpecular.addAssign(r.mul(xT({lightDirection:e})).mul(Ex))}indirect(e){const{ambientOcclusion:t,irradiance:n,reflectedLight:r}=e.context;r.indirectDiffuse.addAssign(n.mul(vT({diffuseColor:Nm}))),r.indirectDiffuse.mulAssign(t)}}const TT=new Ls;class ST extends Qb{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(TT),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new hT(t):null}setupLightingModel(){return new bT(!1)}}const MT=new Cs;class wT extends Qb{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(MT),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new hT(t):null}setupLightingModel(){return new bT}setupVariants(){const e=(this.shininessNode?lm(this.shininessNode):xx).max(1e-4);qm.assign(e);const t=this.specularNode||Sx;Wm.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}const ET=nm(e=>{if(!1===e.geometry.hasAttribute("normal"))return lm(0);const t=vy.dFdx().abs().max(vy.dFdy().abs());return t.x.max(t.y).max(t.z)}),AT=nm(e=>{const{roughness:t}=e,n=ET();let r=t.max(.0525);return r=r.add(n),r=r.min(1),r}),RT=nm(({alpha:e,dotNL:t,dotNV:n})=>{const r=e.pow2(),i=t.mul(r.add(r.oneMinus().mul(n.pow2())).sqrt()),s=n.mul(r.add(r.oneMinus().mul(t.pow2())).sqrt());return yg(.5,i.add(s).max(Gg))}).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),CT=nm(({alphaT:e,alphaB:t,dotTV:n,dotBV:r,dotTL:i,dotBL:s,dotNV:a,dotNL:o})=>{const l=o.mul(gm(e.mul(n),t.mul(r),a).length()),u=a.mul(gm(e.mul(i),t.mul(s),o).length());return yg(.5,l.add(u)).saturate()}).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"}]}),NT=nm(({alpha:e,dotNH:t})=>{const n=e.pow2(),r=t.pow2().mul(n.oneMinus()).oneMinus();return n.div(r.pow2()).mul(1/Math.PI)}).setLayout({name:"D_GGX",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNH",type:"float"}]}),PT=lm(1/Math.PI),LT=nm(({alphaT:e,alphaB:t,dotNH:n,dotTH:r,dotBH:i})=>{const s=e.mul(t),a=gm(t.mul(r),e.mul(i),s.mul(n)),o=a.dot(a),l=s.div(o);return PT.mul(s.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"}]}),DT=nm(({lightDirection:e,f0:t,f90:n,roughness:r,f:i,normalView:s=xy,USE_IRIDESCENCE:a,USE_ANISOTROPY:o})=>{const l=r.pow2(),u=e.add(hy).normalize(),c=s.dot(e).clamp(),h=s.dot(hy).clamp(),d=s.dot(u).clamp(),p=hy.dot(u).clamp();let f,m,g=_T({f0:t,f90:n,dotVH:p});if($f(a)&&(g=Bm.mix(g,i)),$f(o)){const t=Hm.dot(e),n=Hm.dot(hy),r=Hm.dot(u),i=jm.dot(e),s=jm.dot(hy),a=jm.dot(u);f=CT({alphaT:Vm,alphaB:l,dotTV:n,dotBV:s,dotTL:t,dotBL:i,dotNV:h,dotNL:c}),m=LT({alphaT:Vm,alphaB:l,dotNH:d,dotTH:r,dotBH:a})}else f=RT({alpha:l,dotNL:c,dotNV:h}),m=NT({alpha:l,dotNH:d});return g.mul(f).mul(m)}),IT=nm(({roughness:e,dotNV:t})=>{const n=xm(-1,-.0275,-.572,.022),r=xm(1,.0425,1.04,-.04),i=e.mul(n).add(r),s=i.x.mul(i.x).min(t.mul(-9.28).exp2()).mul(i.x).add(i.y);return dm(-1.04,1.04).mul(s).add(i.zw)}).setLayout({name:"DFGApprox",type:"vec2",inputs:[{name:"roughness",type:"float"},{name:"dotNV",type:"vec3"}]}),UT=nm(e=>{const{dotNV:t,specularColor:n,specularF90:r,roughness:i}=e,s=IT({dotNV:t,roughness:i});return n.mul(s.x).add(r.mul(s.y))}),OT=nm(({f:e,f90:t,dotVH:n})=>{const r=n.oneMinus().saturate(),i=r.mul(r),s=r.mul(i,i).clamp(0,.9999);return e.sub(gm(t).mul(s)).div(s.oneMinus())}).setLayout({name:"Schlick_to_F0",type:"vec3",inputs:[{name:"f",type:"vec3"},{name:"f90",type:"float"},{name:"dotVH",type:"float"}]}),FT=nm(({roughness:e,dotNH:t})=>{const n=e.pow2(),r=lm(1).div(n),i=t.pow2().oneMinus().max(.0078125);return lm(2).add(r).mul(i.pow(r.mul(.5))).div(2*Math.PI)}).setLayout({name:"D_Charlie",type:"float",inputs:[{name:"roughness",type:"float"},{name:"dotNH",type:"float"}]}),BT=nm(({dotNV:e,dotNL:t})=>lm(1).div(lm(4).mul(t.add(e).sub(t.mul(e))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),kT=nm(({lightDirection:e})=>{const t=e.add(hy).normalize(),n=xy.dot(e).clamp(),r=xy.dot(hy).clamp(),i=xy.dot(t).clamp(),s=FT({roughness:Fm,dotNH:i}),a=BT({dotNV:r,dotNL:n});return Om.mul(s).mul(a)}),zT=nm(({N:e,V:t,roughness:n})=>{const r=e.dot(t).saturate(),i=dm(n,r.oneMinus().sqrt());return i.assign(i.mul(.984375).add(.0078125)),i}).setLayout({name:"LTC_Uv",type:"vec2",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"roughness",type:"float"}]}),VT=nm(({f:e})=>{const t=e.length();return S_(t.mul(t).add(e.z).div(t.add(1)),0)}).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),GT=nm(({v1:e,v2:t})=>{const n=e.dot(t),r=n.abs().toVar(),i=r.mul(.0145206).add(.4965155).mul(r).add(.8543985).toVar(),s=r.add(4.1616724).mul(r).add(3.417594).toVar(),a=i.div(s),o=n.greaterThan(0).select(a,S_(n.mul(n).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"}]}),HT=nm(({N:e,V:t,P:n,mInv:r,p0:i,p1:s,p2:a,p3:o})=>{const l=s.sub(i).toVar(),u=o.sub(i).toVar(),c=l.cross(u),h=gm().toVar();return sm(c.dot(n.sub(i)).greaterThanEqual(0),()=>{const l=t.sub(e.mul(t.dot(e))).normalize(),u=e.cross(l).negate(),c=r.mul(wm(l,u,e).transpose()).toVar(),d=c.mul(i.sub(n)).normalize().toVar(),p=c.mul(s.sub(n)).normalize().toVar(),f=c.mul(a.sub(n)).normalize().toVar(),m=c.mul(o.sub(n)).normalize().toVar(),g=gm(0).toVar();g.addAssign(GT({v1:d,v2:p})),g.addAssign(GT({v1:p,v2:f})),g.addAssign(GT({v1:f,v2:m})),g.addAssign(GT({v1:m,v2:d})),h.assign(gm(VT({f:g})))}),h}).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"}]}),jT=1/6,WT=e=>vg(jT,vg(e,vg(e,e.negate().add(3)).sub(3)).add(1)),XT=e=>vg(jT,vg(e,vg(e,vg(3,e).sub(6))).add(4)),qT=e=>vg(jT,vg(e,vg(e,vg(-3,e).add(3)).add(3)).add(1)),$T=e=>vg(jT,N_(e,3)),YT=e=>WT(e).add(XT(e)),KT=e=>qT(e).add($T(e)),QT=e=>gg(-1,XT(e).div(WT(e).add(XT(e)))),ZT=e=>gg(1,$T(e).div(qT(e).add($T(e)))),JT=(e,t,n)=>{const r=e.uvNode,i=vg(r,t.zw).add(.5),s=e_(i),a=r_(i),o=YT(a.x),l=KT(a.x),u=QT(a.x),c=ZT(a.x),h=QT(a.y),d=ZT(a.y),p=dm(s.x.add(u),s.y.add(h)).sub(.5).mul(t.xy),f=dm(s.x.add(c),s.y.add(h)).sub(.5).mul(t.xy),m=dm(s.x.add(u),s.y.add(d)).sub(.5).mul(t.xy),g=dm(s.x.add(c),s.y.add(d)).sub(.5).mul(t.xy),_=YT(a.y).mul(gg(o.mul(e.sample(p).level(n)),l.mul(e.sample(f).level(n)))),v=KT(a.y).mul(gg(o.mul(e.sample(m).level(n)),l.mul(e.sample(g).level(n))));return _.add(v)},eS=nm(([e,t])=>{const n=dm(e.size(um(t))),r=dm(e.size(um(t.add(1)))),i=yg(1,n),s=yg(1,r),a=JT(e,xm(i,n),e_(t)),o=JT(e,xm(s,r),t_(t));return r_(t).mix(a,o)}),tS=nm(([e,t,n,r,i])=>{const s=gm(k_(t.negate(),n_(e),yg(1,r))),a=gm(d_(i[0].xyz),d_(i[1].xyz),d_(i[2].xyz));return n_(s).mul(n.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"}]}),nS=nm(([e,t])=>e.mul(F_(t.mul(2).sub(2),0,1))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),rS=Ib(),iS=Ib(),sS=nm(([e,t,n],{material:r})=>{const i=(1===r.side?rS:iS).sample(e),s=Qg(Cb.x).mul(nS(t,n));return eS(i,s)}),aS=nm(([e,t,n])=>(sm(n.notEqual(0),()=>{const r=Kg(t).negate().div(n);return $g(r.negate().mul(e))}),gm(1))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),oS=nm(([e,t,n,r,i,s,a,o,l,u,c,h,d,p,f])=>{let m,g;if(f){m=xm().toVar(),g=gm().toVar();const i=c.sub(1).mul(f.mul(.025)),s=gm(c.sub(i),c,c.add(i));fb({start:0,end:3},({i:i})=>{const c=s.element(i),f=tS(e,t,h,c,o),_=a.add(f),v=u.mul(l.mul(xm(_,1))),y=dm(v.xy.div(v.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(dm(y.x,y.y.oneMinus()));const x=sS(y,n,c);m.element(i).assign(x.element(i)),m.a.addAssign(x.a),g.element(i).assign(r.element(i).mul(aS(d_(f),d,p).element(i)))}),m.a.divAssign(3)}else{const i=tS(e,t,h,c,o),s=a.add(i),f=u.mul(l.mul(xm(s,1))),_=dm(f.xy.div(f.w)).toVar();_.addAssign(1),_.divAssign(2),_.assign(dm(_.x,_.y.oneMinus())),m=sS(_,n,c),g=r.mul(aS(d_(i),d,p))}const _=g.rgb.mul(m.rgb),v=e.dot(t).clamp(),y=gm(UT({dotNV:v,specularColor:i,specularF90:s,roughness:n})),x=g.r.add(g.g,g.b).div(3);return xm(y.oneMinus().mul(_),m.a.oneMinus().mul(x).oneMinus())}),lS=wm(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),uS=(e,t)=>e.sub(t).div(e.add(t)).pow2(),cS=nm(({outsideIOR:e,eta2:t,cosTheta1:n,thinFilmThickness:r,baseF0:i})=>{const s=O_(e,t,z_(0,.03,r)),a=e.div(s).pow2().mul(n.pow2().oneMinus()).oneMinus();sm(a.lessThan(0),()=>gm(1));const o=a.sqrt(),l=uS(s,e),u=_T({f0:l,f90:1,dotVH:n}),c=u.oneMinus(),h=s.lessThan(e).select(Math.PI,0),d=lm(Math.PI).sub(h),p=(e=>{const t=e.sqrt();return gm(1).add(t).div(gm(1).sub(t))})(i.clamp(0,.9999)),f=uS(p,s.toVec3()),m=_T({f0:f,f90:1,dotVH:o}),g=gm(p.x.lessThan(s).select(Math.PI,0),p.y.lessThan(s).select(Math.PI,0),p.z.lessThan(s).select(Math.PI,0)),_=s.mul(r,o,2),v=gm(d).add(g),y=u.mul(m).clamp(1e-5,.9999),x=y.sqrt(),b=c.pow2().mul(m).div(gm(1).sub(y)),T=u.add(b).toVar(),S=b.sub(c).toVar();return fb({start:1,end:2,condition:"<=",name:"m"},({m:e})=>{S.mulAssign(x);const t=((e,t)=>{const n=e.mul(2*Math.PI*1e-9),r=gm(54856e-17,44201e-17,52481e-17),i=gm(1681e3,1795300,2208400),s=gm(43278e5,93046e5,66121e5),a=lm(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(n.mul(2239900).add(t.x).cos()).mul(n.pow2().mul(-45282e5).exp());let o=r.mul(s.mul(2*Math.PI).sqrt()).mul(i.mul(n).add(t).cos()).mul(n.pow2().negate().mul(s).exp());return o=gm(o.x.add(a),o.y,o.z).div(1.0685e-7),lS.mul(o)})(lm(e).mul(_),lm(e).mul(v)).mul(2);T.addAssign(S.mul(t))}),T.max(gm(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"}]}),hS=nm(({normal:e,viewDir:t,roughness:n})=>{const r=e.dot(t).saturate(),i=n.pow2(),s=j_(n.lessThan(.25),lm(-339.2).mul(i).add(lm(161.4).mul(n)).sub(25.9),lm(-8.48).mul(i).add(lm(14.3).mul(n)).sub(9.95)),a=j_(n.lessThan(.25),lm(44).mul(i).sub(lm(23.7).mul(n)).add(3.26),lm(1.97).mul(i).sub(lm(3.27).mul(n)).add(.72));return j_(n.lessThan(.25),0,lm(.1).mul(n).sub(.025)).add(s.mul(r).add(a).exp()).mul(1/Math.PI).saturate()}),dS=gm(.04),pS=lm(1);class fS extends pT{constructor(e=!1,t=!1,n=!1,r=!1,i=!1,s=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=n,this.anisotropy=r,this.transmission=i,this.dispersion=s,this.clearcoatRadiance=null,this.clearcoatSpecularDirect=null,this.clearcoatSpecularIndirect=null,this.sheenSpecularDirect=null,this.sheenSpecularIndirect=null,this.iridescenceFresnel=null,this.iridescenceF0=null}start(e){if(!0===this.clearcoat&&(this.clearcoatRadiance=gm().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=gm().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=gm().toVar("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=gm().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=gm().toVar("sheenSpecularIndirect")),!0===this.iridescence){const e=xy.dot(hy).clamp();this.iridescenceFresnel=cS({outsideIOR:lm(1),eta2:km,cosTheta1:e,thinFilmThickness:zm,baseF0:Wm}),this.iridescenceF0=OT({f:this.iridescenceFresnel,f90:1,dotVH:e})}if(!0===this.transmission){const t=ly,n=$v.sub(ly).normalize(),r=by,i=e.context;i.backdrop=oS(r,n,Lm,Nm,Wm,Xm,t,Jv,qv,Xv,Qm,Jm,tg,eg,this.dispersion?ng:null),i.backdropAlpha=Zm,Nm.a.mulAssign(O_(1,i.backdrop.a,Zm))}super.start(e)}computeMultiscattering(e,t,n){const r=xy.dot(hy).clamp(),i=IT({roughness:Lm,dotNV:r}),s=(this.iridescenceF0?Bm.mix(Wm,this.iridescenceF0):Wm).mul(i.x).add(n.mul(i.y)),a=i.x.add(i.y).oneMinus(),o=Wm.add(Wm.oneMinus().mul(.047619)),l=s.mul(o).div(a.mul(o).oneMinus());e.addAssign(s),t.addAssign(l.mul(a))}direct({lightDirection:e,lightColor:t,reflectedLight:n}){const r=xy.dot(e).clamp().mul(t);if(!0===this.sheen&&this.sheenSpecularDirect.addAssign(r.mul(kT({lightDirection:e}))),!0===this.clearcoat){const n=Ty.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(n.mul(DT({lightDirection:e,f0:dS,f90:pS,roughness:Um,normalView:Ty})))}n.directDiffuse.addAssign(r.mul(vT({diffuseColor:Nm.rgb}))),n.directSpecular.addAssign(r.mul(DT({lightDirection:e,f0:Wm,f90:1,roughness:Lm,iridescence:this.iridescence,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy})))}directRectArea({lightColor:e,lightPosition:t,halfWidth:n,halfHeight:r,reflectedLight:i,ltc_1:s,ltc_2:a}){const o=t.add(n).sub(r),l=t.sub(n).sub(r),u=t.sub(n).add(r),c=t.add(n).add(r),h=xy,d=hy,p=cy.toVar(),f=zT({N:h,V:d,roughness:Lm}),m=s.sample(f).toVar(),g=a.sample(f).toVar(),_=wm(gm(m.x,0,m.y),gm(0,1,0),gm(m.z,0,m.w)).toVar(),v=Wm.mul(g.x).add(Wm.oneMinus().mul(g.y)).toVar();i.directSpecular.addAssign(e.mul(v).mul(HT({N:h,V:d,P:p,mInv:_,p0:o,p1:l,p2:u,p3:c}))),i.directDiffuse.addAssign(e.mul(Nm).mul(HT({N:h,V:d,P:p,mInv:wm(1,0,0,0,1,0,0,0,1),p0:o,p1:l,p2:u,p3:c})))}indirect(e){this.indirectDiffuse(e),this.indirectSpecular(e),this.ambientOcclusion(e)}indirectDiffuse(e){const{irradiance:t,reflectedLight:n}=e.context;n.indirectDiffuse.addAssign(t.mul(vT({diffuseColor:Nm})))}indirectSpecular(e){const{radiance:t,iblIrradiance:n,reflectedLight:r}=e.context;if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(n.mul(Om,hS({normal:xy,viewDir:hy,roughness:Fm}))),!0===this.clearcoat){const e=Ty.dot(hy).clamp(),t=UT({dotNV:e,specularColor:dS,specularF90:pS,roughness:Um});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const i=gm().toVar("singleScattering"),s=gm().toVar("multiScattering"),a=n.mul(1/Math.PI);this.computeMultiscattering(i,s,Xm);const o=i.add(s),l=Nm.mul(o.r.max(o.g).max(o.b).oneMinus());r.indirectSpecular.addAssign(t.mul(i)),r.indirectSpecular.addAssign(s.mul(a)),r.indirectDiffuse.addAssign(l.mul(a))}ambientOcclusion(e){const{ambientOcclusion:t,reflectedLight:n}=e.context,r=xy.dot(hy).clamp().add(t),i=Lm.mul(-16).oneMinus().negate().exp2(),s=t.sub(r.pow(i).oneMinus()).clamp();!0===this.clearcoat&&this.clearcoatSpecularIndirect.mulAssign(t),!0===this.sheen&&this.sheenSpecularIndirect.mulAssign(t),n.indirectDiffuse.mulAssign(t),n.indirectSpecular.mulAssign(s)}finish({context:e}){const{outgoingLight:t}=e;if(!0===this.clearcoat){const e=Ty.dot(hy).clamp(),n=_T({dotVH:e,f0:dS,f90:pS}),r=t.mul(Im.mul(n).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(Im));t.assign(r)}if(!0===this.sheen){const e=Om.r.max(Om.g).max(Om.b).mul(.157).oneMinus(),n=t.mul(e).add(this.sheenSpecularDirect,this.sheenSpecularIndirect);t.assign(n)}}}const mS=lm(1),gS=lm(-2),_S=lm(.8),vS=lm(-1),yS=lm(.4),xS=lm(2),bS=lm(.305),TS=lm(3),SS=lm(.21),MS=lm(4),wS=lm(4),ES=lm(16),AS=nm(([e])=>{const t=gm(c_(e)).toVar(),n=lm(-1).toVar();return sm(t.x.greaterThan(t.z),()=>{sm(t.x.greaterThan(t.y),()=>{n.assign(j_(e.x.greaterThan(0),0,3))}).Else(()=>{n.assign(j_(e.y.greaterThan(0),1,4))})}).Else(()=>{sm(t.z.greaterThan(t.y),()=>{n.assign(j_(e.z.greaterThan(0),2,5))}).Else(()=>{n.assign(j_(e.y.greaterThan(0),1,4))})}),n}).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),RS=nm(([e,t])=>{const n=dm().toVar();return sm(t.equal(0),()=>{n.assign(dm(e.z,e.y).div(c_(e.x)))}).ElseIf(t.equal(1),()=>{n.assign(dm(e.x.negate(),e.z.negate()).div(c_(e.y)))}).ElseIf(t.equal(2),()=>{n.assign(dm(e.x.negate(),e.y).div(c_(e.z)))}).ElseIf(t.equal(3),()=>{n.assign(dm(e.z.negate(),e.y).div(c_(e.x)))}).ElseIf(t.equal(4),()=>{n.assign(dm(e.x.negate(),e.z).div(c_(e.y)))}).Else(()=>{n.assign(dm(e.x,e.y).div(c_(e.z)))}),vg(.5,n.add(1))}).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),CS=nm(([e])=>{const t=lm(0).toVar();return sm(e.greaterThanEqual(_S),()=>{t.assign(mS.sub(e).mul(vS.sub(gS)).div(mS.sub(_S)).add(gS))}).ElseIf(e.greaterThanEqual(yS),()=>{t.assign(_S.sub(e).mul(xS.sub(vS)).div(_S.sub(yS)).add(vS))}).ElseIf(e.greaterThanEqual(bS),()=>{t.assign(yS.sub(e).mul(TS.sub(xS)).div(yS.sub(bS)).add(xS))}).ElseIf(e.greaterThanEqual(SS),()=>{t.assign(bS.sub(e).mul(MS.sub(TS)).div(bS.sub(SS)).add(TS))}).Else(()=>{t.assign(lm(-2).mul(Qg(vg(1.16,e))))}),t}).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),NS=nm(([e,t])=>{const n=e.toVar();n.assign(vg(2,n).sub(1));const r=gm(n,1).toVar();return sm(t.equal(0),()=>{r.assign(r.zyx)}).ElseIf(t.equal(1),()=>{r.assign(r.xzy),r.xz.mulAssign(-1)}).ElseIf(t.equal(2),()=>{r.x.mulAssign(-1)}).ElseIf(t.equal(3),()=>{r.assign(r.zyx),r.xz.mulAssign(-1)}).ElseIf(t.equal(4),()=>{r.assign(r.xzy),r.xy.mulAssign(-1)}).ElseIf(t.equal(5),()=>{r.z.mulAssign(-1)}),r}).setLayout({name:"getDirection",type:"vec3",inputs:[{name:"uv",type:"vec2"},{name:"face",type:"float"}]}),PS=nm(([e,t,n,r,i,s])=>{const a=lm(n),o=gm(t),l=F_(CS(a),gS,s),u=r_(l),c=e_(l),h=gm(LS(e,o,c,r,i,s)).toVar();return sm(u.notEqual(0),()=>{const t=gm(LS(e,o,c.add(1),r,i,s)).toVar();h.assign(O_(h,t,u))}),h}),LS=nm(([e,t,n,r,i,s])=>{const a=lm(n).toVar(),o=gm(t),l=lm(AS(o)).toVar(),u=lm(S_(wS.sub(a),0)).toVar();a.assign(S_(a,wS));const c=lm(Yg(a)).toVar(),h=dm(RS(o,l).mul(c.sub(2)).add(1)).toVar();return sm(l.greaterThan(2),()=>{h.y.addAssign(c),l.subAssign(3)}),h.x.addAssign(l.mul(c)),h.x.addAssign(u.mul(vg(3,ES))),h.y.addAssign(vg(4,Yg(s).sub(c))),h.x.mulAssign(r),h.y.mulAssign(i),e.sample(h).grad(dm(),dm())}),DS=nm(({envMap:e,mipInt:t,outputDirection:n,theta:r,axis:i,CUBEUV_TEXEL_WIDTH:s,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const l=s_(r),u=n.mul(l).add(i.cross(n).mul(i_(r))).add(i.mul(i.dot(n).mul(l.oneMinus())));return LS(e,u,t,s,a,o)}),IS=nm(({n:e,latitudinal:t,poleAxis:n,outputDirection:r,weights:i,samples:s,dTheta:a,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:c,CUBEUV_MAX_MIP:h})=>{const d=gm(j_(t,n,C_(n,r))).toVar();sm(d.equal(gm(0)),()=>{d.assign(gm(r.z,0,r.x.negate()))}),d.assign(n_(d));const p=gm().toVar();return p.addAssign(i.element(0).mul(DS({theta:0,axis:d,outputDirection:r,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:c,CUBEUV_MAX_MIP:h}))),fb({start:um(1),end:e},({i:e})=>{sm(e.greaterThanEqual(s),()=>{Tv("break").toStack()});const t=lm(a.mul(lm(e))).toVar();p.addAssign(i.element(e).mul(DS({theta:t.mul(-1),axis:d,outputDirection:r,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:c,CUBEUV_MAX_MIP:h}))),p.addAssign(i.element(e).mul(DS({theta:t,axis:d,outputDirection:r,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:c,CUBEUV_MAX_MIP:h})))}),xm(p,1)}),US=[.125,.215,.35,.446,.526,.582],OS=20,FS=new na(-1,1,1,-1,0,1),BS=new Mi(90,1),kS=new Nr;let zS=null,VS=0,GS=0;const HS=(1+Math.sqrt(5))/2,jS=1/HS,WS=[new Ut(-HS,jS,0),new Ut(HS,jS,0),new Ut(-jS,0,HS),new Ut(jS,0,HS),new Ut(0,HS,-jS),new Ut(0,HS,jS),new Ut(-1,1,-1),new Ut(1,1,-1),new Ut(-1,1,1),new Ut(1,1,1)],XS=new Ut,qS=new WeakMap,$S=[3,1,5,0,4,2],YS=NS(Av(),Ev("faceIndex")).normalize(),KS=gm(YS.x,YS.y,YS.z);class QS{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._backgroundBox=null}get _hasInitialized(){return this._renderer.hasInitialized()}fromScene(e,t=0,n=.1,r=100,i={}){const{size:s=256,position:a=XS,renderTarget:o=null}=i;if(this._setSize(s),!1===this._hasInitialized){console.warn("THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.");const s=o||this._allocateTarget();return i.renderTarget=s,this.fromSceneAsync(e,t,n,r,i),s}zS=this._renderer.getRenderTarget(),VS=this._renderer.getActiveCubeFace(),GS=this._renderer.getActiveMipmapLevel();const l=o||this._allocateTarget();return l.depthBuffer=!0,this._init(l),this._sceneToCubeUV(e,n,r,l,a),t>0&&this._blur(l,0,0,t),this._applyPMREM(l),this._cleanup(l),l}async fromSceneAsync(e,t=0,n=.1,r=100,i={}){return!1===this._hasInitialized&&await this._renderer.init(),this.fromScene(e,t,n,r,i)}fromEquirectangular(e,t=null){if(!1===this._hasInitialized){console.warn("THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead."),this._setSizeFromTexture(e);const n=t||this._allocateTarget();return this.fromEquirectangularAsync(e,n),n}return this._fromTexture(e,t)}async fromEquirectangularAsync(e,t=null){return!1===this._hasInitialized&&await this._renderer.init(),this._fromTexture(e,t)}fromCubemap(e,t=null){if(!1===this._hasInitialized){console.warn("THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead."),this._setSizeFromTexture(e);const n=t||this._allocateTarget();return this.fromCubemapAsync(e,t),n}return this._fromTexture(e,t)}async fromCubemapAsync(e,t=null){return!1===this._hasInitialized&&await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=tM(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=nM(),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===G||e.mapping===H?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._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodPlanes.length;e++)this._lodPlanes[e].dispose()}_cleanup(e){this._renderer.setRenderTarget(zS,VS,GS),e.scissorTest=!1,JS(e,0,0,e.width,e.height)}_fromTexture(e,t){this._setSizeFromTexture(e),zS=this._renderer.getRenderTarget(),VS=this._renderer.getActiveCubeFace(),GS=this._renderer.getActiveMipmapLevel();const n=t||this._allocateTarget();return this._init(n),this._textureToCubeUV(e,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTarget(){return ZS(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=ZS(e.width,e.height);const{_lodMax:t}=this;({sizeLods:this._sizeLods,lodPlanes:this._lodPlanes,sigmas:this._sigmas,lodMeshes:this._lodMeshes}=function(e){const t=[],n=[],r=[],i=[];let s=e;const a=e-4+1+US.length;for(let o=0;o<a;o++){const a=Math.pow(2,s);n.push(a);let l=1/a;o>e-4?l=US[o-e+4-1]:0===o&&(l=0),r.push(l);const u=1/(a-2),c=-u,h=1+u,d=[c,c,h,c,h,h,c,c,h,h,c,h],p=6,f=6,m=3,g=2,_=1,v=new Float32Array(m*f*p),y=new Float32Array(g*f*p),x=new Float32Array(_*f*p);for(let e=0;e<p;e++){const t=e%3*2/3-1,n=e>2?0:-1,r=[t,n,0,t+2/3,n,0,t+2/3,n+1,0,t,n,0,t+2/3,n+1,0,t,n+1,0],i=$S[e];v.set(r,m*f*i),y.set(d,g*f*i);const s=[i,i,i,i,i,i];x.set(s,_*f*i)}const b=new ei;b.setAttribute("position",new Gr(v,m)),b.setAttribute("uv",new Gr(y,g)),b.setAttribute("faceIndex",new Gr(x,_)),t.push(b),i.push(new di(b,null)),s>4&&s--}return{lodPlanes:t,sizeLods:n,sigmas:r,lodMeshes:i}}(t)),this._blurMaterial=function(e,t,n){const r=Vv(new Array(OS).fill(0)),i=cg(new Ut(0,1,0)),s=cg(0),a=lm(OS),o=cg(0),l=cg(1),u=Uv(null),c=cg(0),h=lm(1/t),d=lm(1/n),p=lm(e),f={n:a,latitudinal:o,weights:r,poleAxis:i,outputDirection:KS,dTheta:s,samples:l,envMap:u,mipInt:c,CUBEUV_TEXEL_WIDTH:h,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:p},m=eM("blur");return m.fragmentNode=IS({...f,latitudinal:o.equal(1)}),qS.set(m,f),m}(t,e.width,e.height)}}async _compileMaterial(e){const t=new di(this._lodPlanes[0],e);await this._renderer.compile(t,FS)}_sceneToCubeUV(e,t,n,r,i){const s=BS;s.near=t,s.far=n;const a=[1,1,1,1,-1,1],o=[1,-1,1,-1,1,-1],l=this._renderer,u=l.autoClear;l.getClearColor(kS),l.autoClear=!1;let c=this._backgroundBox;if(null===c){const e=new Ir({name:"PMREM.Background",side:1,depthWrite:!1,depthTest:!1});c=new di(new fi,e)}let h=!1;const d=e.background;d?d.isColor&&(c.material.color.copy(d),e.background=null,h=!0):(c.material.color.copy(kS),h=!0),l.setRenderTarget(r),l.clear(),h&&l.render(c,s);for(let t=0;t<6;t++){const n=t%3;0===n?(s.up.set(0,a[t],0),s.position.set(i.x,i.y,i.z),s.lookAt(i.x+o[t],i.y,i.z)):1===n?(s.up.set(0,0,a[t]),s.position.set(i.x,i.y,i.z),s.lookAt(i.x,i.y+o[t],i.z)):(s.up.set(0,a[t],0),s.position.set(i.x,i.y,i.z),s.lookAt(i.x,i.y,i.z+o[t]));const u=this._cubeSize;JS(r,n*u,t>2?u:0,u,u),l.render(e,s)}l.autoClear=u,e.background=d}_textureToCubeUV(e,t){const n=this._renderer,r=e.mapping===G||e.mapping===H;r?null===this._cubemapMaterial&&(this._cubemapMaterial=tM(e)):null===this._equirectMaterial&&(this._equirectMaterial=nM(e));const i=r?this._cubemapMaterial:this._equirectMaterial;i.fragmentNode.value=e;const s=this._lodMeshes[0];s.material=i;const a=this._cubeSize;JS(t,0,0,3*a,2*a),n.setRenderTarget(t),n.render(s,FS)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;const r=this._lodPlanes.length;for(let t=1;t<r;t++){const n=Math.sqrt(this._sigmas[t]*this._sigmas[t]-this._sigmas[t-1]*this._sigmas[t-1]),i=WS[(r-t-1)%WS.length];this._blur(e,t-1,t,n,i)}t.autoClear=n}_blur(e,t,n,r,i){const s=this._pingPongRenderTarget;this._halfBlur(e,s,t,n,r,"latitudinal",i),this._halfBlur(s,e,n,n,r,"longitudinal",i)}_halfBlur(e,t,n,r,i,s,a){const o=this._renderer,l=this._blurMaterial;"latitudinal"!==s&&"longitudinal"!==s&&console.error("blur direction must be either latitudinal or longitudinal!");const u=this._lodMeshes[r];u.material=l;const c=qS.get(l),h=this._sizeLods[n]-1,d=isFinite(i)?Math.PI/(2*h):2*Math.PI/39,p=i/d,f=isFinite(i)?1+Math.floor(3*p):OS;f>OS&&console.warn(`sigmaRadians, ${i}, is too large and will clip, as it requested ${f} samples when the maximum is set to 20`);const m=[];let g=0;for(let e=0;e<OS;++e){const t=e/p,n=Math.exp(-t*t/2);m.push(n),0===e?g+=n:e<f&&(g+=2*n)}for(let e=0;e<m.length;e++)m[e]=m[e]/g;e.texture.frame=(e.texture.frame||0)+1,c.envMap.value=e.texture,c.samples.value=f,c.weights.array=m,c.latitudinal.value="latitudinal"===s?1:0,a&&(c.poleAxis.value=a);const{_lodMax:_}=this;c.dTheta.value=d,c.mipInt.value=_-n;const v=this._sizeLods[r];JS(t,3*v*(r>_-4?r-_+4:0),4*(this._cubeSize-v),3*v,2*v),o.setRenderTarget(t),o.render(u,FS)}}function ZS(e,t){const n=new on(e,t,{magFilter:J,minFilter:J,generateMipmaps:!1,type:ue,format:ge,colorSpace:it});return n.texture.mapping=X,n.texture.name="PMREM.cubeUv",n.texture.isPMREMTexture=!0,n.scissorTest=!0,n}function JS(e,t,n,r,i){e.viewport.set(t,n,r,i),e.scissor.set(t,n,r,i)}function eM(e){const t=new Qb;return t.depthTest=!1,t.depthWrite=!1,t.blending=0,t.name=`PMREM_${e}`,t}function tM(e){const t=eM("cubemap");return t.fragmentNode=Fy(e,KS),t}function nM(e){const t=eM("equirect");return t.fragmentNode=Uv(e,iT(KS),0),t}const rM=new WeakMap;function iM(e,t,n){const r=function(e){let t=rM.get(e);void 0===t&&(t=new WeakMap,rM.set(e,t));return t}(t);let i=r.get(e);if((void 0!==i?i.pmremVersion:-1)!==e.pmremVersion){const t=e.image;if(e.isCubeTexture){if(!function(e){if(null==e)return!1;let t=0;const n=6;for(let r=0;r<n;r++)void 0!==e[r]&&t++;return t===n}(t))return null;i=n.fromCubemap(e,i)}else{if(!function(e){return null!=e&&e.height>0}(t))return null;i=n.fromEquirectangular(e,i)}i.pmremVersion=e.pmremVersion,r.set(e,i)}return i.texture}class sM extends df{static get type(){return"PMREMNode"}constructor(e,t=null,n=null){super("vec3"),this._value=e,this._pmrem=null,this.uvNode=t,this.levelNode=n,this._generator=null;const r=new sn;r.isRenderTargetTexture=!0,this._texture=Uv(r),this._width=cg(0),this._height=cg(0),this._maxMip=cg(0),this.updateBeforeType=Zp}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,n=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,t),112)),texelHeight:n,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 n=t?t.pmremVersion:-1,r=this._value;n!==r.pmremVersion&&(t=!0===r.isPMREMTexture?r:iM(r,e.renderer,this._generator),null!==t&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){null===this._generator&&(this._generator=new QS(e.renderer)),this.updateBefore(e);let t=this.uvNode;null===t&&e.context.getUV&&(t=e.context.getUV(this)),t=Cy.mul(gm(t.x,t.y.negate(),t.z));let n=this.levelNode;return null===n&&e.context.getTextureLevel&&(n=e.context.getTextureLevel(this)),PS(this._texture,t,n,this._width,this._height,this._maxMip)}dispose(){super.dispose(),null!==this._generator&&this._generator.dispose()}}const aM=Jf(sM).setParameterLength(1,3),oM=new WeakMap;class lM extends xb{static get type(){return"EnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){const{material:t}=e;let n=this.envNode;if(n.isTextureNode||n.isMaterialReferenceNode){const e=n.isTextureNode?n.value:t[n.property];let r=oM.get(e);void 0===r&&(r=aM(e),oM.set(e,r)),n=r}const r=!0===t.useAnisotropy||t.anisotropy>0?ux:xy,i=n.context(uM(Lm,r)).mul(Ry),s=n.context(cM(by)).mul(Math.PI).mul(Ry),a=gv(i),o=gv(s);e.context.radiance.addAssign(a),e.context.iblIrradiance.addAssign(o);const l=e.context.lightingModel.clearcoatRadiance;if(l){const e=n.context(uM(Um,Ty)).mul(Ry),t=gv(e);l.addAssign(t)}}}const uM=(e,t)=>{let n=null;return{getUV:()=>(null===n&&(n=hy.negate().reflect(t),n=e.mul(e).mix(n,t).normalize(),n=n.transformDirection(qv)),n),getTextureLevel:()=>e}},cM=e=>({getUV:()=>e,getTextureLevel:()=>lm(1)}),hM=new As;class dM extends Qb{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(hM),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return null===t&&e.environmentNode&&(t=e.environmentNode),t?new lM(t):null}setupLightingModel(){return new fS}setupSpecular(){const e=O_(gm(.04),Nm.rgb,Dm);Wm.assign(e),Xm.assign(1)}setupVariants(){const e=this.metalnessNode?lm(this.metalnessNode):Cx;Dm.assign(e);let t=this.roughnessNode?lm(this.roughnessNode):Rx;t=AT({roughness:t}),Lm.assign(t),this.setupSpecular(),Nm.assign(xm(Nm.rgb.mul(e.oneMinus()),Nm.a))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}const pM=new Rs;class fM extends dM{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(pM),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?lm(this.iorNode):Hx;Qm.assign(e),Wm.assign(O_(T_(P_(Qm.sub(1).div(Qm.add(1))).mul(wx),gm(1)).mul(Mx),Nm.rgb,Dm)),Xm.assign(O_(Mx,1,Dm))}setupLightingModel(){return new fS(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?lm(this.clearcoatNode):Px,t=this.clearcoatRoughnessNode?lm(this.clearcoatRoughnessNode):Lx;Im.assign(e),Um.assign(AT({roughness:t}))}if(this.useSheen){const e=this.sheenNode?gm(this.sheenNode):Ux,t=this.sheenRoughnessNode?lm(this.sheenRoughnessNode):Ox;Om.assign(e),Fm.assign(t)}if(this.useIridescence){const e=this.iridescenceNode?lm(this.iridescenceNode):Bx,t=this.iridescenceIORNode?lm(this.iridescenceIORNode):kx,n=this.iridescenceThicknessNode?lm(this.iridescenceThicknessNode):zx;Bm.assign(e),km.assign(t),zm.assign(n)}if(this.useAnisotropy){const e=(this.anisotropyNode?dm(this.anisotropyNode):Fx).toVar();Gm.assign(e.length()),sm(Gm.equal(0),()=>{e.assign(dm(1,0))}).Else(()=>{e.divAssign(dm(Gm)),Gm.assign(Gm.saturate())}),Vm.assign(Gm.pow2().mix(Lm.pow2(),1)),Hm.assign(lx[0].mul(e.x).add(lx[1].mul(e.y))),jm.assign(lx[1].mul(e.x).sub(lx[0].mul(e.y)))}if(this.useTransmission){const e=this.transmissionNode?lm(this.transmissionNode):Vx,t=this.thicknessNode?lm(this.thicknessNode):Gx,n=this.attenuationDistanceNode?lm(this.attenuationDistanceNode):jx,r=this.attenuationColorNode?gm(this.attenuationColorNode):Wx;if(Zm.assign(e),Jm.assign(t),eg.assign(n),tg.assign(r),this.useDispersion){const e=this.dispersionNode?lm(this.dispersionNode):Qx;ng.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?gm(this.clearcoatNormalNode):Dx}setup(e){e.context.setupClearcoatNormal=()=>K_(this.setupClearcoatNormal(e),"NORMAL","vec3"),super.setup(e)}copy(e){return this.clearcoatNode=e.clearcoatNode,this.clearcoatRoughnessNode=e.clearcoatRoughnessNode,this.clearcoatNormalNode=e.clearcoatNormalNode,this.sheenNode=e.sheenNode,this.sheenRoughnessNode=e.sheenRoughnessNode,this.iridescenceNode=e.iridescenceNode,this.iridescenceIORNode=e.iridescenceIORNode,this.iridescenceThicknessNode=e.iridescenceThicknessNode,this.specularIntensityNode=e.specularIntensityNode,this.specularColorNode=e.specularColorNode,this.transmissionNode=e.transmissionNode,this.thicknessNode=e.thicknessNode,this.attenuationDistanceNode=e.attenuationDistanceNode,this.attenuationColorNode=e.attenuationColorNode,this.dispersionNode=e.dispersionNode,this.anisotropyNode=e.anisotropyNode,super.copy(e)}}const mM=nm(({normal:e,lightDirection:t,builder:n})=>{const r=e.dot(t),i=dm(r.mul(.5).add(.5),0);if(n.material.gradientMap){const e=Hy("gradientMap","texture").context({getUV:()=>i});return gm(e.r)}{const e=i.fwidth().mul(.5);return O_(gm(.7),gm(1),z_(lm(.7).sub(e.x),lm(.7).add(e.x),i.x))}});class gM extends pT{direct({lightDirection:e,lightColor:t,reflectedLight:n},r){const i=mM({normal:my,lightDirection:e,builder:r}).mul(t);n.directDiffuse.addAssign(i.mul(vT({diffuseColor:Nm.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:n,reflectedLight:r}=e.context;r.indirectDiffuse.addAssign(n.mul(vT({diffuseColor:Nm}))),r.indirectDiffuse.mulAssign(t)}}const _M=new Ns;class vM extends Qb{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(_M),this.setValues(e)}setupLightingModel(){return new gM}}const yM=nm(()=>{const e=gm(hy.z,0,hy.x.negate()).normalize(),t=hy.cross(e);return dm(e.dot(xy),t.dot(xy)).mul(.495).add(.5)}).once(["NORMAL","VERTEX"])().toVar("matcapUV"),xM=new Us;class bM extends Qb{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(xM),this.setValues(e)}setupVariants(e){const t=yM;let n;n=e.material.matcap?Hy("matcap","texture").context({getUV:()=>t}):gm(O_(.2,.8,t.y)),Nm.rgb.mulAssign(n.rgb)}}class TM extends df{static get type(){return"RotateNode"}constructor(e,t){super(),this.positionNode=e,this.rotationNode=t}getNodeType(e){return this.positionNode.getNodeType(e)}setup(e){const{rotationNode:t,positionNode:n}=this;if("vec2"===this.getNodeType(e)){const e=t.cos(),r=t.sin();return Mm(e,r,r.negate(),e).mul(n)}{const e=t,r=Em(xm(1,0,0,0),xm(0,s_(e.x),i_(e.x).negate(),0),xm(0,i_(e.x),s_(e.x),0),xm(0,0,0,1)),i=Em(xm(s_(e.y),0,i_(e.y),0),xm(0,1,0,0),xm(i_(e.y).negate(),0,s_(e.y),0),xm(0,0,0,1)),s=Em(xm(s_(e.z),i_(e.z).negate(),0,0),xm(i_(e.z),s_(e.z),0,0),xm(0,0,1,0),xm(0,0,0,1));return r.mul(i).mul(s).mul(xm(n,1)).xyz}}}const SM=Jf(TM).setParameterLength(2),MM=new Oi;class wM extends Qb{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(MM),this.setValues(e)}setupPositionView(e){const{object:t,camera:n}=e,r=this.sizeAttenuation,{positionNode:i,rotationNode:s,scaleNode:a}=this,o=ty.mul(gm(i||0));let l=dm(Jv[0].xyz.length(),Jv[1].xyz.length());if(null!==a&&(l=l.mul(dm(a))),!1===r)if(n.isPerspectiveCamera)l=l.mul(o.z.negate());else{const e=lm(2).div(Xv.element(1).element(1));l=l.mul(e.mul(2))}let u=sy.xy;if(t.center&&!0===t.center.isVector2){const e=((e,t,n)=>Kf(new sv(e,t,n)))("center","vec2",t);u=u.sub(e.sub(.5))}u=u.mul(l);const c=lm(s||Ix),h=SM(u,c);return xm(o.xy.add(h),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 EM=new ss;class AM extends wM{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(EM),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return ty.mul(gm(e||ay)).xyz}setupVertex(e){const t=super.setupVertex(e);if(!0!==e.material.isNodeMaterial)return t;const{rotationNode:n,scaleNode:r,sizeNode:i}=this,s=sy.xy.toVar(),a=Pb.z.div(Pb.w);if(n&&n.isNode){const e=lm(n);s.assign(SM(s,e))}let o=null!==i?dm(i):Kx;return!0===this.sizeAttenuation&&(o=o.mul(o.div(cy.z.negate()))),r&&r.isNode&&(o=o.mul(dm(r))),s.mulAssign(o.mul(2)),s.assign(s.div(Pb.z)),s.y.assign(s.y.mul(a)),s.assign(s.mul(t.w)),t.addAssign(xm(s,0,0)),t}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}}class RM extends pT{constructor(){super(),this.shadowNode=lm(1).toVar("shadowMask")}direct({lightNode:e}){null!==e.shadowNode&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){Nm.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(Nm.rgb)}}const CM=new Es;class NM extends Qb{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(CM),this.setValues(e)}setupLightingModel(){return new RM}}Rm("vec3"),Rm("vec3"),Rm("vec3");class PM{constructor(e,t){this.nodes=e,this.info=t,this._context="undefined"!=typeof self?self:null,this._animationLoop=null,this._requestId=null}start(){const e=(t,n)=>{this._requestId=this._context.requestAnimationFrame(e),!0===this.info.autoReset&&this.info.reset(),this.nodes.nodeFrame.update(),this.info.frame=this.nodes.nodeFrame.frameId,null!==this._animationLoop&&this._animationLoop(t,n)};e()}stop(){this._context.cancelAnimationFrame(this._requestId),this._requestId=null}getAnimationLoop(){return this._animationLoop}setAnimationLoop(e){this._animationLoop=e}getContext(){return this._context}setContext(e){this._context=e}dispose(){this.stop()}}class LM{constructor(){this.weakMap=new WeakMap}get(e){let t=this.weakMap;for(let n=0;n<e.length-1;n++)if(t=t.get(e[n]),void 0===t)return;return t.get(e[e.length-1])}set(e,t){let n=this.weakMap;for(let t=0;t<e.length-1;t++){const r=e[t];!1===n.has(r)&&n.set(r,new WeakMap),n=n.get(r)}return n.set(e[e.length-1],t),this}delete(e){let t=this.weakMap;for(let n=0;n<e.length-1;n++)if(t=t.get(e[n]),void 0===t)return!1;return t.delete(e[e.length-1])}}let DM=0;class IM{constructor(e,t,n,r,i,s,a,o,l,u){this.id=DM++,this._nodes=e,this._geometries=t,this.renderer=n,this.object=r,this.material=i,this.scene=s,this.camera=a,this.lightsNode=o,this.context=l,this.geometry=r.geometry,this.version=i.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=u,this.clippingContextCacheKey=null!==u?u.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)}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,n=[],r=new Set,i={};for(const s of e){let e;if(s.node&&s.node.attribute?e=s.node.attribute:(e=t.getAttribute(s.name),i[s.name]=e.version),void 0===e)continue;n.push(e);const a=e.isInterleavedBufferAttribute?e.data:e;r.add(a)}return this.attributes=n,this.attributesId=i,this.vertexBuffers=Array.from(r.values()),n}getVertexBuffers(){return null===this.vertexBuffers&&this.getAttributes(),this.vertexBuffers}getDrawParameters(){const{object:e,material:t,geometry:n,group:r,drawRange:i}=this,s=this.drawParams||(this.drawParams={vertexCount:0,firstVertex:0,instanceCount:0,firstInstance:0}),a=this.getIndex(),o=null!==a;let l=1;if(!0===n.isInstancedBufferGeometry?l=n.instanceCount:void 0!==e.count&&(l=Math.max(0,e.count)),0===l)return null;if(s.instanceCount=l,!0===e.isBatchedMesh)return s;let u=1;!0!==t.wireframe||e.isPoints||e.isLineSegments||e.isLine||e.isLineLoop||(u=2);let c=i.start*u,h=(i.start+i.count)*u;null!==r&&(c=Math.max(c,r.start*u),h=Math.min(h,(r.start+r.count)*u));const d=n.attributes.position;let p=1/0;o?p=a.count:null!=d&&(p=d.count),c=Math.max(c,0),h=Math.min(h,p);const f=h-c;return f<0||f===1/0?null:(s.vertexCount=f,s.firstVertex=c,s)}getGeometryCacheKey(){const{geometry:e}=this;let t="";for(const n of Object.keys(e.attributes).sort()){const r=e.attributes[n];t+=n+",",r.data&&(t+=r.data.stride+","),r.offset&&(t+=r.offset+","),r.itemSize&&(t+=r.itemSize+","),r.normalized&&(t+="n,")}for(const n of Object.keys(e.morphAttributes).sort()){const r=e.morphAttributes[n];t+="morph-"+n+",";for(let e=0,n=r.length;e<n;e++){t+=r[e].id+","}}return e.index&&(t+="index,"),t}getMaterialCacheKey(){const{object:e,material:t}=this;let n=t.customProgramCacheKey();for(const e of function(e){const t=Object.keys(e);let n=Object.getPrototypeOf(e);for(;n;){const e=Object.getOwnPropertyDescriptors(n);for(const n in e)if(void 0!==e[n]){const r=e[n];r&&"function"==typeof r.get&&t.push(n)}n=Object.getPrototypeOf(n)}return t}(t)){if(/^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test(e))continue;const r=t[e];let i;if(null!==r){const e=typeof r;"number"===e?i=0!==r?"1":"0":"object"===e?(i="{",r.isTexture&&(i+=r.mapping),i+="}"):i=String(r)}else i=String(r);n+=i+","}return n+=this.clippingContextCacheKey+",",e.geometry&&(n+=this.getGeometryCacheKey()),e.skeleton&&(n+=e.skeleton.bones.length+","),e.isBatchedMesh&&(n+=e._matricesTexture.uuid+",",null!==e._colorsTexture&&(n+=e._colorsTexture.uuid+",")),e.count>1&&(n+=e.uuid+","),n+=e.receiveShadow+",",kp(n)}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 n=this.geometry.getAttribute(t);if(void 0===n||e[t]!==n.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=Vp(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=Vp(e,1)),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.geometry.removeEventListener("dispose",this.onGeometryDispose),this.onDispose()}}const UM=[];class OM{constructor(e,t,n,r,i,s){this.renderer=e,this.nodes=t,this.geometries=n,this.pipelines=r,this.bindings=i,this.info=s,this.chainMaps={}}get(e,t,n,r,i,s,a,o){const l=this.getChainMap(o);UM[0]=e,UM[1]=t,UM[2]=s,UM[3]=i;let u=l.get(UM);return void 0===u?(u=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,n,r,i,s,a,o),l.set(UM,u)):(u.updateClipping(a),u.needsGeometryUpdate&&u.setGeometry(e.geometry),(u.version!==t.version||u.needsUpdate)&&(u.initialCacheKey!==u.getCacheKey()?(u.dispose(),u=this.get(e,t,n,r,i,s,a,o)):u.version=t.version)),UM.length=0,u}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new LM)}dispose(){this.chainMaps={}}createRenderObject(e,t,n,r,i,s,a,o,l,u,c){const h=this.getChainMap(c),d=new IM(e,t,n,r,i,s,a,o,l,u);return d.onDispose=()=>{this.pipelines.delete(d),this.bindings.delete(d),this.nodes.delete(d),h.delete(d.getChainArray())},d}}class FM{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 BM=1,kM=2,zM=3,VM=4,GM=16;class HM extends FM{constructor(e){super(),this.backend=e}delete(e){const t=super.delete(e);return null!==t&&this.backend.destroyAttribute(e),t}update(e,t){const n=this.get(e);if(void 0===n.version)t===BM?this.backend.createAttribute(e):t===kM?this.backend.createIndexAttribute(e):t===zM?this.backend.createStorageAttribute(e):t===VM&&this.backend.createIndirectStorageAttribute(e),n.version=this._getBufferAttribute(e).version;else{const t=this._getBufferAttribute(e);(n.version<t.version||t.usage===_t)&&(this.backend.updateAttribute(e),n.version=t.version)}}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}function jM(e){return null!==e.index?e.index.version:e.attributes.position.version}function WM(e){const t=[],n=e.index,r=e.attributes.position;if(null!==n){const e=n.array;for(let n=0,r=e.length;n<r;n+=3){const r=e[n+0],i=e[n+1],s=e[n+2];t.push(r,i,i,s,s,r)}}else{for(let e=0,n=r.array.length/3-1;e<n;e+=3){const n=e+0,r=e+1,i=e+2;t.push(n,r,r,i,i,n)}}const i=new(zt(t)?jr:Hr)(t,1);return i.version=jM(e),i}class XM extends FM{constructor(e,t){super(),this.attributes=e,this.info=t,this.wireframes=new WeakMap,this.attributeCall=new WeakMap}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 n=()=>{this.info.memory.geometries--;const r=t.index,i=e.getAttributes();null!==r&&this.attributes.delete(r);for(const e of i)this.attributes.delete(e);const s=this.wireframes.get(t);void 0!==s&&this.attributes.delete(s),t.removeEventListener("dispose",n)};t.addEventListener("dispose",n)}updateAttributes(e){const t=e.getAttributes();for(const e of t)e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute?this.updateAttribute(e,zM):this.updateAttribute(e,BM);const n=this.getIndex(e);null!==n&&this.updateAttribute(n,kM);const r=e.geometry.indirect;null!==r&&this.updateAttribute(r,VM)}updateAttribute(e,t){const n=this.info.render.calls;e.isInterleavedBufferAttribute?void 0===this.attributeCall.get(e)?(this.attributes.update(e,t),this.attributeCall.set(e,n)):this.attributeCall.get(e.data)!==n&&(this.attributes.update(e,t),this.attributeCall.set(e.data,n),this.attributeCall.set(e,n)):this.attributeCall.get(e)!==n&&(this.attributes.update(e,t),this.attributeCall.set(e,n))}getIndirect(e){return e.geometry.indirect}getIndex(e){const{geometry:t,material:n}=e;let r=t.index;if(!0===n.wireframe){const e=this.wireframes;let n=e.get(t);void 0===n?(n=WM(t),e.set(t,n)):n.version!==jM(t)&&(this.attributes.delete(n),n=WM(t),e.set(t,n)),r=n}return r}}class qM{constructor(){this.autoReset=!0,this.frame=0,this.calls=0,this.render={calls:0,frameCalls:0,drawCalls:0,triangles:0,points:0,lines:0,timestamp:0},this.compute={calls:0,frameCalls:0,timestamp:0},this.memory={geometries:0,textures:0}}update(e,t,n){this.render.drawCalls++,e.isMesh||e.isSprite?this.render.triangles+=n*(t/3):e.isPoints?this.render.points+=n*t:e.isLineSegments?this.render.lines+=n*(t/2):e.isLine?this.render.lines+=n*(t-1):console.error("THREE.WebGPUInfo: Unknown object type.")}reset(){this.render.drawCalls=0,this.render.frameCalls=0,this.compute.frameCalls=0,this.render.triangles=0,this.render.points=0,this.render.lines=0}dispose(){this.reset(),this.calls=0,this.render.calls=0,this.compute.calls=0,this.render.timestamp=0,this.compute.timestamp=0,this.memory.geometries=0,this.memory.textures=0}}class $M{constructor(e){this.cacheKey=e,this.usedTimes=0}}class YM extends $M{constructor(e,t,n){super(e),this.vertexProgram=t,this.fragmentProgram=n}}class KM extends $M{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let QM=0;class ZM{constructor(e,t,n,r=null,i=null){this.id=QM++,this.code=e,this.stage=t,this.name=n,this.transforms=r,this.attributes=i,this.usedTimes=0}}class JM extends FM{constructor(e,t){super(),this.backend=e,this.nodes=t,this.bindings=null,this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}getForCompute(e,t){const{backend:n}=this,r=this.get(e);if(this._needsComputeUpdate(e)){const i=r.pipeline;i&&(i.usedTimes--,i.computeProgram.usedTimes--);const s=this.nodes.getForCompute(e);let a=this.programs.compute.get(s.computeShader);void 0===a&&(i&&0===i.computeProgram.usedTimes&&this._releaseProgram(i.computeProgram),a=new ZM(s.computeShader,"compute",e.name,s.transforms,s.nodeAttributes),this.programs.compute.set(s.computeShader,a),n.createProgram(a));const o=this._getComputeCacheKey(e,a);let l=this.caches.get(o);void 0===l&&(i&&0===i.usedTimes&&this._releasePipeline(i),l=this._getComputePipeline(e,a,o,t)),l.usedTimes++,a.usedTimes++,r.version=e.version,r.pipeline=l}return r.pipeline}getForRender(e,t=null){const{backend:n}=this,r=this.get(e);if(this._needsRenderUpdate(e)){const i=r.pipeline;i&&(i.usedTimes--,i.vertexProgram.usedTimes--,i.fragmentProgram.usedTimes--);const s=e.getNodeBuilderState(),a=e.material?e.material.name:"";let o=this.programs.vertex.get(s.vertexShader);void 0===o&&(i&&0===i.vertexProgram.usedTimes&&this._releaseProgram(i.vertexProgram),o=new ZM(s.vertexShader,"vertex",a),this.programs.vertex.set(s.vertexShader,o),n.createProgram(o));let l=this.programs.fragment.get(s.fragmentShader);void 0===l&&(i&&0===i.fragmentProgram.usedTimes&&this._releaseProgram(i.fragmentProgram),l=new ZM(s.fragmentShader,"fragment",a),this.programs.fragment.set(s.fragmentShader,l),n.createProgram(l));const u=this._getRenderCacheKey(e,o,l);let c=this.caches.get(u);void 0===c?(i&&0===i.usedTimes&&this._releasePipeline(i),c=this._getRenderPipeline(e,o,l,u,t)):e.pipeline=c,c.usedTimes++,o.usedTimes++,l.usedTimes++,r.pipeline=c}return r.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,n,r){n=n||this._getComputeCacheKey(e,t);let i=this.caches.get(n);return void 0===i&&(i=new KM(n,t),this.caches.set(n,i),this.backend.createComputePipeline(i,r)),i}_getRenderPipeline(e,t,n,r,i){r=r||this._getRenderCacheKey(e,t,n);let s=this.caches.get(r);return void 0===s&&(s=new YM(r,t,n),this.caches.set(r,s),e.pipeline=s,this.backend.createRenderPipeline(e,i)),s}_getComputeCacheKey(e,t){return e.id+","+t.id}_getRenderCacheKey(e,t,n){return t.id+","+n.id+","+this.backend.getRenderCacheKey(e)}_releasePipeline(e){this.caches.delete(e.cacheKey)}_releaseProgram(e){const t=e.code,n=e.stage;this.programs[n].delete(t)}_needsComputeUpdate(e){const t=this.get(e);return void 0===t.pipeline||t.version!==e.version}_needsRenderUpdate(e){return void 0===this.get(e).pipeline||this.backend.needsRenderUpdate(e)}}class ew extends FM{constructor(e,t,n,r,i,s){super(),this.backend=e,this.textures=n,this.pipelines=i,this.attributes=r,this.nodes=t,this.info=s,this.pipelines.bindings=this}getForRender(e){const t=e.getBindings();for(const e of t){const n=this.get(e);void 0===n.bindGroup&&(this._init(e),this.backend.createBindings(e,t,0),n.bindGroup=e)}return t}getForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const e of t){const n=this.get(e);void 0===n.bindGroup&&(this._init(e),this.backend.createBindings(e,t,0),n.bindGroup=e)}return t}updateForCompute(e){this._updateBindings(this.getForCompute(e))}updateForRender(e){this._updateBindings(this.getForRender(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.isStorageBuffer){const e=t.attribute,n=e.isIndirectStorageBufferAttribute?VM:zM;this.attributes.update(e,n)}}_update(e,t){const{backend:n}=this;let r=!1,i=!0,s=0,a=0;for(const t of e.bindings){if(t.isNodeUniformsGroup){if(!1===this.nodes.updateGroup(t))continue}if(t.isStorageBuffer){const e=t.attribute,n=e.isIndirectStorageBufferAttribute?VM:zM;this.attributes.update(e,n)}if(t.isUniformBuffer){t.update()&&n.updateBinding(t)}else if(t.isSampler)t.update();else if(t.isSampledTexture){const e=this.textures.get(t.texture);t.needsBindingsUpdate(e.generation)&&(r=!0);const o=t.update(),l=t.texture;o&&this.textures.updateTexture(l);const u=n.get(l);if(void 0!==u.externalTexture||e.isDefaultTexture?i=!1:(s=10*s+l.id,a+=l.version),!0===n.isWebGPUBackend&&void 0===u.texture&&void 0===u.externalTexture&&(console.error("Bindings._update: binding should be available:",t,o,l,t.textureNode.value,r),this.textures.updateTexture(l),r=!0),!0===l.isStorageTexture){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)}}}!0===r&&this.backend.updateBindings(e,t,i?s:0,a)}}function tw(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 nw(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 rw(e){return(e.transmission>0||e.transmissionNode)&&2===e.side&&!1===e.forceSinglePass}class iw{constructor(e,t,n){this.renderItems=[],this.renderItemsIndex=0,this.opaque=[],this.transparentDoublePass=[],this.transparent=[],this.bundles=[],this.lightsNode=e.getNode(t,n),this.lightsArray=[],this.scene=t,this.camera=n,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,n,r,i,s,a){let o=this.renderItems[this.renderItemsIndex];return void 0===o?(o={id:e.id,object:e,geometry:t,material:n,groupOrder:r,renderOrder:e.renderOrder,z:i,group:s,clippingContext:a},this.renderItems[this.renderItemsIndex]=o):(o.id=e.id,o.object=e,o.geometry=t,o.material=n,o.groupOrder=r,o.renderOrder=e.renderOrder,o.z=i,o.group=s,o.clippingContext=a),this.renderItemsIndex++,o}push(e,t,n,r,i,s,a){const o=this.getNextRenderItem(e,t,n,r,i,s,a);!0===e.occlusionTest&&this.occlusionQueryCount++,!0===n.transparent||n.transmission>0?(rw(n)&&this.transparentDoublePass.push(o),this.transparent.push(o)):this.opaque.push(o)}unshift(e,t,n,r,i,s,a){const o=this.getNextRenderItem(e,t,n,r,i,s,a);!0===n.transparent||n.transmission>0?(rw(n)&&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||tw),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||nw),this.transparent.length>1&&this.transparent.sort(t||nw)}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 sw=[];class aw{constructor(e){this.lighting=e,this.lists=new LM}get(e,t){const n=this.lists;sw[0]=e,sw[1]=t;let r=n.get(sw);return void 0===r&&(r=new iw(this.lighting,e,t),n.set(sw,r)),sw.length=0,r}dispose(){this.lists=new LM}}let ow=0;class lw{constructor(){this.id=ow++,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 an,this.scissor=!1,this.scissorValue=new an,this.renderTarget=null,this.textures=null,this.depthTexture=null,this.activeCubeFace=0,this.activeMipmapLevel=0,this.sampleCount=1,this.width=0,this.height=0,this.occlusionQueryCount=0,this.clippingContext=null,this.isRenderContext=!0}getCacheKey(){return uw(this)}}function uw(e){const{textures:t,activeCubeFace:n}=e,r=[n];for(const e of t)r.push(e.id);return zp(r)}const cw=[],hw=new Li,dw=new xi;class pw{constructor(){this.chainMaps={}}get(e,t,n=null){let r;if(cw[0]=e,cw[1]=t,null===n)r="default";else{const e=n.texture.format;r=`${n.textures.length}:${e}:${n.samples}:${n.depthBuffer}:${n.stencilBuffer}`}const i=this._getChainMap(r);let s=i.get(cw);return void 0===s&&(s=new lw,i.set(cw,s)),cw.length=0,null!==n&&(s.sampleCount=0===n.samples?1:n.samples),s}getForClear(e=null){return this.get(hw,dw,e)}_getChainMap(e){return this.chainMaps[e]||(this.chainMaps[e]=new LM)}dispose(){this.chainMaps={}}}const fw=new Ut;class mw extends FM{constructor(e,t,n){super(),this.renderer=e,this.backend=t,this.info=n}updateRenderTarget(e,t=0){const n=this.get(e),r=0===e.samples?1:e.samples,i=n.depthTextureMips||(n.depthTextureMips={}),s=e.textures,a=this.getSize(s[0]),o=a.width>>t,l=a.height>>t;let u=e.depthTexture||i[t];const c=!0===e.depthBuffer||!0===e.stencilBuffer;let h=!1;void 0===u&&c&&(u=new os,u.format=e.stencilBuffer?ve:_e,u.type=e.stencilBuffer?de:oe,u.image.width=o,u.image.height=l,u.image.depth=a.depth,u.isArrayTexture=!0===e.multiview&&a.depth>1,i[t]=u),n.width===a.width&&a.height===n.height||(h=!0,u&&(u.needsUpdate=!0,u.image.width=o,u.image.height=l,u.image.depth=u.isArrayTexture?u.image.depth:1)),n.width=a.width,n.height=a.height,n.textures=s,n.depthTexture=u||null,n.depth=e.depthBuffer,n.stencil=e.stencilBuffer,n.renderTarget=e,n.sampleCount!==r&&(h=!0,u&&(u.needsUpdate=!0),n.sampleCount=r);const d={sampleCount:r};if(!0!==e.isXRRenderTarget){for(let e=0;e<s.length;e++){const t=s[e];h&&(t.needsUpdate=!0),this.updateTexture(t,d)}u&&this.updateTexture(u,d)}if(!0!==n.initialized){n.initialized=!0;const t=()=>{e.removeEventListener("dispose",t);for(let e=0;e<s.length;e++)this._destroyTexture(s[e]);u&&this._destroyTexture(u),this.delete(e)};e.addEventListener("dispose",t)}}updateTexture(e,t={}){const n=this.get(e);if(!0===n.initialized&&n.version===e.version)return;const r=e.isRenderTargetTexture||e.isDepthTexture||e.isFramebufferTexture,i=this.backend;if(r&&!0===n.initialized&&(i.destroySampler(e),i.destroyTexture(e)),e.isFramebufferTexture){const t=this.renderer.getRenderTarget();e.type=t?t.texture.type:ne}const{width:s,height:a,depth:o}=this.getSize(e);if(t.width=s,t.height=a,t.depth=o,t.needsMipmaps=this.needsMipmaps(e),t.levels=t.needsMipmaps?this.getMipLevels(e,s,a):1,r||!0===e.isStorageTexture)i.createSampler(e),i.createTexture(e,t),n.generation=e.version;else{if(!0!==n.initialized&&i.createSampler(e),e.version>0){const r=e.image;if(void 0===r)console.warn("THREE.Renderer: Texture marked for update but image is undefined.");else if(!1===r.complete)console.warn("THREE.Renderer: Texture marked for update but image is incomplete.");else{if(e.images){const n=[];for(const t of e.images)n.push(t);t.images=n}else t.image=r;void 0!==n.isDefaultTexture&&!0!==n.isDefaultTexture||(i.createTexture(e,t),n.isDefaultTexture=!1,n.generation=e.version),!0===e.source.dataReady&&i.updateTexture(e,t),t.needsMipmaps&&0===e.mipmaps.length&&i.generateMipmaps(e)}}else i.createDefaultTexture(e),n.isDefaultTexture=!0,n.generation=e.version}if(!0!==n.initialized){n.initialized=!0,n.generation=e.version,this.info.memory.textures++;const t=()=>{e.removeEventListener("dispose",t),this._destroyTexture(e)};e.addEventListener("dispose",t)}n.version=e.version}getSize(e,t=fw){let n=e.images?e.images[0]:e.image;return n?(void 0!==n.image&&(n=n.image),t.width=n.width||1,t.height=n.height||1,t.depth=e.isCubeTexture?6:n.depth||1):t.width=t.height=t.depth=1,t}getMipLevels(e,t,n){let r;return r=e.isCompressedTexture?e.mipmaps?e.mipmaps.length:1:Math.floor(Math.log2(Math.max(t,n)))+1,r}needsMipmaps(e){return!0===e.isCompressedTexture||e.generateMipmaps}_destroyTexture(e){!0===this.has(e)&&(this.backend.destroySampler(e),this.backend.destroyTexture(e),this.delete(e),this.info.memory.textures--)}}class gw extends Nr{constructor(e,t,n,r=1){super(e,t,n),this.a=r}set(e,t,n,r=1){return this.a=r,super.set(e,t,n)}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 _w extends Am{static get type(){return"ParameterNode"}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getHash(){return this.uuid}generate(){return this.name}}class vw extends uf{static get type(){return"StackNode"}constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this._expressionNode=null,this.isStackNode=!0}getNodeType(e){return this.outputNode?this.outputNode.getNodeType(e):"void"}getMemberType(e,t){return this.outputNode?this.outputNode.getMemberType(e,t):"void"}add(e){return this.nodes.push(e),this}If(e,t){const n=new Yf(t);return this._currentCond=j_(e,n),this.add(this._currentCond)}ElseIf(e,t){const n=new Yf(t),r=j_(e,n);return this._currentCond.elseNode=r,this._currentCond=r,this}Else(e){return this._currentCond.elseNode=new Yf(e),this}Switch(e){return this._expressionNode=Kf(e),this}Case(...e){const t=[];if(!(e.length>=2))throw new Error("TSL: Invalid parameter length. Case() requires at least two parameters.");for(let n=0;n<e.length-1;n++)t.push(this._expressionNode.equal(Kf(e[n])));const n=new Yf(e[e.length-1]);let r=t[0];for(let e=1;e<t.length;e++)r=r.or(t[e]);const i=j_(r,n);return null===this._currentCond?(this._currentCond=i,this.add(this._currentCond)):(this._currentCond.elseNode=i,this._currentCond=i,this)}Default(e){return this.Else(e),this}build(e,...t){const n=e.currentStack,r=im();rm(this),e.currentStack=this;const i=e.buildStage;for(const t of this.nodes)if("setup"===i)t.build(e);else if("analyze"===i)t.build(e,this);else if("generate"===i){const n=e.getDataFromNode(t,"any").stages,r=n&&n[e.shaderStage];if(t.isVarNode&&r&&1===r.length&&r[0]&&r[0].isStackNode)continue;t.build(e,"void")}const s=this.outputNode?this.outputNode.build(e,...t):super.build(e,...t);return rm(r),e.currentStack=n,s}}const yw=Jf(vw).setParameterLength(0,1);new Gi,new Ut,new Ut,new Ut,new Bn,new Ut(0,0,-1),new an,new Ut,new Ut,new an,new Dt;const xw=new on;Rb.flipX(),xw.depthTexture=new os(1,1);const bw=new na(-1,1,1,-1,0,1);class Tw extends ei{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new Xr([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new Xr(t,2))}}const Sw=new Tw;class Mw extends di{constructor(e=null){super(Sw,e),this.camera=bw,this.isQuadMesh=!0}async renderAsync(e){return e.renderAsync(this,bw)}render(e){e.render(this,bw)}}const ww=new $n,Ew=new Bn;class Aw extends uf{static get type(){return"SceneNode"}constructor(e=Aw.BACKGROUND_BLURRINESS,t=null){super(),this.scope=e,this.scene=t}setup(e){const t=this.scope,n=null!==this.scene?this.scene:e.scene;let r;return t===Aw.BACKGROUND_BLURRINESS?r=zy("backgroundBlurriness","float",n):t===Aw.BACKGROUND_INTENSITY?r=zy("backgroundIntensity","float",n):t===Aw.BACKGROUND_ROTATION?r=cg("mat4").label("backgroundRotation").setGroup(og).onRenderUpdate(()=>{const e=n.background;return null!==e&&e.isTexture&&300!==e.mapping?(ww.copy(n.backgroundRotation),ww.x*=-1,ww.y*=-1,ww.z*=-1,Ew.makeRotationFromEuler(ww)):Ew.identity(),Ew}):console.error("THREE.SceneNode: Unknown scope:",t),r}}Aw.BACKGROUND_BLURRINESS="backgroundBlurriness",Aw.BACKGROUND_INTENSITY="backgroundIntensity",Aw.BACKGROUND_ROTATION="backgroundRotation";const Rw=em(Aw,Aw.BACKGROUND_BLURRINESS),Cw=em(Aw,Aw.BACKGROUND_INTENSITY),Nw=em(Aw,Aw.BACKGROUND_ROTATION),Pw=nm(({texture:e,uv:t})=>{const n=1e-4,r=gm().toVar();return sm(t.x.lessThan(n),()=>{r.assign(gm(1,0,0))}).ElseIf(t.y.lessThan(n),()=>{r.assign(gm(0,1,0))}).ElseIf(t.z.lessThan(n),()=>{r.assign(gm(0,0,1))}).ElseIf(t.x.greaterThan(.9999),()=>{r.assign(gm(-1,0,0))}).ElseIf(t.y.greaterThan(.9999),()=>{r.assign(gm(0,-1,0))}).ElseIf(t.z.greaterThan(.9999),()=>{r.assign(gm(0,0,-1))}).Else(()=>{const n=.01,i=e.sample(t.add(gm(-.01,0,0))).r.sub(e.sample(t.add(gm(n,0,0))).r),s=e.sample(t.add(gm(0,-.01,0))).r.sub(e.sample(t.add(gm(0,n,0))).r),a=e.sample(t.add(gm(0,0,-.01))).r.sub(e.sample(t.add(gm(0,0,n))).r);r.assign(gm(i,s,a))}),r.normalize()});class Lw extends Dv{static get type(){return"Texture3DNode"}constructor(e,t=null,n=null){super(e,t,n),this.isTexture3DNode=!0}getInputType(){return"texture3D"}getDefaultUV(){return gm(.5,.5,.5)}setUpdateMatrix(){}setupUV(e,t){const n=this.value;return!e.isFlipY()||!0!==n.isRenderTargetTexture&&!0!==n.isFramebufferTexture||(t=this.sampler?t.flipY():t.setY(um(Cv(this,this.levelNode).y).sub(t.y).sub(1))),t}generateUV(e,t){return t.build(e,"vec3")}normal(e){return Pw({texture:this,uv:e})}}const Dw=Jf(Lw).setParameterLength(1,3),Iw=new Dt;class Uw extends Dv{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.setUpdateMatrix(!1)}setup(e){return e.object.isQuadMesh&&this.passNode.build(e),super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class Ow extends Uw{static get type(){return"PassMultipleTextureNode"}constructor(e,t,n=!1){super(e,null),this.textureName=t,this.previousTexture=n}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}}class Fw extends df{static get type(){return"PassNode"}constructor(e,t,n,r={}){super("vec4"),this.scope=e,this.scene=t,this.camera=n,this.options=r,this._pixelRatio=1,this._width=1,this._height=1;const i=new os;i.isRenderTargetTexture=!0,i.name="depth";const s=new on(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:ue,...r});s.texture.name="output",s.depthTexture=i,this.renderTarget=s,this._textures={output:s.texture,depth:i},this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=cg(0),this._cameraFar=cg(0),this._mrt=null,this._layers=null,this._resolution=1,this.isPassNode=!0,this.updateBeforeType=Qp,this.global=!0}setResolution(e){return this._resolution=e,this}getResolution(){return this._resolution}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 n=this._textures[e],r=this.renderTarget.textures.indexOf(n);this.renderTarget.textures[r]=t,this._textures[e]=t,this._previousTextures[e]=n,this._textureNodes[e].updateTexture(),this._previousTextureNodes[e].updateTexture()}}getTextureNode(e="output"){let t=this._textureNodes[e];return void 0===t&&(t=Kf(new Ow(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=Kf(new Ow(this,e,!0)),t.updateTexture(),this._previousTextureNodes[e]=t),t}getViewZNode(e="depth"){let t=this._viewZNodes[e];if(void 0===t){const n=this._cameraNear,r=this._cameraFar;this._viewZNodes[e]=t=Vb(this.getTextureNode(e),n,r)}return t}getLinearDepthNode(e="depth"){let t=this._linearDepthNodes[e];if(void 0===t){const n=this._cameraNear,r=this._cameraFar,i=this.getViewZNode(e);this._linearDepthNodes[e]=t=kb(i,n,r)}return t}setup({renderer:e}){return this.renderTarget.samples=void 0===this.options.samples?e.samples:this.options.samples,this.renderTarget.texture.type=e.getColorBufferType(),this.scope===Fw.COLOR?this.getTextureNode():this.getLinearDepthNode()}updateBefore(e){const{renderer:t}=e,{scene:n}=this;let r,i;const s=t.getOutputRenderTarget();s&&!0===s.isXRRenderTarget?(i=1,r=t.xr.getCamera(),t.xr.updateCamera(r),Iw.set(s.width,s.height)):(r=this.camera,i=t.getPixelRatio(),t.getSize(Iw)),this._pixelRatio=i,this.setSize(Iw.width,Iw.height);const a=t.getRenderTarget(),o=t.getMRT(),l=r.layers.mask;this._cameraNear.value=r.near,this._cameraFar.value=r.far,null!==this._layers&&(r.layers.mask=this._layers.mask);for(const e in this._previousTextures)this.toggleTexture(e);t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.render(n,r),t.setRenderTarget(a),t.setMRT(o),r.layers.mask=l}setSize(e,t){this._width=e,this._height=t;const n=this._width*this._pixelRatio*this._resolution,r=this._height*this._pixelRatio*this._resolution;this.renderTarget.setSize(n,r)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}Fw.COLOR="color",Fw.DEPTH="depth";const Bw=nm(([e,t])=>e.mul(t).clamp()).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),kw=nm(([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"}]}),zw=nm(([e,t])=>{const n=(e=(e=e.mul(t)).sub(.004).max(0)).mul(e.mul(6.2).add(.5)),r=e.mul(e.mul(6.2).add(1.7)).add(.06);return n.div(r).pow(2.2)}).setLayout({name:"cineonToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),Vw=nm(([e])=>{const t=e.mul(e.add(.0245786)).sub(90537e-9),n=e.mul(e.add(.432951).mul(.983729)).add(.238081);return t.div(n)}),Gw=nm(([e,t])=>{const n=wm(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),r=wm(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=n.mul(e),e=Vw(e),(e=r.mul(e)).clamp()}).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),Hw=wm(gm(1.6605,-.1246,-.0182),gm(-.5876,1.1329,-.1006),gm(-.0728,-.0083,1.1187)),jw=wm(gm(.6274,.0691,.0164),gm(.3293,.9195,.088),gm(.0433,.0113,.8956)),Ww=nm(([e])=>{const t=gm(e).toVar(),n=gm(t.mul(t)).toVar(),r=gm(n.mul(n)).toVar();return lm(15.5).mul(r.mul(n)).sub(vg(40.14,r.mul(t))).add(vg(31.96,r).sub(vg(6.868,n.mul(t))).add(vg(.4298,n).add(vg(.1191,t).sub(.00232))))}),Xw=nm(([e,t])=>{const n=gm(e).toVar(),r=wm(gm(.856627153315983,.137318972929847,.11189821299995),gm(.0951212405381588,.761241990602591,.0767994186031903),gm(.0482516061458583,.101439036467562,.811302368396859)),i=wm(gm(1.1271005818144368,-.1413297634984383,-.14132976349843826),gm(-.11060664309660323,1.157823702216272,-.11060664309660294),gm(-.016493938717834573,-.016493938717834257,1.2519364065950405)),s=lm(-12.47393),a=lm(4.026069);return n.mulAssign(t),n.assign(jw.mul(n)),n.assign(r.mul(n)),n.assign(S_(n,1e-10)),n.assign(Qg(n)),n.assign(n.sub(s).div(a.sub(s))),n.assign(F_(n,0,1)),n.assign(Ww(n)),n.assign(i.mul(n)),n.assign(N_(S_(gm(0),n),gm(2.2))),n.assign(Hw.mul(n)),n.assign(F_(n,0,1)),n}).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),qw=nm(([e,t])=>{const n=lm(.76),r=lm(.15);e=e.mul(t);const i=T_(e.r,T_(e.g,e.b)),s=j_(i.lessThan(.08),i.sub(vg(6.25,i.mul(i))),.04);e.subAssign(s);const a=S_(e.r,S_(e.g,e.b));sm(a.lessThan(n),()=>e);const o=_g(1,n),l=_g(1,o.mul(o).div(a.add(o.sub(n))));e.mulAssign(l.div(a));const u=_g(1,yg(1,r.mul(a.sub(l)).add(1)));return O_(e,gm(l),u)}).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class $w extends uf{static get type(){return"CodeNode"}constructor(e="",t=[],n=""){super("code"),this.isCodeNode=!0,this.global=!0,this.code=e,this.includes=t,this.language=n}setIncludes(e){return this.includes=e,this}getIncludes(){return this.includes}generate(e){const t=this.getIncludes(e);for(const n of t)n.build(e);const n=e.getCodeFromNode(this,this.getNodeType(e));return n.code=this.code,n.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 Yw extends $w{static get type(){return"FunctionNode"}constructor(e="",t=[],n=""){super(e,t,n)}getNodeType(e){return this.getNodeFunction(e).type}getInputs(e){return this.getNodeFunction(e).inputs}getNodeFunction(e){const t=e.getDataFromNode(this);let n=t.nodeFunction;return void 0===n&&(n=e.parser.parseFunction(this.code),t.nodeFunction=n),n}generate(e,t){super.generate(e);const n=this.getNodeFunction(e),r=n.name,i=n.type,s=e.getCodeFromNode(this,i);""!==r&&(s.name=r);const a=e.getPropertyName(s),o=this.getNodeFunction(e).getCode(a);return s.code=o+"\n","property"===t?a:e.format(`${a}()`,i,t)}}function Kw(e){let t;const n=e.context.getViewZ;return void 0!==n&&(t=n(this)),(t||cy.z).negate()}const Qw=nm(([e,t],n)=>{const r=Kw(n);return z_(e,t,r)}),Zw=nm(([e],t)=>{const n=Kw(t);return e.mul(e,n,n).negate().exp().oneMinus()}),Jw=nm(([e,t])=>xm(t.toFloat().mix($m.rgb,e.toVec3()),$m.a));Jf(class extends uf{constructor(e){super(),this.scope=e}generate(e){const{scope:t}=this,{renderer:n}=e;!0===n.backend.isWebGLBackend?e.addFlowCode(`\t// ${t}Barrier \n`):e.addLineFlowCode(`${t}Barrier()`,this)}});class eE extends uf{static get type(){return"AtomicFunctionNode"}constructor(e,t,n){super("uint"),this.method=e,this.pointerNode=t,this.valueNode=n,this.parents=!0}getInputType(e){return this.pointerNode.getNodeType(e)}getNodeType(e){return this.getInputType(e)}generate(e){const t=e.getNodeProperties(this),n=t.parents,r=this.method,i=this.getNodeType(e),s=this.getInputType(e),a=this.pointerNode,o=this.valueNode,l=[];l.push(`&${a.build(e,s)}`),null!==o&&l.push(o.build(e,s));const u=`${e.getMethod(r,i)}( ${l.join(", ")} )`;if(!(1===n.length&&!0===n[0].isStackNode))return void 0===t.constNode&&(t.constNode=Tv(u,i).toConst()),t.constNode.build(e);e.addLineFlowCode(u,this)}}let tE;function nE(e){tE=tE||new WeakMap;let t=tE.get(e);return void 0===t&&tE.set(e,t={}),t}function rE(e){const t=nE(e);return t.shadowMatrix||(t.shadowMatrix=cg("mat4").setGroup(og).onRenderUpdate(t=>(!0===e.castShadow&&!1!==t.renderer.shadowMap.enabled||e.shadow.updateMatrices(e),e.shadow.matrix)))}function iE(e){const t=nE(e);return t.position||(t.position=cg(new Ut).setGroup(og).onRenderUpdate((t,n)=>n.value.setFromMatrixPosition(e.matrixWorld)))}function sE(e){const t=nE(e);return t.viewPosition||(t.viewPosition=cg(new Ut).setGroup(og).onRenderUpdate(({camera:t},n)=>{n.value=n.value||new Ut,n.value.setFromMatrixPosition(e.matrixWorld),n.value.applyMatrix4(t.matrixWorldInverse)}))}eE.ATOMIC_LOAD="atomicLoad",eE.ATOMIC_STORE="atomicStore",eE.ATOMIC_ADD="atomicAdd",eE.ATOMIC_SUB="atomicSub",eE.ATOMIC_MAX="atomicMax",eE.ATOMIC_MIN="atomicMin",eE.ATOMIC_AND="atomicAnd",eE.ATOMIC_OR="atomicOr",eE.ATOMIC_XOR="atomicXor",Jf(eE);const aE=e=>qv.transformDirection(iE(e).sub(function(e){const t=nE(e);return t.targetPosition||(t.targetPosition=cg(new Ut).setGroup(og).onRenderUpdate((t,n)=>n.value.setFromMatrixPosition(e.target.matrixWorld)))}(e))),oE=(e,t)=>{for(const n of t)if(n.isAnalyticLightNode&&n.light.id===e)return n;return null},lE=new WeakMap,uE=[];class cE extends uf{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=Rm("vec3","totalDiffuse"),this.totalSpecularNode=Rm("vec3","totalSpecular"),this.outgoingLightNode=Rm("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 n=e[t];if(uE.push(n.id),uE.push(n.castShadow?1:0),!0===n.isSpotLight){const e=null!==n.map?n.map.id:-1,t=n.colorNode?n.colorNode.getCacheKey():-1;uE.push(e,t)}}const t=zp(uE);return uE.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.getSelf().getHash());this._lightNodesHash="lights-"+t.join(",")}return this._lightNodesHash}analyze(e){const t=e.getNodeProperties(this);for(const n of t.nodes)n.build(e);t.outputNode.build(e)}setupLightsNode(e){const t=[],n=this._lightNodes,r=(e=>e.sort((e,t)=>e.id-t.id))(this._lights),i=e.renderer.library;for(const e of r)if(e.isNode)t.push(Kf(e));else{let r=null;if(null!==n&&(r=oE(e.id,n)),null===r){const n=i.getLightNodeClass(e.constructor);if(null===n){console.warn(`LightsNode.setupNodeLights: Light node not found for ${e.constructor.name}`);continue}let r=null;lE.has(e)?r=lE.get(e):(r=Kf(new n(e)),lE.set(e,r)),t.push(r)}}this._lightNodes=t}setupDirectLight(e,t,n){const{lightingModel:r,reflectedLight:i}=e.context;r.direct({...n,lightNode:t,reflectedLight:i},e)}setupDirectRectAreaLight(e,t,n){const{lightingModel:r,reflectedLight:i}=e.context;r.directRectArea({...n,lightNode:t,reflectedLight:i},e)}setupLights(e,t){for(const n of t)n.build(e)}getLightNodes(e){return null===this._lightNodes&&this.setupLightsNode(e),this._lightNodes}setup(e){const t=e.lightsNode;e.lightsNode=this;let n=this.outgoingLightNode;const r=e.context,i=r.lightingModel,s=e.getNodeProperties(this);if(i){const{totalDiffuseNode:t,totalSpecularNode:a}=this;r.outgoingLight=n;const o=e.addStack();s.nodes=o.nodes,i.start(e);const{backdrop:l,backdropAlpha:u}=r,{directDiffuse:c,directSpecular:h,indirectDiffuse:d,indirectSpecular:p}=r.reflectedLight;let f=c.add(d);null!==l&&(f=gm(null!==u?u.mix(f,l):l),r.material.transparent=!0),t.assign(f),a.assign(h.add(p)),n.assign(t.add(a)),i.finish(e),n=n.bypass(e.removeStack())}else s.nodes=[];return e.lightsNode=t,n}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 hE extends uf{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=Zp,this.isShadowBaseNode=!0}setupShadowPosition({context:e,material:t}){dE.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||ly)}}const dE=Rm("vec3","shadowPositionWorld");function pE(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 Nr),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 fE=new WeakMap,mE=nm(({depthTexture:e,shadowCoord:t,depthLayer:n})=>{let r=Uv(e,t.xy).label("t_basic");return e.isArrayTexture&&(r=r.depth(n)),r.compare(t.z)}),gE=nm(({depthTexture:e,shadowCoord:t,shadow:n,depthLayer:r})=>{const i=(t,n)=>{let i=Uv(e,t);return e.isArrayTexture&&(i=i.depth(r)),i.compare(n)},s=zy("mapSize","vec2",n).setGroup(og),a=zy("radius","float",n).setGroup(og),o=dm(1).div(s),l=o.x.negate().mul(a),u=o.y.negate().mul(a),c=o.x.mul(a),h=o.y.mul(a),d=l.div(2),p=u.div(2),f=c.div(2),m=h.div(2);return gg(i(t.xy.add(dm(l,u)),t.z),i(t.xy.add(dm(0,u)),t.z),i(t.xy.add(dm(c,u)),t.z),i(t.xy.add(dm(d,p)),t.z),i(t.xy.add(dm(0,p)),t.z),i(t.xy.add(dm(f,p)),t.z),i(t.xy.add(dm(l,0)),t.z),i(t.xy.add(dm(d,0)),t.z),i(t.xy,t.z),i(t.xy.add(dm(f,0)),t.z),i(t.xy.add(dm(c,0)),t.z),i(t.xy.add(dm(d,m)),t.z),i(t.xy.add(dm(0,m)),t.z),i(t.xy.add(dm(f,m)),t.z),i(t.xy.add(dm(l,h)),t.z),i(t.xy.add(dm(0,h)),t.z),i(t.xy.add(dm(c,h)),t.z)).mul(1/17)}),_E=nm(({depthTexture:e,shadowCoord:t,shadow:n,depthLayer:r})=>{const i=(t,n)=>{let i=Uv(e,t);return e.isArrayTexture&&(i=i.depth(r)),i.compare(n)},s=zy("mapSize","vec2",n).setGroup(og),a=dm(1).div(s),o=a.x,l=a.y,u=t.xy,c=r_(u.mul(s).add(.5));return u.subAssign(c.mul(a)),gg(i(u,t.z),i(u.add(dm(o,0)),t.z),i(u.add(dm(0,l)),t.z),i(u.add(a),t.z),O_(i(u.add(dm(o.negate(),0)),t.z),i(u.add(dm(o.mul(2),0)),t.z),c.x),O_(i(u.add(dm(o.negate(),l)),t.z),i(u.add(dm(o.mul(2),l)),t.z),c.x),O_(i(u.add(dm(0,l.negate())),t.z),i(u.add(dm(0,l.mul(2))),t.z),c.y),O_(i(u.add(dm(o,l.negate())),t.z),i(u.add(dm(o,l.mul(2))),t.z),c.y),O_(O_(i(u.add(dm(o.negate(),l.negate())),t.z),i(u.add(dm(o.mul(2),l.negate())),t.z),c.x),O_(i(u.add(dm(o.negate(),l.mul(2))),t.z),i(u.add(dm(o.mul(2),l.mul(2))),t.z),c.x),c.y)).mul(1/9)}),vE=nm(({depthTexture:e,shadowCoord:t,depthLayer:n})=>{const r=lm(1).toVar();let i=Uv(e).sample(t.xy);e.isArrayTexture&&(i=i.depth(n)),i=i.rg;const s=M_(t.z,i.x);return sm(s.notEqual(lm(1)),()=>{const e=t.z.sub(i.x),n=S_(0,i.y.mul(i.y));let a=n.div(n.add(e.mul(e)));a=F_(_g(a,.3).div(.95-.3)),r.assign(F_(S_(s,a)))}),r}),yE=nm(([e,t,n])=>{let r=ly.sub(e).length();return r=r.sub(t).div(n.sub(t)),r=r.saturate(),r}),xE=e=>{let t=fE.get(e);if(void 0===t){const n=e.isPointLight?(e=>{const t=e.shadow.camera,n=zy("near","float",t).setGroup(og),r=zy("far","float",t).setGroup(og),i=Qv(e);return yE(i,n,r)})(e):null;t=new Qb,t.colorNode=xm(0,0,0,1),t.depthNode=n,t.isShadowPassMaterial=!0,t.name="ShadowMaterial",t.fog=!1,fE.set(e,t)}return t},bE=new LM,TE=[],SE=nm(({samples:e,radius:t,size:n,shadowPass:r,depthLayer:i})=>{const s=lm(0).toVar("meanVertical"),a=lm(0).toVar("squareMeanVertical"),o=e.lessThanEqual(lm(1)).select(lm(0),lm(2).div(e.sub(1))),l=e.lessThanEqual(lm(1)).select(lm(0),lm(-1));fb({start:um(0),end:um(e),type:"int",condition:"<"},({i:e})=>{const u=l.add(lm(e).mul(o));let c=r.sample(gg(Nb.xy,dm(0,u).mul(t)).div(n));r.value.isArrayTexture&&(c=c.depth(i)),c=c.x,s.addAssign(c),a.addAssign(c.mul(c))}),s.divAssign(e),a.divAssign(e);const u=Zg(a.sub(s.mul(s)));return dm(s,u)}),ME=nm(({samples:e,radius:t,size:n,shadowPass:r,depthLayer:i})=>{const s=lm(0).toVar("meanHorizontal"),a=lm(0).toVar("squareMeanHorizontal"),o=e.lessThanEqual(lm(1)).select(lm(0),lm(2).div(e.sub(1))),l=e.lessThanEqual(lm(1)).select(lm(0),lm(-1));fb({start:um(0),end:um(e),type:"int",condition:"<"},({i:e})=>{const u=l.add(lm(e).mul(o));let c=r.sample(gg(Nb.xy,dm(u,0).mul(t)).div(n));r.value.isArrayTexture&&(c=c.depth(i)),s.addAssign(c.x),a.addAssign(gg(c.y.mul(c.y),c.x.mul(c.x)))}),s.divAssign(e),a.divAssign(e);const u=Zg(a.sub(s.mul(s)));return dm(s,u)}),wE=[mE,gE,_E,vE];let EE;const AE=new Mw;class RE extends hE{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._cameraFrameId=new WeakMap,this.isShadowNode=!0,this.depthLayer=0}setupShadowFilter(e,{filterFn:t,depthTexture:n,shadowCoord:r,shadow:i,depthLayer:s}){const a=r.x.greaterThanEqual(0).and(r.x.lessThanEqual(1)).and(r.y.greaterThanEqual(0)).and(r.y.lessThanEqual(1)).and(r.z.lessThanEqual(1)),o=t({depthTexture:n,shadowCoord:r,shadow:i,depthLayer:s});return a.select(o,lm(1))}setupShadowCoord(e,t){const{shadow:n}=this,{renderer:r}=e,i=zy("bias","float",n).setGroup(og);let s,a=t;if(n.camera.isOrthographicCamera||!0!==r.logarithmicDepthBuffer)a=a.xyz.div(a.w),s=a.z,r.coordinateSystem===xt&&(s=s.mul(2).sub(1));else{const e=a.w;a=a.xy.div(e);const t=zy("near","float",n.camera).setGroup(og),r=zy("far","float",n.camera).setGroup(og);s=Gb(e.negate(),t,r)}return a=gm(a.x,a.y.oneMinus(),s.add(i)),a}getShadowFilterFn(e){return wE[e]}setupRenderTarget(e,t){const n=new os(e.mapSize.width,e.mapSize.height);n.name="ShadowDepthTexture",n.compareFunction=ut;const r=t.createRenderTarget(e.mapSize.width,e.mapSize.height);return r.texture.name="ShadowMap",r.texture.type=e.mapType,r.depthTexture=n,{shadowMap:r,depthTexture:n}}setupShadow(e){const{renderer:t}=e,{light:n,shadow:r}=this,i=t.shadowMap.type,{depthTexture:s,shadowMap:a}=this.setupRenderTarget(r,e);if(r.camera.updateProjectionMatrix(),3===i&&!0!==r.isPointLightShadow){s.compareFunction=null,a.depth>1?(a._vsmShadowMapVertical||(a._vsmShadowMapVertical=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:be,type:ue,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:be,type:ue,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:be,type:ue,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:be,type:ue,depthBuffer:!1}));let t=Uv(s);s.isArrayTexture&&(t=t.depth(this.depthLayer));let n=Uv(this.vsmShadowMapVertical.texture);s.isArrayTexture&&(n=n.depth(this.depthLayer));const i=zy("blurSamples","float",r).setGroup(og),o=zy("radius","float",r).setGroup(og),l=zy("mapSize","vec2",r).setGroup(og);let u=this.vsmMaterialVertical||(this.vsmMaterialVertical=new Qb);u.fragmentNode=SE({samples:i,radius:o,size:l,shadowPass:t,depthLayer:this.depthLayer}).context(e.getSharedContext()),u.name="VSMVertical",u=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new Qb),u.fragmentNode=ME({samples:i,radius:o,size:l,shadowPass:n,depthLayer:this.depthLayer}).context(e.getSharedContext()),u.name="VSMHorizontal"}const o=zy("intensity","float",r).setGroup(og),l=zy("normalBias","float",r).setGroup(og),u=rE(n).mul(dE.add(by.mul(l))),c=this.setupShadowCoord(e,u),h=r.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(null===h)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const d=3===i&&!0!==r.isPointLightShadow?this.vsmShadowMapHorizontal.texture:s,p=this.setupShadowFilter(e,{filterFn:h,shadowTexture:a.texture,depthTexture:d,shadowCoord:c,shadow:r,depthLayer:this.depthLayer});let f=Uv(a.texture,c);s.isArrayTexture&&(f=f.depth(this.depthLayer));const m=O_(1,p.rgb.mix(f,1),o.mul(f.a)).toVar();return this.shadowMap=a,this.shadow.map=a,m}setup(e){if(!1!==e.renderer.shadowMap.enabled)return nm(()=>{let t=this._node;return this.setupShadowPosition(e),null===t&&(this._node=t=this.setupShadow(e)),e.material.shadowNode&&console.warn('THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.'),e.material.receivedShadowNode&&(t=e.material.receivedShadowNode(t)),t})()}renderShadow(e){const{shadow:t,shadowMap:n,light:r}=this,{renderer:i,scene:s}=e;t.updateMatrices(r),n.setSize(t.mapSize.width,t.mapSize.height,n.depth),i.render(s,t.camera)}updateShadow(e){const{shadowMap:t,light:n,shadow:r}=this,{renderer:i,scene:s,camera:a}=e,o=i.shadowMap.type,l=t.depthTexture.version;this._depthVersionCached=l;const u=r.camera.layers.mask;4294967294&r.camera.layers.mask||(r.camera.layers.mask=a.layers.mask);const c=i.getRenderObjectFunction(),h=i.getMRT(),d=!!h&&h.has("velocity");EE=function(e,t,n){return n=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,n=pE(e,n)),n}(i,s,EE),s.overrideMaterial=xE(n),i.setRenderObjectFunction(((e,t,n,r)=>{TE[0]=e,TE[1]=t;let i=bE.get(TE);return void 0!==i&&i.shadowType===n&&i.useVelocity===r||(i=(i,s,a,o,l,u,...c)=>{(!0===i.castShadow||i.receiveShadow&&3===n)&&(r&&($p(i).useVelocity=!0),i.onBeforeShadow(e,i,a,t.camera,o,s.overrideMaterial,u),e.renderObject(i,s,a,o,l,u,...c),i.onAfterShadow(e,i,a,t.camera,o,s.overrideMaterial,u))},i.shadowType=n,i.useVelocity=r,bE.set(TE,i)),TE[0]=null,TE[1]=null,i})(i,r,o,d)),i.setClearColor(0,0),i.setRenderTarget(t),this.renderShadow(e),i.setRenderObjectFunction(c),3===o&&!0!==r.isPointLightShadow&&this.vsmPass(i),r.camera.layers.mask=u,function(e,t,n){!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,n),function(e,t){e.background=t.background,e.backgroundNode=t.backgroundNode,e.overrideMaterial=t.overrideMaterial}(t,n)}(i,s,EE)}vsmPass(e){const{shadow:t}=this,n=this.shadowMap.depth;this.vsmShadowMapVertical.setSize(t.mapSize.width,t.mapSize.height,n),this.vsmShadowMapHorizontal.setSize(t.mapSize.width,t.mapSize.height,n),e.setRenderTarget(this.vsmShadowMapVertical),AE.material=this.vsmMaterialVertical,AE.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),AE.material=this.vsmMaterialHorizontal,AE.render(e)}dispose(){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),super.dispose()}updateBefore(e){const{shadow:t}=this;let n=t.needsUpdate||t.autoUpdate;n&&(this._cameraFrameId[e.camera]===e.frameId&&(n=!1),this._cameraFrameId[e.camera]=e.frameId),n&&(this.updateShadow(e),this.shadowMap.depthTexture.version===this._depthVersionCached&&(t.needsUpdate=!1))}}const CE=new Nr,NE=nm(([e,t])=>{const n=e.toVar(),r=c_(n),i=yg(1,S_(r.x,S_(r.y,r.z)));r.mulAssign(i),n.mulAssign(i.mul(t.mul(2).oneMinus()));const s=dm(n.xy).toVar(),a=t.mul(1.5).oneMinus();return sm(r.z.greaterThanEqual(a),()=>{sm(n.z.greaterThan(0),()=>{s.x.assign(_g(4,n.x))})}).ElseIf(r.x.greaterThanEqual(a),()=>{const e=h_(n.x);s.x.assign(n.z.mul(e).add(e.mul(2)))}).ElseIf(r.y.greaterThanEqual(a),()=>{const e=h_(n.y);s.x.assign(n.x.add(e.mul(2)).add(2)),s.y.assign(n.z.mul(e).sub(2))}),dm(.125,.25).mul(s).add(dm(.375,.75)).flipY()}).setLayout({name:"cubeToUV",type:"vec2",inputs:[{name:"pos",type:"vec3"},{name:"texelSizeY",type:"float"}]}),PE=nm(({depthTexture:e,bd3D:t,dp:n,texelSize:r})=>Uv(e,NE(t,r.y)).compare(n)),LE=nm(({depthTexture:e,bd3D:t,dp:n,texelSize:r,shadow:i})=>{const s=zy("radius","float",i).setGroup(og),a=dm(-1,1).mul(s).mul(r.y);return Uv(e,NE(t.add(a.xyy),r.y)).compare(n).add(Uv(e,NE(t.add(a.yyy),r.y)).compare(n)).add(Uv(e,NE(t.add(a.xyx),r.y)).compare(n)).add(Uv(e,NE(t.add(a.yyx),r.y)).compare(n)).add(Uv(e,NE(t,r.y)).compare(n)).add(Uv(e,NE(t.add(a.xxy),r.y)).compare(n)).add(Uv(e,NE(t.add(a.yxy),r.y)).compare(n)).add(Uv(e,NE(t.add(a.xxx),r.y)).compare(n)).add(Uv(e,NE(t.add(a.yxx),r.y)).compare(n)).mul(1/9)}),DE=nm(({filterFn:e,depthTexture:t,shadowCoord:n,shadow:r})=>{const i=n.xyz.toVar(),s=i.length(),a=cg("float").setGroup(og).onRenderUpdate(()=>r.camera.near),o=cg("float").setGroup(og).onRenderUpdate(()=>r.camera.far),l=zy("bias","float",r).setGroup(og),u=cg(r.mapSize).setGroup(og),c=lm(1).toVar();return sm(s.sub(o).lessThanEqual(0).and(s.sub(a).greaterThanEqual(0)),()=>{const n=s.sub(a).div(o.sub(a)).toVar();n.addAssign(l);const h=i.normalize(),d=dm(1).div(u.mul(dm(4,2)));c.assign(e({depthTexture:t,bd3D:h,dp:n,texelSize:d,shadow:r}))}),c}),IE=new an,UE=new Dt,OE=new Dt;class FE extends RE{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return 0===e?PE:LE}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,shadowTexture:n,depthTexture:r,shadowCoord:i,shadow:s}){return DE({filterFn:t,shadowTexture:n,depthTexture:r,shadowCoord:i,shadow:s})}renderShadow(e){const{shadow:t,shadowMap:n,light:r}=this,{renderer:i,scene:s}=e,a=t.getFrameExtents();OE.copy(t.mapSize),OE.multiply(a),n.setSize(OE.width,OE.height),UE.copy(t.mapSize);const o=i.autoClear,l=i.getClearColor(CE),u=i.getClearAlpha();i.autoClear=!1,i.setClearColor(t.clearColor,t.clearAlpha),i.clear();const c=t.getViewportCount();for(let e=0;e<c;e++){const a=t.getViewport(e),o=UE.x*a.x,l=OE.y-UE.y-UE.y*a.y;IE.set(o,l,UE.x*a.z,UE.y*a.w),n.viewport.copy(IE),t.updateMatrices(r,e),i.render(s,t.camera)}i.autoClear=o,i.setClearColor(l,u)}}class BE extends xb{static get type(){return"AnalyticLightNode"}constructor(e=null){super(),this.light=e,this.color=new Nr,this.colorNode=e&&e.colorNode||cg(this.color).setGroup(og),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=Qp}getHash(){return this.light.uuid}getLightVector(e){return sE(this.light).sub(e.context.positionView||cy)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return((e,t)=>Kf(new RE(e,t)))(this.light)}setupShadow(e){const{renderer:t}=e;if(!1===t.shadowMap.enabled)return;let n=this.shadowColorNode;if(null===n){const e=this.light.shadow.shadowNode;let t;t=void 0!==e?Kf(e):this.setupShadowNode(),this.shadowNode=t,this.shadowColorNode=n=this.colorNode.mul(t),this.baseColorNode=this.colorNode}this.colorNode=n}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),n=this.setupDirectRectArea(e);t&&e.lightsNode.setupDirectLight(e,this,t),n&&e.lightsNode.setupDirectRectAreaLight(e,this,n)}update(){const{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}}const kE=nm(({lightDistance:e,cutoffDistance:t,decayExponent:n})=>{const r=e.pow(n).max(.01).reciprocal();return t.greaterThan(0).select(r.mul(e.div(t).pow4().oneMinus().clamp().pow2()),r)});class zE extends BE{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=cg(0).setGroup(og),this.decayExponentNode=cg(2).setGroup(og)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return((e,t)=>Kf(new FE(e,t)))(this.light)}setupDirect(e){return(({color:e,lightVector:t,cutoffDistance:n,decayExponent:r})=>{const i=t.normalize(),s=t.length(),a=kE({lightDistance:s,cutoffDistance:n,decayExponent:r});return{lightDirection:i,lightColor:e.mul(a)}})({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}}nm(([e=Av()],{renderer:t,material:n})=>{const r=U_(e.mul(2).sub(1));let i;if(n.alphaToCoverage&&t.samples>1){const e=lm(r.fwidth()).toVar();i=z_(e.oneMinus(),e.add(1),r).oneMinus()}else i=j_(r.greaterThan(1),0,1);return i});const VE=nm(([e,t])=>{const n=e.x,r=e.y,i=e.z;let s=t.element(0).mul(.886227);return s=s.add(t.element(1).mul(1.023328).mul(r)),s=s.add(t.element(2).mul(1.023328).mul(i)),s=s.add(t.element(3).mul(1.023328).mul(n)),s=s.add(t.element(4).mul(.858086).mul(n).mul(r)),s=s.add(t.element(5).mul(.858086).mul(r).mul(i)),s=s.add(t.element(6).mul(i.mul(i).mul(.743125).sub(.247708))),s=s.add(t.element(7).mul(.858086).mul(n).mul(i)),s=s.add(t.element(8).mul(.429043).mul(vg(n,n).sub(vg(r,r)))),s}),GE=new gw;class HE extends FM{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,n){const r=this.renderer,i=this.nodes.getBackgroundNode(e)||e.background;let s=!1;if(null===i)r._clearColor.getRGB(GE),GE.a=r._clearColor.a;else if(!0===i.isColor)i.getRGB(GE),GE.a=1,s=!0;else if(!0===i.isNode){const o=this.get(e),l=i;GE.copy(r._clearColor);let u=o.backgroundMesh;if(void 0===u){const h=X_(xm(l).mul(Cw),{getUV:()=>Nw.mul(yy),getTextureLevel:()=>Rw});let d=tb;d=d.setZ(d.w);const p=new Qb;function f(){i.removeEventListener("dispose",f),u.material.dispose(),u.geometry.dispose()}p.name="Background.material",p.side=1,p.depthTest=!1,p.depthWrite=!1,p.allowOverride=!1,p.fog=!1,p.lights=!1,p.vertexNode=d,p.colorNode=h,o.backgroundMeshNode=h,o.backgroundMesh=u=new di(new Ms(1,32,32),p),u.frustumCulled=!1,u.name="Background.mesh",u.onBeforeRender=function(e,t,n){this.matrixWorld.copyPosition(n.matrixWorld)},i.addEventListener("dispose",f)}const c=l.getCacheKey();o.backgroundCacheKey!==c&&(o.backgroundMeshNode.node=xm(l).mul(Cw),o.backgroundMeshNode.needsUpdate=!0,u.material.needsUpdate=!0,o.backgroundCacheKey=c),t.unshift(u,u.geometry,u.material,0,0,null,null)}else console.error("THREE.Renderer: Unsupported background configuration.",i);const a=r.xr.getEnvironmentBlendMode();if("additive"===a?GE.set(0,0,0,1):"alpha-blend"===a&&GE.set(0,0,0,0),!0===r.autoClear||!0===s){const m=n.clearColorValue;m.r=GE.r,m.g=GE.g,m.b=GE.b,m.a=GE.a,!0!==r.backend.isWebGLBackend&&!0!==r.alpha||(m.r*=m.a,m.g*=m.a,m.b*=m.a),n.depthClearValue=r._clearDepth,n.stencilClearValue=r._clearStencil,n.clearColor=!0===r.autoClearColor,n.clearDepth=!0===r.autoClearDepth,n.clearStencil=!0===r.autoClearStencil}else n.clearColor=!1,n.clearDepth=!1,n.clearStencil=!1}}let jE=0;class WE{constructor(e="",t=[],n=0,r=[]){this.name=e,this.bindings=t,this.index=n,this.bindingsReference=r,this.id=jE++}}class XE{constructor(e,t,n,r,i,s,a,o,l,u=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=n,this.transforms=u,this.nodeAttributes=r,this.bindings=i,this.updateNodes=s,this.updateBeforeNodes=a,this.updateAfterNodes=o,this.observer=l,this.usedTimes=0}createBindings(){const e=[];for(const t of this.bindings){if(!0!==t.bindings[0].groupNode.shared){const n=new WE(t.name,[],t.index,t);e.push(n);for(const e of t.bindings)n.bindings.push(e.clone())}else e.push(t)}return e}}class qE{constructor(e,t,n=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=n}}class $E{constructor(e,t,n){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=n.getSelf()}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 YE{constructor(e,t,n=!1,r=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=n,this.count=r}}class KE extends YE{constructor(e,t,n=null,r=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=n,this.interpolationSampling=r}}class QE{constructor(e,t,n=""){this.name=e,this.type=t,this.code=n,Object.defineProperty(this,"isNodeCode",{value:!0})}}let ZE=0;class JE{constructor(e=null){this.id=ZE++,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 eA{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class tA{constructor(e,t){this.name=e,this.value=t,this.boundary=0,this.itemSize=0,this.offset=0}setValue(e){this.value=e}getValue(){return this.value}}class nA extends tA{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class rA extends tA{constructor(e,t=new Dt){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class iA extends tA{constructor(e,t=new Ut){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class sA extends tA{constructor(e,t=new an){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class aA extends tA{constructor(e,t=new Nr){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class oA extends tA{constructor(e,t=new _a){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}}class lA extends tA{constructor(e,t=new Bt){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class uA extends tA{constructor(e,t=new Bn){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class cA extends nA{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class hA extends rA{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class dA extends iA{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class pA extends sA{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class fA extends aA{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class mA extends oA{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class gA extends lA{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class _A extends uA{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}const vA=new WeakMap,yA=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),xA=e=>/e/g.test(e)?String(e).replace(/\+/g,""):(e=Number(e))+(e%1?"":".0");class bA{constructor(e,t,n){this.object=e,this.material=e&&e.material||null,this.geometry=e&&e.geometry||null,this.renderer=t,this.parser=n,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.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=yw(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new JE,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null,this.subBuildLayers=[],this.currentStack=null,this.subBuildFn=null}getBindGroupsCache(){let e=vA.get(this.renderer);return void 0===e&&(e=new LM,vA.set(this.renderer,e)),e}createRenderTarget(e,t,n){return new on(e,t,n)}createCubeRenderTarget(e,t){return new sT(e,t)}includes(e){return this.nodes.includes(e)}getOutputStructName(){}_getBindGroup(e,t){const n=this.getBindGroupsCache(),r=[];let i,s=!0;for(const e of t)r.push(e),s=s&&!0!==e.groupNode.shared;return s?(i=n.get(r),void 0===i&&(i=new WE(e,r,this.bindingsIndexes[e].group,r),n.set(r,i))):i=new WE(e,r,this.bindingsIndexes[e].group,r),i}getBindGroupArray(e,t){const n=this.bindings[t];let r=n[e];return void 0===r&&(void 0===this.bindingsIndexes[e]&&(this.bindingsIndexes[e]={binding:0,group:Object.keys(this.bindingsIndexes).length}),n[e]=r=[]),r}getBindings(){let e=this.bindGroups;if(null===e){const t={},n=this.bindings;for(const e of sf)for(const r in n[e]){const i=n[e][r];(t[r]||(t[r]=[])).push(...i)}e=[];for(const n in t){const r=t[n],i=this._getBindGroup(n,r);e.push(i)}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 n=e[t];this.bindingsIndexes[n.name].group=t,n.index=t}}setHashNode(e,t){this.hashNodes[t]=e}addNode(e){!1===this.nodes.includes(e)&&(this.nodes.push(e),this.setHashNode(e,e.getHash(this)))}addSequentialNode(e){!1===this.sequentialNodes.includes(e)&&this.sequentialNodes.push(e)}buildUpdateNodes(){for(const e of this.nodes){e.getUpdateType()!==Kp&&this.updateNodes.push(e.getSelf())}for(const e of this.sequentialNodes){const t=e.getUpdateBeforeType(),n=e.getUpdateAfterType();t!==Kp&&this.updateBeforeNodes.push(e.getSelf()),n!==Kp&&this.updateAfterNodes.push(e.getSelf())}}get currentNode(){return this.chaining[this.chaining.length-1]}isFilteredTexture(e){return e.magFilter===J||e.magFilter===ee||e.magFilter===Z||e.magFilter===te||e.minFilter===J||e.minFilter===ee||e.minFilter===Z||e.minFilter===te}addChain(e){this.chaining.push(e)}removeChain(e){if(this.chaining.pop()!==e)throw new Error("NodeBuilder: Invalid node chaining!")}getMethod(e){return e}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}getSharedContext(){return this.context,this.context}setCache(e){this.cache=e}getCache(){return this.cache}getCacheFromNode(e,t=!0){const n=this.getDataFromNode(e);return void 0===n.cache&&(n.cache=new JE(t?this.getCache():null)),n.cache}isAvailable(){return!1}getVertexIndex(){console.warn("Abstract function.")}getInstanceIndex(){console.warn("Abstract function.")}getDrawIndex(){console.warn("Abstract function.")}getFrontFacing(){console.warn("Abstract function.")}getFragCoord(){console.warn("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(){console.warn("Abstract function.")}generateTextureLod(){console.warn("Abstract function.")}generateArrayDeclaration(e,t){return this.getType(e)+"[ "+t+" ]"}generateArray(e,t,n=null){let r=this.generateArrayDeclaration(e,t)+"( ";for(let i=0;i<t;i++){const s=n?n[i]:null;r+=null!==s?s.build(this,e):this.generateConst(e),i<t-1&&(r+=", ")}return r+=" )",r}generateStruct(e,t,n=null){const r=[];for(const e of t){const{name:t,type:i}=e;n&&n[t]&&n[t].isNode?r.push(n[t].build(this,i)):r.push(this.generateConst(i))}return e+"( "+r.join(", ")+" )"}generateConst(e,t=null){if(null===t&&("float"===e||"int"===e||"uint"===e?t=0:"bool"===e?t=!1:"color"===e?t=new Nr:"vec2"===e?t=new Dt:"vec3"===e?t=new Ut:"vec4"===e&&(t=new an)),"float"===e)return xA(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")}( ${xA(t.r)}, ${xA(t.g)}, ${xA(t.b)} )`;const n=this.getTypeLength(e),r=this.getComponentType(e),i=e=>this.generateConst(r,e);if(2===n)return`${this.getType(e)}( ${i(t.x)}, ${i(t.y)} )`;if(3===n)return`${this.getType(e)}( ${i(t.x)}, ${i(t.y)}, ${i(t.z)} )`;if(4===n&&"mat2"!==e)return`${this.getType(e)}( ${i(t.x)}, ${i(t.y)}, ${i(t.z)}, ${i(t.w)} )`;if(n>=4&&t&&(t.isMatrix2||t.isMatrix3||t.isMatrix4))return`${this.getType(e)}( ${t.elements.map(i).join(", ")} )`;if(n>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 n=this.attributes;for(const t of n)if(t.name===e)return t;const r=new qE(e,t);return this.registerDeclaration(r),n.push(r),r}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===ae)return"int";if(t===oe)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 n=function(e){return jp.get(e)}(e);const r="float"===t?"":t[0];return!0===/mat2/.test(t)&&(n=n.replace("vec","mat")),r+n}getTypeFromArray(e){return yA.get(e.constructor)}isInteger(e){return/int|uint|(i|u)vec/.test(e)}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);const n=t.array,r=e.itemSize,i=e.normalized;let s;return e instanceof Wr||!0===i||(s=this.getTypeFromArray(n)),this.getTypeFromLength(r,s)}getTypeLength(e){const t=this.getVectorType(e),n=/vec([2-4])/.exec(t);return null!==n?Number(n[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")}addStack(){return this.stack=yw(this.stack),this.stacks.push(im()||this.stack),rm(this.stack),this.stack}removeStack(){const e=this.stack;return this.stack=e.parent,rm(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,n=null){let r=(n=null===n?e.isGlobal(this)?this.globalCache:this.cache:n).getData(e);void 0===r&&(r={},n.setData(e,r)),void 0===r[t]&&(r[t]={});let i=r[t];const s=r.any?r.any.subBuilds:null,a=this.getClosestSubBuild(s);return a&&(void 0===i.subBuildsCache&&(i.subBuildsCache={}),i=i.subBuildsCache[a]||(i.subBuildsCache[a]={}),i.subBuilds=s),i}getNodeProperties(e,t="any"){const n=this.getDataFromNode(e,t);return n.properties||(n.properties={outputNode:null})}getBufferAttributeFromNode(e,t){const n=this.getDataFromNode(e);let r=n.bufferAttribute;if(void 0===r){const i=this.uniforms.index++;r=new qE("nodeAttribute"+i,t,e),this.bufferAttributes.push(r),n.bufferAttribute=r}return r}getStructTypeFromNode(e,t,n=null,r=this.shaderStage){const i=this.getDataFromNode(e,r,this.globalCache);let s=i.structType;if(void 0===s){const e=this.structs.index++;null===n&&(n="StructType"+e),s=new eA(n,t),this.structs[r].push(s),i.structType=s}return s}getOutputStructTypeFromNode(e,t){const n=this.getStructTypeFromNode(e,t,"OutputType","fragment");return n.output=!0,n}getUniformFromNode(e,t,n=this.shaderStage,r=null){const i=this.getDataFromNode(e,n,this.globalCache);let s=i.uniform;if(void 0===s){const a=this.uniforms.index++;s=new $E(r||"nodeUniform"+a,t,e),this.uniforms[n].push(s),this.registerDeclaration(s),i.uniform=s}return s}getArrayCount(e){let t=null;return e.isArrayNode?t=e.count:e.isVarNode&&e.node.isArrayNode&&(t=e.node.count),t}getVarFromNode(e,t=null,n=e.getNodeType(this),r=this.shaderStage,i=!1){const s=this.getDataFromNode(e,r),a=this.getSubBuildProperty("variable",s.subBuilds);let o=s[a];if(void 0===o){const l=i?"_const":"_var",u=this.vars[r]||(this.vars[r]=[]),c=this.vars[l]||(this.vars[l]=0);null===t&&(t=(i?"nodeConst":"nodeVar")+c,this.vars[l]++),"variable"!==a&&(t=this.getSubBuildProperty(t,s.subBuilds));const h=this.getArrayCount(e);o=new YE(t,n,i,h),i||u.push(o),this.registerDeclaration(o),s[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,n=e.getNodeType(this),r=null,i=null){const s=this.getDataFromNode(e,"any"),a=this.getSubBuildProperty("varying",s.subBuilds);let o=s[a];if(void 0===o){const e=this.varyings,l=e.length;null===t&&(t="nodeVarying"+l),"varying"!==a&&(t=this.getSubBuildProperty(t,s.subBuilds)),o=new KE(t,n,r,i),e.push(o),this.registerDeclaration(o),s[a]=o}return o}registerDeclaration(e){const t=this.shaderStage,n=this.declarations[t]||(this.declarations[t]={}),r=this.getPropertyName(e);let i=1,s=r;for(;void 0!==n[s];)s=r+"_"+i++;i>1&&(e.name=s,console.warn(`THREE.TSL: Declaration name '${r}' of '${e.type}' already in use. Renamed to '${s}'.`)),n[s]=e}getCodeFromNode(e,t,n=this.shaderStage){const r=this.getDataFromNode(e);let i=r.code;if(void 0===i){const e=this.codes[n]||(this.codes[n]=[]),s=e.length;i=new QE("nodeCode"+s,t),e.push(i),r.code=i}return i}addFlowCodeHierarchy(e,t){const{flowCodes:n,flowCodeBlock:r}=this.getDataFromNode(e);let i=!0,s=t;for(;s;){if(!0===r.get(s)){i=!1;break}s=this.getDataFromNode(s).parentNodeBlock}if(i)for(const e of n)this.addLineFlowCode(e)}addLineFlowCodeBlock(e,t,n){const r=this.getDataFromNode(e),i=r.flowCodes||(r.flowCodes=[]),s=r.flowCodeBlock||(r.flowCodeBlock=new WeakMap);i.push(t),s.set(n,!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),n=this.flowChildNode(e,t);return this.flowsData.set(e,n),n}addInclude(e){null!==this.currentFunctionNode&&this.currentFunctionNode.includes.push(e)}buildFunctionNode(e){const t=new Yw,n=this.currentFunctionNode;return this.currentFunctionNode=t,t.code=this.buildFunctionCode(e),this.currentFunctionNode=n,t}flowShaderNode(e){const t=e.layout,n={[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)n[e.name]=new _w(e.type,e.name);e.layout=null;const r=e.call(n),i=this.flowStagesNode(r,t.type);return e.layout=t,i}flowStagesNode(e,t=null){const n=this.flow,r=this.vars,i=this.declarations,s=this.cache,a=this.buildStage,o=this.stack,l={code:""};this.flow=l,this.vars={},this.declarations={},this.cache=new JE,this.stack=yw();for(const n of rf)this.setBuildStage(n),l.result=e.build(this,t);return l.vars=this.getVars(this.shaderStage),this.flow=n,this.vars=r,this.declarations=i,this.cache=s,this.stack=o,this.setBuildStage(a),l}getFunctionOperator(){return null}buildFunctionCode(){console.warn("Abstract function.")}flowChildNode(e,t=null){const n=this.flow,r={code:""};return this.flow=r,r.result=e.build(this,t),this.flow=n,r}flowNodeFromShaderStage(e,t,n=null,r=null){const i=this.tab,s=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 u=null;if("generate"===this.buildStage){const i=this.flowChildNode(t,n);null!==r&&(i.code+=`${this.tab+r} = ${i.result};\n`),this.flowCode[e]=this.flowCode[e]+i.code,u=i}else u=t.build(this);return this.setShaderStage(a),this.cache=s,this.tab=i,this.context=o,u}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){console.warn("Abstract function.")}getVaryings(){console.warn("Abstract function.")}getVar(e,t,n=null){return`${null!==n?this.generateArrayDeclaration(e,n):this.getType(e)} ${t}`}getVars(e){let t="";const n=this.vars[e];if(void 0!==n)for(const e of n)t+=`${this.getVar(e.type,e.name)}; `;return t}getUniforms(){console.warn("Abstract function.")}getCodes(e){const t=this.codes[e];let n="";if(void 0!==t)for(const e of t)n+=e.code+"\n";return n}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(){console.warn("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 n=this.subBuildLayers;for(let e=t.length-1;e>=0;e--){const r=t[e];if(n.includes(r))return r}return null}getSubBuildOutput(e){return this.getSubBuildProperty("outputNode",e)}getSubBuildProperty(e="",t=null){let n,r;return n=null!==t?this.getClosestSubBuild(t):this.subBuildFn,r=n?e?n+"_"+e:n:e,r}build(){const{object:e,material:t,renderer:n}=this;if(null!==t){let e=n.library.fromMaterial(t);null===e&&(console.error(`NodeMaterial: Material "${t.type}" is not compatible.`),e=new Qb),e.build(this)}else this.addFlow("compute",e);for(const e of rf){this.setBuildStage(e),this.context.vertex&&this.context.vertex.isNode&&this.flowNodeFromShaderStage("vertex",this.context.vertex);for(const t of sf){this.setShaderStage(t);const n=this.flowNodes[t];for(const t of n)"generate"===e?this.flowNode(t):t.build(this)}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}getNodeUniform(e,t){if("float"===t||"int"===t||"uint"===t)return new cA(e);if("vec2"===t||"ivec2"===t||"uvec2"===t)return new hA(e);if("vec3"===t||"ivec3"===t||"uvec3"===t)return new dA(e);if("vec4"===t||"ivec4"===t||"uvec4"===t)return new pA(e);if("color"===t)return new fA(e);if("mat2"===t)return new mA(e);if("mat3"===t)return new gA(e);if("mat4"===t)return new _A(e);throw new Error(`Uniform "${t}" not declared.`)}format(e,t,n){if((t=this.getVectorType(t))===(n=this.getVectorType(n))||null===n||this.isReference(n))return e;const r=this.getTypeLength(t),i=this.getTypeLength(n);return 16===r&&9===i?`${this.getType(n)}( ${e}[ 0 ].xyz, ${e}[ 1 ].xyz, ${e}[ 2 ].xyz )`:9===r&&4===i?`${this.getType(n)}( ${e}[ 0 ].xy, ${e}[ 1 ].xy )`:r>4||i>4||0===i?e:r===i?`${this.getType(n)}( ${e} )`:r>i?(e="bool"===n?`all( ${e} )`:`${e}.${"xyz".slice(0,i)}`,this.format(e,this.getTypeFromLength(i,this.getComponentType(t)),n)):4===i&&r>1?`${this.getType(n)}( ${this.format(e,t,"vec3")}, 1.0 )`:2===r?`${this.getType(n)}( ${this.format(e,t,"vec2")}, 0.0 )`:(1===r&&i>1&&t!==this.getComponentType(n)&&(e=`${this.getType(this.getComponentType(n))}( ${e} )`),`${this.getType(n)}( ${e} )`)}getSignature(){return`// Three.js r${s} - Node System\n`}*[Symbol.iterator](){}}class TA{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 n=e.get(t);return void 0===n&&(n={renderMap:new WeakMap,frameMap:new WeakMap},e.set(t,n)),n}updateBeforeNode(e){const t=e.getUpdateBeforeType(),n=e.updateReference(this);if(t===Qp){const{frameMap:t}=this._getMaps(this.updateBeforeMap,n);t.get(n)!==this.frameId&&!1!==e.updateBefore(this)&&t.set(n,this.frameId)}else if(t===Zp){const{renderMap:t}=this._getMaps(this.updateBeforeMap,n);t.get(n)!==this.renderId&&!1!==e.updateBefore(this)&&t.set(n,this.renderId)}else t===Jp&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),n=e.updateReference(this);if(t===Qp){const{frameMap:t}=this._getMaps(this.updateAfterMap,n);t.get(n)!==this.frameId&&!1!==e.updateAfter(this)&&t.set(n,this.frameId)}else if(t===Zp){const{renderMap:t}=this._getMaps(this.updateAfterMap,n);t.get(n)!==this.renderId&&!1!==e.updateAfter(this)&&t.set(n,this.renderId)}else t===Jp&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),n=e.updateReference(this);if(t===Qp){const{frameMap:t}=this._getMaps(this.updateMap,n);t.get(n)!==this.frameId&&!1!==e.update(this)&&t.set(n,this.frameId)}else if(t===Zp){const{renderMap:t}=this._getMaps(this.updateMap,n);t.get(n)!==this.renderId&&!1!==e.update(this)&&t.set(n,this.renderId)}else t===Jp&&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 SA{constructor(e,t,n=null,r="",i=!1){this.type=e,this.name=t,this.count=n,this.qualifier=r,this.isConst=i}}SA.isNodeFunctionInput=!0;class MA extends BE{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:aE(this.light),lightColor:e}}}const wA=new Bn,EA=new Bn;let AA=null;class RA extends BE{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=cg(new Ut).setGroup(og),this.halfWidth=cg(new Ut).setGroup(og),this.updateType=Zp}update(e){super.update(e);const{light:t}=this,n=e.camera.matrixWorldInverse;EA.identity(),wA.copy(t.matrixWorld),wA.premultiply(n),EA.extractRotation(wA),this.halfWidth.value.set(.5*t.width,0,0),this.halfHeight.value.set(0,.5*t.height,0),this.halfWidth.value.applyMatrix4(EA),this.halfHeight.value.applyMatrix4(EA)}setupDirectRectArea(e){let t,n;e.isAvailable("float32Filterable")?(t=Uv(AA.LTC_FLOAT_1),n=Uv(AA.LTC_FLOAT_2)):(t=Uv(AA.LTC_HALF_1),n=Uv(AA.LTC_HALF_2));const{colorNode:r,light:i}=this;return{lightColor:r,lightPosition:sE(i),halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:n}}static setLTC(e){AA=e}}class CA extends BE{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=cg(0).setGroup(og),this.penumbraCosNode=cg(0).setGroup(og),this.cutoffDistanceNode=cg(0).setGroup(og),this.decayExponentNode=cg(0).setGroup(og),this.colorNode=cg(this.color).setGroup(og)}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:n,penumbraCosNode:r}=this;return z_(n,r,t)}getLightCoord(e){const t=e.getNodeProperties(this);let n=t.projectionUV;return void 0===n&&(n=function(e,t=ly){const n=rE(e).mul(t);return n.xyz.div(n.w)}(this.light,e.context.positionWorld),t.projectionUV=n),n}setupDirect(e){const{colorNode:t,cutoffDistanceNode:n,decayExponentNode:r,light:i}=this,s=this.getLightVector(e),a=s.normalize(),o=a.dot(aE(i)),l=this.getSpotAttenuation(e,o),u=s.length(),c=kE({lightDistance:u,cutoffDistance:n,decayExponent:r});let h,d,p=t.mul(l).mul(c);if(i.colorNode?(d=this.getLightCoord(e),h=i.colorNode(d)):i.map&&(d=this.getLightCoord(e),h=Uv(i.map,d.xy).onRenderUpdate(()=>i.map)),h){p=d.mul(2).sub(1).abs().lessThan(1).all().select(p.mul(h),p)}return{lightColor:p,lightDirection:a}}}class NA extends CA{static get type(){return"IESSpotLightNode"}getSpotAttenuation(e,t){const n=this.light.iesMap;let r=null;if(n&&!0===n.isTexture){const e=t.acos().mul(1/Math.PI);r=Uv(n,dm(e,0),0).r}else r=super.getSpotAttenuation(t);return r}}const PA=nm(([e,t])=>{const n=e.abs().sub(t);return d_(S_(n,0)).add(T_(S_(n.x,n.y),0))});class LA extends CA{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=this.penumbraCosNode,n=this.getLightCoord(e),r=n.xyz.div(n.w),i=PA(r.xy.sub(dm(.5)),dm(.5)),s=yg(-1,_g(1,l_(t)).sub(1));return B_(i.mul(-2).mul(s))}}class DA extends BE{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class IA extends BE{static get type(){return"HemisphereLightNode"}constructor(e=null){super(e),this.lightPositionNode=iE(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=cg(new Nr).setGroup(og)}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:n,lightDirectionNode:r}=this,i=by.dot(r).mul(.5).add(.5),s=O_(n,t,i);e.context.irradiance.addAssign(s)}}class UA extends BE{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let e=0;e<9;e++)t.push(new Ut);this.lightProbe=Vv(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=VE(by,this.lightProbe);e.context.irradiance.addAssign(t)}}class OA{parseFunction(){console.warn("Abstract function.")}}class FA{constructor(e,t,n="",r=""){this.type=e,this.inputs=t,this.name=n,this.precision=r}getCode(){console.warn("Abstract function.")}}FA.isNodeFunction=!0;const BA=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,kA=/[a-z_0-9]+/gi,zA="#pragma main";class VA extends FA{constructor(e){const{type:t,inputs:n,name:r,precision:i,inputsCode:s,blockCode:a,headerCode:o}=(e=>{const t=(e=e.trim()).indexOf(zA),n=-1!==t?e.slice(t+12):e,r=n.match(BA);if(null!==r&&5===r.length){const i=r[4],s=[];let a=null;for(;null!==(a=kA.exec(i));)s.push(a);const o=[];let l=0;for(;l<s.length;){const e="const"===s[l][0];!0===e&&l++;let t=s[l][0];"in"===t||"out"===t||"inout"===t?l++:t="";const n=s[l++][0];let r=Number.parseInt(s[l][0]);!1===Number.isNaN(r)?l++:r=null;const i=s[l++][0];o.push(new SA(n,i,r,t,e))}const u=n.substring(r[0].length),c=void 0!==r[3]?r[3]:"";return{type:r[2],inputs:o,name:c,precision:void 0!==r[1]?r[1]:"",inputsCode:i,blockCode:u,headerCode:-1!==t?e.slice(0,t):""}}throw new Error("FunctionNode: Function is not a GLSL code.")})(e);super(t,n,r,i),this.inputsCode=s,this.blockCode=a,this.headerCode=o}getCode(e=this.name){let t;const n=this.blockCode;if(""!==n){const{type:r,inputsCode:i,headerCode:s,precision:a}=this;let o=`${r} ${e} ( ${i.trim()} )`;""!==a&&(o=`${a} ${o}`),t=s+o+n}else t="";return t}}class GA extends OA{parseFunction(e){return new VA(e)}}const HA=new WeakMap,jA=[],WA=[];class XA extends FM{constructor(e,t){super(),this.renderer=e,this.backend=t,this.nodeFrame=new TA,this.nodeBuilderCache=new Map,this.callHashCache=new LM,this.groupsData=new LM,this.cacheLib={}}updateGroup(e){const t=e.groupNode,n=t.name;if(n===lg.name)return!0;if(n===og.name){const t=this.get(e),n=this.nodeFrame.renderId;return t.renderId!==n&&(t.renderId=n,!0)}if(n===ag.name){const t=this.get(e),n=this.nodeFrame.frameId;return t.frameId!==n&&(t.frameId=n,!0)}jA[0]=t,jA[1]=e;let r=this.groupsData.get(jA);return void 0===r&&this.groupsData.set(jA,r={}),jA.length=0,r.version!==t.version&&(r.version=t.version,!0)}getForRenderCacheKey(e){return e.initialCacheKey}getForRender(e){const t=this.get(e);let n=t.nodeBuilderState;if(void 0===n){const{nodeBuilderCache:r}=this,i=this.getForRenderCacheKey(e);if(n=r.get(i),void 0===n){const t=this.backend.createNodeBuilder(e.object,this.renderer);t.scene=e.scene,t.material=e.material,t.camera=e.camera,t.context.material=e.material,t.lightsNode=e.lightsNode,t.environmentNode=this.getEnvironmentNode(e.scene),t.fogNode=this.getFogNode(e.scene),t.clippingContext=e.clippingContext,this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview&&t.enableMultiview(),t.build(),n=this._createNodeBuilderState(t),r.set(i,n)}n.usedTimes++,t.nodeBuilderState=n}return n}delete(e){if(e.isRenderObject){const t=this.get(e).nodeBuilderState;t.usedTimes--,0===t.usedTimes&&this.nodeBuilderCache.delete(this.getForRenderCacheKey(e))}return super.delete(e)}getForCompute(e){const t=this.get(e);let n=t.nodeBuilderState;if(void 0===n){const r=this.backend.createNodeBuilder(e,this.renderer);r.build(),n=this._createNodeBuilderState(r),t.nodeBuilderState=n}return n}_createNodeBuilderState(e){return new XE(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 n=this.get(e);n.environmentNode&&(t=n.environmentNode)}return t}getBackgroundNode(e){this.updateBackground(e);let t=null;if(e.backgroundNode&&e.backgroundNode.isNode)t=e.backgroundNode;else{const n=this.get(e);n.backgroundNode&&(t=n.backgroundNode)}return t}getFogNode(e){return this.updateFog(e),e.fogNode||this.get(e).fogNode||null}getCacheKey(e,t){jA[0]=e,jA[1]=t;const n=this.renderer.info.calls,r=this.callHashCache.get(jA)||{};if(r.callId!==n){const i=this.getEnvironmentNode(e),s=this.getFogNode(e);t&&WA.push(t.getCacheKey(!0)),i&&WA.push(i.getCacheKey()),s&&WA.push(s.getCacheKey()),WA.push(this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview?1:0),WA.push(this.renderer.shadowMap.enabled?1:0),r.callId=n,r.cacheKey=zp(WA),this.callHashCache.set(jA,r),WA.length=0}return jA.length=0,r.cacheKey}get isToneMappingState(){return!this.renderer.getRenderTarget()}updateBackground(e){const t=this.get(e),n=e.background;if(n){const r=0===e.backgroundBlurriness&&t.backgroundBlurriness>0||e.backgroundBlurriness>0&&0===t.backgroundBlurriness;if(t.background!==n||r){const i=this.getCacheNode("background",n,()=>{if(!0===n.isCubeTexture||n.mapping===j||n.mapping===W||n.mapping===X){if(e.backgroundBlurriness>0||n.mapping===X)return aM(n);{let e;return e=!0===n.isCubeTexture?Fy(n):Uv(n),cT(e)}}if(!0===n.isTexture)return Uv(n,Rb.flipY()).setUpdateMatrix(!0);!0!==n.isColor&&console.error("WebGPUNodes: Unsupported background configuration.",n)},r);t.backgroundNode=i,t.background=n,t.backgroundBlurriness=e.backgroundBlurriness}}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}getCacheNode(e,t,n,r=!1){const i=this.cacheLib[e]||(this.cacheLib[e]=new WeakMap);let s=i.get(t);return(void 0===s||r)&&(s=n(),i.set(t,s)),s}updateFog(e){const t=this.get(e),n=e.fog;if(n){if(t.fog!==n){const e=this.getCacheNode("fog",n,()=>{if(n.isFogExp2){const e=zy("color","color",n).setGroup(og),t=zy("density","float",n).setGroup(og);return Jw(e,Zw(t))}if(n.isFog){const e=zy("color","color",n).setGroup(og),t=zy("near","float",n).setGroup(og),r=zy("far","float",n).setGroup(og);return Jw(e,Qw(t,r))}console.error("THREE.Renderer: Unsupported fog configuration.",n)});t.fogNode=e,t.fog=n}}else delete t.fogNode,delete t.fog}updateEnvironment(e){const t=this.get(e),n=e.environment;if(n){if(t.environment!==n){const e=this.getCacheNode("environment",n,()=>!0===n.isCubeTexture?Fy(n):!0===n.isTexture?Uv(n):void console.error("Nodes: Unsupported environment configuration.",n));t.environmentNode=e,t.environment=n}}else t.environmentNode&&(delete t.environmentNode,delete t.environment)}getNodeFrame(e=this.renderer,t=null,n=null,r=null,i=null){const s=this.nodeFrame;return s.renderer=e,s.scene=t,s.object=n,s.camera=r,s.material=i,s}getNodeFrameForRender(e){return this.getNodeFrame(e.renderer,e.scene,e.object,e.camera,e.material)}getOutputCacheKey(){const e=this.renderer;return e.toneMapping+","+e.currentColorSpace+","+e.xr.isPresenting}hasOutputChange(e){return HA.get(e)!==this.getOutputCacheKey()}getOutputNode(e){const t=this.renderer,n=this.getOutputCacheKey(),r=e.isArrayTexture?Dw(e,gm(Rb,Gv("gl_ViewID_OVR"))).renderOutput(t.toneMapping,t.currentColorSpace):Uv(e,Rb).renderOutput(t.toneMapping,t.currentColorSpace);return HA.set(e,n),r}updateBefore(e){const t=e.getNodeBuilderState();for(const n of t.updateBeforeNodes)this.getNodeFrameForRender(e).updateBeforeNode(n)}updateAfter(e){const t=e.getNodeBuilderState();for(const n of t.updateAfterNodes)this.getNodeFrameForRender(e).updateAfterNode(n)}updateForCompute(e){const t=this.getNodeFrame(),n=this.getForCompute(e);for(const e of n.updateNodes)t.updateNode(e)}updateForRender(e){const t=this.getNodeFrameForRender(e),n=e.getNodeBuilderState();for(const e of n.updateNodes)t.updateNode(e)}needsRefresh(e){const t=this.getNodeFrameForRender(e);return e.getMonitor().needsRefresh(e,t)}dispose(){super.dispose(),this.nodeFrame=new TA,this.nodeBuilderCache=new Map,this.cacheLib={}}}const qA=new Gi;class $A{constructor(e=null){this.version=0,this.clipIntersection=null,this.cacheKey="",this.shadowPass=!1,this.viewNormalMatrix=new Bt,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,n){const r=e.length;for(let i=0;i<r;i++){qA.copy(e[i]).applyMatrix4(this.viewMatrix,this.viewNormalMatrix);const r=t[n+i],s=qA.normal;r.x=-s.x,r.y=-s.y,r.z=-s.z,r.w=qA.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 n=!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 r=t.clippingPlanes,i=r.length;let s,a;if(this.clipIntersection?(s=this.intersectionPlanes,a=e.intersectionPlanes.length):(s=this.unionPlanes,a=e.unionPlanes.length),s.length!==a+i){s.length=a+i;for(let e=0;e<i;e++)s[a+e]=new an;n=!0}this.projectPlanes(r,s,a),n&&(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 $A(this),this.clippingGroupContexts.set(e,t)),t.update(this,e),t}get unionClippingCount(){return this.unionPlanes.length}}class YA{constructor(e,t){this.bundleGroup=e,this.camera=t}}const KA=[];class QA{constructor(){this.bundles=new LM}get(e,t){const n=this.bundles;KA[0]=e,KA[1]=t;let r=n.get(KA);return void 0===r&&(r=new YA(e,t),n.set(KA,r)),KA.length=0,r}dispose(){this.bundles=new LM}}class ZA{constructor(){this.lightNodes=new WeakMap,this.materialNodes=new Map,this.toneMappingNodes=new Map}fromMaterial(e){if(e.isNodeMaterial)return e;let t=null;const n=this.getMaterialNodeClass(e.type);if(null!==n){t=new n;for(const n in e)t[n]=e[n]}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,n){if(n.has(t))console.warn(`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.`);n.set(t,e)}}addClass(e,t,n){if(n.has(t))console.warn(`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.`);n.set(t,e)}}}const JA=new cE,eR=[];class tR extends LM{constructor(){super()}createNode(e=[]){return(new cE).setLights(e)}getNode(e,t){if(e.isQuadMesh)return JA;eR[0]=e,eR[1]=t;let n=this.get(eR);return void 0===n&&(n=this.createNode(),this.set(eR,n)),eR.length=0,n}}class nR extends on{constructor(e=1,t=1,n={}){super(e,t,n),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 rR=new Ut,iR=new Ut;class sR extends bt{constructor(e,t=!1){super(),this.enabled=!1,this.isPresenting=!1,this.cameraAutoUpdate=!0,this._renderer=e,this._cameraL=new Mi,this._cameraL.viewport=new an,this._cameraR=new Mi,this._cameraR.viewport=new an,this._cameras=[this._cameraL,this._cameraR],this._cameraXR=new ua,this._currentDepthNear=null,this._currentDepthFar=null,this._controllers=[],this._controllerInputSources=[],this._xrRenderTarget=null,this._layers=[],this._supportsLayers=!1,this._frameBufferTargets=null,this._createXRLayer=cR.bind(this),this._gl=null,this._currentAnimationContext=null,this._currentAnimationLoop=null,this._currentPixelRatio=null,this._currentSize=new Dt,this._onSessionEvent=oR.bind(this),this._onSessionEnd=lR.bind(this),this._onInputSourcesChange=uR.bind(this),this._onAnimationFrame=hR.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._useLayers="undefined"!=typeof XRWebGLBinding&&"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&&console.warn("THREE.XRManager: Cannot change framebuffer scale while presenting.")}getReferenceSpaceType(){return this._referenceSpaceType}setReferenceSpaceType(e){this._referenceSpaceType=e,!0===this.isPresenting&&console.warn("THREE.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}getFrame(){return this._xrFrame}useMultiview(){return this._useMultiview}createQuadLayer(e,t,n,r,i,s,a,o={}){const l=new Ss(e,t),u=new nR(i,s,{format:ge,type:ne,depthTexture:new os(i,s,o.stencil?de:oe,void 0,void 0,void 0,void 0,void 0,void 0,o.stencil?ve:_e),stencilBuffer:o.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});u._autoAllocateDepthBuffer=!0;const c=new Ir({color:16777215,side:0});c.map=u.texture,c.map.offset.y=1,c.map.repeat.y=-1;const h=new di(l,c);h.position.copy(n),h.quaternion.copy(r);const d={type:"quad",width:e,height:t,translation:n,quaternion:r,pixelwidth:i,pixelheight:s,plane:h,material:c,rendercall:a,renderTarget:u};if(this._layers.push(d),null!==this._session){d.plane.material=new Ir({color:16777215,side:0}),d.plane.material.blending=5,d.plane.material.blendEquation=g,d.plane.material.blendSrc=y,d.plane.material.blendDst=y,d.xrlayer=this._createXRLayer(d);const e=this._session.renderState.layers;e.unshift(d.xrlayer),this._session.updateRenderState({layers:e})}else u.isXRRenderTarget=!1;return h}createCylinderLayer(e,t,n,r,i,s,a,o,l={}){const u=new ls(e,e,e*t/n,64,64,!0,Math.PI-t/2,t),c=new nR(s,a,{format:ge,type:ne,depthTexture:new os(s,a,l.stencil?de:oe,void 0,void 0,void 0,void 0,void 0,void 0,l.stencil?ve:_e),stencilBuffer:l.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});c._autoAllocateDepthBuffer=!0;const h=new Ir({color:16777215,side:1});h.map=c.texture,h.map.offset.y=1,h.map.repeat.y=-1;const d=new di(u,h);d.position.copy(r),d.quaternion.copy(i);const p={type:"cylinder",radius:e,centralAngle:t,aspectratio:n,translation:r,quaternion:i,pixelwidth:s,pixelheight:a,plane:d,material:h,rendercall:o,renderTarget:c};if(this._layers.push(p),null!==this._session){p.plane.material=new Ir({color:16777215,side:1}),p.plane.material.blending=5,p.plane.material.blendEquation=g,p.plane.material.blendSrc=y,p.plane.material.blendDst=y,p.xrlayer=this._createXRLayer(p);const e=this._session.renderState.layers;e.unshift(p.xrlayer),this._session.updateRenderState({layers:e})}else c.isXRRenderTarget=!1;return d}renderLayers(){const e=new Ut,t=new It,n=this._renderer,r=this.isPresenting,i=n.getOutputRenderTarget(),s=n._frameBufferTarget;this.isPresenting=!1;const a=new Dt;n.getSize(a);const o=n._quad;for(const r of this._layers)if(r.renderTarget.isXRRenderTarget=null!==this._session,r.renderTarget._hasExternalTextures=r.renderTarget.isXRRenderTarget,r.renderTarget.isXRRenderTarget&&this._supportsLayers){r.xrlayer.transform=new XRRigidTransform(r.plane.getWorldPosition(e),r.plane.getWorldQuaternion(t));const i=this._glBinding.getSubImage(r.xrlayer,this._xrFrame);n.backend.setXRRenderTargetTextures(r.renderTarget,i.colorTexture,void 0),n._setXRLayerSize(r.renderTarget.width,r.renderTarget.height),n.setOutputRenderTarget(r.renderTarget),n.setRenderTarget(null),n._frameBufferTarget=null,this._frameBufferTargets||(this._frameBufferTargets=new WeakMap);const{frameBufferTarget:s,quad:a}=this._frameBufferTargets.get(r.renderTarget)||{frameBufferTarget:null,quad:null};s?(n._frameBufferTarget=s,n._quad=a):(n._quad=new Mw(new Qb),this._frameBufferTargets.set(r.renderTarget,{frameBufferTarget:n._getFrameBufferTarget(),quad:n._quad})),r.rendercall(),n._frameBufferTarget=null}else n.setRenderTarget(r.renderTarget),r.rendercall();n.setRenderTarget(null),n.setOutputRenderTarget(i),n._frameBufferTarget=s,n._setXRLayerSize(a.x,a.y),n._quad=o,this.isPresenting=r}getSession(){return this._session}async setSession(e){const t=this._renderer,n=t.backend;this._gl=t.getContext();const r=this._gl,i=r.getContextAttributes();if(this._session=e,null!==e){if(!0===n.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 n.makeXRCompatible(),this._currentPixelRatio=t.getPixelRatio(),t.getSize(this._currentSize),this._currentAnimationContext=t._animation.getContext(),this._currentAnimationLoop=t._animation.getAnimationLoop(),t._animation.stop(),!0===this._useLayers){let n=null,s=null,a=null;t.depth&&(a=t.stencil?r.DEPTH24_STENCIL8:r.DEPTH_COMPONENT24,n=t.stencil?ve:_e,s=t.stencil?de:oe);const o={colorFormat:r.RGBA8,depthFormat:a,scaleFactor:this._framebufferScaleFactor,clearOnAccess:!1};this._useMultiviewIfPossible&&t.hasFeature("OVR_multiview2")&&(o.textureType="texture-array",this._useMultiview=!0);const l=new XRWebGLBinding(e,r),u=l.createProjectionLayer(o),c=[u];this._glBinding=l,this._glProjLayer=u,t.setPixelRatio(1),t._setXRLayerSize(u.textureWidth,u.textureHeight);const h=this._useMultiview?2:1,d=new os(u.textureWidth,u.textureHeight,s,void 0,void 0,void 0,void 0,void 0,void 0,n,h);if(this._xrRenderTarget=new nR(u.textureWidth,u.textureHeight,{format:ge,type:ne,colorSpace:t.outputColorSpace,depthTexture:d,stencilBuffer:t.stencil,samples:i.antialias?4:0,resolveDepthBuffer:!1===u.ignoreDepthValues,resolveStencilBuffer:!1===u.ignoreDepthValues,depth:this._useMultiview?2:1,multiview:this._useMultiview}),this._xrRenderTarget._hasExternalTextures=!0,this._xrRenderTarget.depth=this._useMultiview?2:1,this._supportsLayers=e.enabledFeatures.includes("layers"),this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType()),this._supportsLayers)for(const e of this._layers)e.plane.material=new Ir({color:16777215,side:"cylinder"===e.type?1:0}),e.plane.material.blending=5,e.plane.material.blendEquation=g,e.plane.material.blendSrc=y,e.plane.material.blendDst=y,e.xrlayer=this._createXRLayer(e),c.unshift(e.xrlayer);e.updateRenderState({layers:c})}else{const n={antialias:t.samples>0,alpha:!0,depth:t.depth,stencil:t.stencil,framebufferScaleFactor:this.getFramebufferScaleFactor()},i=new XRWebGLLayer(e,r,n);this._glBaseLayer=i,e.updateRenderState({baseLayer:i}),t.setPixelRatio(1),t._setXRLayerSize(i.framebufferWidth,i.framebufferHeight),this._xrRenderTarget=new nR(i.framebufferWidth,i.framebufferHeight,{format:ge,type:ne,colorSpace:t.outputColorSpace,stencilBuffer:t.stencil,resolveDepthBuffer:!1===i.ignoreDepthValues,resolveStencilBuffer:!1===i.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 n=e.near,r=e.far,i=this._cameraXR,s=this._cameraL,a=this._cameraR;i.near=a.near=s.near=n,i.far=a.far=s.far=r,i.isMultiViewCamera=this._useMultiview,this._currentDepthNear===i.near&&this._currentDepthFar===i.far||(t.updateRenderState({depthNear:i.near,depthFar:i.far}),this._currentDepthNear=i.near,this._currentDepthFar=i.far),s.layers.mask=2|e.layers.mask,a.layers.mask=4|e.layers.mask,i.layers.mask=s.layers.mask|a.layers.mask;const o=e.parent,l=i.cameras;aR(i,o);for(let e=0;e<l.length;e++)aR(l[e],o);2===l.length?function(e,t,n){rR.setFromMatrixPosition(t.matrixWorld),iR.setFromMatrixPosition(n.matrixWorld);const r=rR.distanceTo(iR),i=t.projectionMatrix.elements,s=n.projectionMatrix.elements,a=i[14]/(i[10]-1),o=i[14]/(i[10]+1),l=(i[9]+1)/i[5],u=(i[9]-1)/i[5],c=(i[8]-1)/i[0],h=(s[8]+1)/s[0],d=a*c,p=a*h,f=r/(-c+h),m=f*-c;if(t.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.translateX(m),e.translateZ(f),e.matrixWorld.compose(e.position,e.quaternion,e.scale),e.matrixWorldInverse.copy(e.matrixWorld).invert(),-1===i[10])e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse);else{const t=a+f,n=o+f,i=d-m,s=p+(r-m),c=l*o/n*t,h=u*o/n*t;e.projectionMatrix.makePerspective(i,s,c,h,t,n),e.projectionMatrixInverse.copy(e.projectionMatrix).invert()}}(i,s,a):i.projectionMatrix.copy(s.projectionMatrix),function(e,t,n){null===n?e.matrix.copy(t.matrixWorld):(e.matrix.copy(n.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*wt*Math.atan(1/e.projectionMatrix.elements[5]),e.zoom=1)}(e,i,o)}_getController(e){let t=this._controllers[e];return void 0===t&&(t=new Pi,this._controllers[e]=t),t}}function aR(e,t){null===t?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}function oR(e){const t=this._controllerInputSources.indexOf(e.inputSource);if(-1===t)return;const n=this._controllers[t];if(void 0!==n){const t=this.getReferenceSpace();n.update(e.inputSource,e.frame,t),n.dispatchEvent({type:e.type,data:e.inputSource})}}function lR(){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,!0===this._supportsLayers)for(const e of this._layers)e.renderTarget=new nR(e.pixelwidth,e.pixelheight,{format:ge,type:ne,depthTexture:new os(e.pixelwidth,e.pixelheight,e.stencilBuffer?de:oe,void 0,void 0,void 0,void 0,void 0,void 0,e.stencilBuffer?ve:_e),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 uR(e){const t=this._controllers,n=this._controllerInputSources;for(let r=0;r<e.removed.length;r++){const i=e.removed[r],s=n.indexOf(i);s>=0&&(n[s]=null,t[s].disconnect(i))}for(let r=0;r<e.added.length;r++){const i=e.added[r];let s=n.indexOf(i);if(-1===s){for(let e=0;e<t.length;e++){if(e>=n.length){n.push(i),s=e;break}if(null===n[e]){n[e]=i,s=e;break}}if(-1===s)break}const a=t[s];a&&a.connect(i)}}function cR(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 hR(e,t){if(void 0===t)return;const n=this._cameraXR,r=this._renderer,i=r.backend,s=this._glBaseLayer,a=this.getReferenceSpace(),o=t.getViewerPose(a);if(this._xrFrame=t,null!==o){const e=o.views;null!==this._glBaseLayer&&i.setXRTarget(s.framebuffer);let t=!1;e.length!==n.cameras.length&&(n.cameras.length=0,t=!0);for(let r=0;r<e.length;r++){const a=e[r];let o;if(!0===this._useLayers){const e=this._glBinding.getViewSubImage(this._glProjLayer,a);o=e.viewport,0===r&&i.setXRRenderTargetTextures(this._xrRenderTarget,e.colorTexture,this._glProjLayer.ignoreDepthValues&&!this._useMultiview?void 0:e.depthStencilTexture)}else o=s.getViewport(a);let l=this._cameras[r];void 0===l&&(l=new Mi,l.layers.enable(r),l.viewport=new an,this._cameras[r]=l),l.matrix.fromArray(a.transform.matrix),l.matrix.decompose(l.position,l.quaternion,l.scale),l.projectionMatrix.fromArray(a.projectionMatrix),l.projectionMatrixInverse.copy(l.projectionMatrix).invert(),l.viewport.set(o.x,o.y,o.width,o.height),0===r&&(n.matrix.copy(l.matrix),n.matrix.decompose(n.position,n.quaternion,n.scale)),!0===t&&n.cameras.push(l)}r.setOutputRenderTarget(this._xrRenderTarget)}for(let e=0;e<this._controllers.length;e++){const n=this._controllerInputSources[e],r=this._controllers[e];null!==n&&void 0!==r&&r.update(n,t,a)}this._currentAnimationLoop&&this._currentAnimationLoop(e,t),t.detectedPlanes&&this.dispatchEvent({type:"planesdetected",data:t}),this._xrFrame=null}const dR=new Li,pR=new Dt,fR=new an,mR=new Xi,gR=new Yi,_R=new Bn,vR=new an;class yR{constructor(e,t={}){this.isRenderer=!0;const{logarithmicDepthBuffer:n=!1,alpha:r=!0,depth:i=!0,stencil:s=!1,antialias:a=!1,samples:o=0,getFallback:l=null,colorBufferType:u=ue,multiview:c=!1}=t;this.domElement=e.getDomElement(),this.backend=e,this.samples=o||!0===a?4:0,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.alpha=r,this.logarithmicDepthBuffer=n,this.outputColorSpace=rt,this.toneMapping=0,this.toneMappingExposure=1,this.sortObjects=!0,this.depth=i,this.stencil=s,this.info=new qM,this.overrideNodes={modelViewMatrix:null,modelNormalViewMatrix:null},this.library=new ZA,this.lighting=new tR,this._getFallback=l,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new an(0,0,this._width,this._height),this._scissor=new an(0,0,this._width,this._height),this._scissorTest=!1,this._attributes=null,this._geometries=null,this._nodes=null,this._animation=null,this._bindings=null,this._objects=null,this._pipelines=null,this._bundles=null,this._renderLists=null,this._renderContexts=null,this._textures=null,this._background=null,this._quad=new Mw(new Qb),this._quad.material.name="Renderer_output",this._currentRenderContext=null,this._opaqueSort=null,this._transparentSort=null,this._frameBufferTarget=null;const h=!0===this.alpha?0:1;this._clearColor=new gw(0,0,0,h),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._colorBufferType=u,this._initialized=!1,this._initPromise=null,this._compilationPromises=null,this.transparent=!0,this.opaque=!0,this.shadowMap={enabled:!1,type:1},this.xr=new sR(this,c),this.debug={checkShaderErrors:!0,onShaderError:null,getShaderAsync:async(e,t,n)=>{await this.compileAsync(e,t);const r=this._renderLists.get(e,t),i=this._renderContexts.get(e,t,this._renderTarget),s=e.overrideMaterial||n.material,a=this._objects.get(n,s,e,t,r.lightsNode,i,i.clippingContext),{fragmentShader:o,vertexShader:l}=a.getNodeBuilderState();return{fragmentShader:o,vertexShader:l}}}}async init(){if(this._initialized)throw new Error("Renderer: Backend has already been initialized.");return null!==this._initPromise||(this._initPromise=new Promise(async(e,t)=>{let n=this.backend;try{await n.init(this)}catch(e){if(null===this._getFallback)return void t(e);try{this.backend=n=this._getFallback(e),await n.init(this)}catch(e){return void t(e)}}this._nodes=new XA(this,n),this._animation=new PM(this._nodes,this.info),this._attributes=new HM(n),this._background=new HE(this,this._nodes),this._geometries=new XM(this._attributes,this.info),this._textures=new mw(this,n,this.info),this._pipelines=new JM(n,this._nodes),this._bindings=new ew(n,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new OM(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new aw(this.lighting),this._bundles=new QA,this._renderContexts=new pw,this._animation.start(),this._initialized=!0,e(this)})),this._initPromise}get coordinateSystem(){return this.backend.coordinateSystem}async compileAsync(e,t,n=null){if(!0===this._isDeviceLost)return;!1===this._initialized&&await this.init();const r=this._nodes.nodeFrame,i=r.renderId,s=this._currentRenderContext,a=this._currentRenderObjectFunction,o=this._compilationPromises,l=!0===e.isScene?e:dR;null===n&&(n=e);const u=this._renderTarget,c=this._renderContexts.get(n,t,u),h=this._activeMipmapLevel,d=[];this._currentRenderContext=c,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=d,r.renderId++,r.update(),c.depth=this.depth,c.stencil=this.stencil,c.clippingContext||(c.clippingContext=new $A),c.clippingContext.updateGlobal(l,t),l.onBeforeRender(this,e,t,u);const p=this._renderLists.get(e,t);if(p.begin(),this._projectObject(e,t,0,p,c.clippingContext),n!==e&&n.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&p.pushLight(e)}),p.finish(),null!==u){this._textures.updateRenderTarget(u,h);const e=this._textures.get(u);c.textures=e.textures,c.depthTexture=e.depthTexture}else c.textures=null,c.depthTexture=null;this._background.update(l,p,c);const f=p.opaque,m=p.transparent,g=p.transparentDoublePass,_=p.lightsNode;!0===this.opaque&&f.length>0&&this._renderObjects(f,t,l,_),!0===this.transparent&&m.length>0&&this._renderTransparents(m,g,t,l,_),r.renderId=i,this._currentRenderContext=s,this._currentRenderObjectFunction=a,this._compilationPromises=o,this._handleObjectFunction=this._renderObjectDirect,await Promise.all(d)}async renderAsync(e,t){!1===this._initialized&&await this.init(),this._renderScene(e,t)}async waitForGPU(){await this.backend.waitForGPU()}set highPrecision(e){!0===e?(this.overrideNodes.modelViewMatrix=ry,this.overrideNodes.modelNormalViewMatrix=iy):this.highPrecision&&(this.overrideNodes.modelViewMatrix=null,this.overrideNodes.modelNormalViewMatrix=null)}get highPrecision(){return this.overrideNodes.modelViewMatrix===ry&&this.overrideNodes.modelNormalViewMatrix===iy}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getColorBufferType(){return this._colorBufferType}_onDeviceLost(e){let t=`THREE.WebGPURenderer: ${e.api} Device Lost:\n\nMessage: ${e.message}`;e.reason&&(t+=`\nReason: ${e.reason}`),console.error(t),this._isDeviceLost=!0}_renderBundle(e,t,n){const{bundleGroup:r,camera:i,renderList:s}=e,a=this._currentRenderContext,o=this._bundles.get(r,i),l=this.backend.get(o);void 0===l.renderContexts&&(l.renderContexts=new Set);const u=r.version!==l.version,c=!1===l.renderContexts.has(a)||u;if(l.renderContexts.add(a),c){this.backend.beginBundle(a),(void 0===l.renderObjects||u)&&(l.renderObjects=[]),this._currentRenderBundle=o;const{transparentDoublePass:e,transparent:c,opaque:h}=s;!0===this.opaque&&h.length>0&&this._renderObjects(h,i,t,n),!0===this.transparent&&c.length>0&&this._renderTransparents(c,e,i,t,n),this._currentRenderBundle=null,this.backend.finishBundle(a,o),l.version=r.version}else{const{renderObjects:e}=l;for(let t=0,n=e.length;t<n;t++){const n=e[t];this._nodes.needsRefresh(n)&&(this._nodes.updateBefore(n),this._nodes.updateForRender(n),this._bindings.updateForRender(n),this._nodes.updateAfter(n))}}this.backend.addBundle(a,o)}render(e,t){if(!1===this._initialized)return console.warn("THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead."),this.renderAsync(e,t);this._renderScene(e,t)}_getFrameBufferTarget(){const{currentToneMapping:e,currentColorSpace:t}=this;if(!1===(0!==e)&&!1===(t!==it))return null;const{width:n,height:r}=this.getDrawingBufferSize(pR),{depth:i,stencil:s}=this;let a=this._frameBufferTarget;null===a&&(a=new on(n,r,{depthBuffer:i,stencilBuffer:s,type:this._colorBufferType,format:ge,colorSpace:it,generateMipmaps:!1,minFilter:J,magFilter:J,samples:this.samples}),a.isPostProcessingRenderTarget=!0,this._frameBufferTarget=a);const o=this.getOutputRenderTarget();return a.depthBuffer=i,a.stencilBuffer=s,null!==o?a.setSize(o.width,o.height,o.depth):a.setSize(n,r,1),a.viewport.copy(this._viewport),a.scissor.copy(this._scissor),a.viewport.multiplyScalar(this._pixelRatio),a.scissor.multiplyScalar(this._pixelRatio),a.scissorTest=this._scissorTest,a.multiview=null!==o&&o.multiview,a.resolveDepthBuffer=null===o||o.resolveDepthBuffer,a._autoAllocateDepthBuffer=null!==o&&o._autoAllocateDepthBuffer,a}_renderScene(e,t,n=!0){if(!0===this._isDeviceLost)return;const r=n?this._getFrameBufferTarget():null,i=this._nodes.nodeFrame,s=i.renderId,a=this._currentRenderContext,o=this._currentRenderObjectFunction,l=!0===e.isScene?e:dR,u=this._renderTarget||this._outputRenderTarget,c=this._activeCubeFace,h=this._activeMipmapLevel;let d;null!==r?(d=r,this.setRenderTarget(d)):d=u;const p=this._renderContexts.get(e,t,d);this._currentRenderContext=p,this._currentRenderObjectFunction=this._renderObjectFunction||this.renderObject,this.info.calls++,this.info.render.calls++,this.info.render.frameCalls++,i.renderId=this.info.calls;const f=this.coordinateSystem,m=this.xr;if(t.coordinateSystem!==f&&!1===m.isPresenting&&(t.coordinateSystem=f,t.updateProjectionMatrix(),t.isArrayCamera))for(const e of t.cameras)e.coordinateSystem=f,e.updateProjectionMatrix();!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&!0===t.matrixWorldAutoUpdate&&t.updateMatrixWorld(),!0===m.enabled&&!0===m.isPresenting&&(!0===m.cameraAutoUpdate&&m.updateCamera(t),t=m.getCamera());let g=this._viewport,_=this._scissor,v=this._pixelRatio;null!==d&&(g=d.viewport,_=d.scissor,v=1),this.getDrawingBufferSize(pR),fR.set(0,0,pR.width,pR.height);const y=void 0===g.minDepth?0:g.minDepth,x=void 0===g.maxDepth?1:g.maxDepth;p.viewportValue.copy(g).multiplyScalar(v).floor(),p.viewportValue.width>>=h,p.viewportValue.height>>=h,p.viewportValue.minDepth=y,p.viewportValue.maxDepth=x,p.viewport=!1===p.viewportValue.equals(fR),p.scissorValue.copy(_).multiplyScalar(v).floor(),p.scissor=this._scissorTest&&!1===p.scissorValue.equals(fR),p.scissorValue.width>>=h,p.scissorValue.height>>=h,p.clippingContext||(p.clippingContext=new $A),p.clippingContext.updateGlobal(l,t),l.onBeforeRender(this,e,t,d);const b=t.isArrayCamera?gR:mR;t.isArrayCamera||(_R.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),b.setFromProjectionMatrix(_R,f));const T=this._renderLists.get(e,t);if(T.begin(),this._projectObject(e,t,0,T,p.clippingContext),T.finish(),!0===this.sortObjects&&T.sort(this._opaqueSort,this._transparentSort),null!==d){this._textures.updateRenderTarget(d,h);const e=this._textures.get(d);p.textures=e.textures,p.depthTexture=e.depthTexture,p.width=e.width,p.height=e.height,p.renderTarget=d,p.depth=d.depthBuffer,p.stencil=d.stencilBuffer}else p.textures=null,p.depthTexture=null,p.width=this.domElement.width,p.height=this.domElement.height,p.depth=this.depth,p.stencil=this.stencil;p.width>>=h,p.height>>=h,p.activeCubeFace=c,p.activeMipmapLevel=h,p.occlusionQueryCount=T.occlusionQueryCount,this._background.update(l,T,p),p.camera=t,this.backend.beginRender(p);const{bundles:S,lightsNode:M,transparentDoublePass:w,transparent:E,opaque:A}=T;return S.length>0&&this._renderBundles(S,l,M),!0===this.opaque&&A.length>0&&this._renderObjects(A,t,l,M),!0===this.transparent&&E.length>0&&this._renderTransparents(E,w,t,l,M),this.backend.finishRender(p),i.renderId=s,this._currentRenderContext=a,this._currentRenderObjectFunction=o,null!==r&&(this.setRenderTarget(u,c,h),this._renderOutput(d)),l.onAfterRender(this,e,t,d),p}_setXRLayerSize(e,t){this._width=e,this._height=t,this.setViewport(0,0,e,t)}_renderOutput(e){const t=this._quad;this._nodes.hasOutputChange(e.texture)&&(t.material.fragmentNode=this._nodes.getOutputNode(e.texture),t.material.needsUpdate=!0);const n=this.autoClear,r=this.xr.enabled;this.autoClear=!1,this.xr.enabled=!1,this._renderScene(t,t.camera,!1),this.autoClear=n,this.xr.enabled=r}getMaxAnisotropy(){return this.backend.getMaxAnisotropy()}getActiveCubeFace(){return this._activeCubeFace}getActiveMipmapLevel(){return this._activeMipmapLevel}async setAnimationLoop(e){!1===this._initialized&&await this.init(),this._animation.setAnimationLoop(e)}async getArrayBufferAsync(e){return await this.backend.getArrayBufferAsync(e)}getContext(){return this.backend.getContext()}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,n){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this._pixelRatio=n,this.domElement.width=Math.floor(e*n),this.domElement.height=Math.floor(t*n),this.setViewport(0,0,e,t),this._initialized&&this.backend.updateSize())}setSize(e,t,n=!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===n&&(this.domElement.style.width=e+"px",this.domElement.style.height=t+"px"),this.setViewport(0,0,e,t),this._initialized&&this.backend.updateSize())}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}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,n,r){const i=this._scissor;e.isVector4?i.copy(e):i.set(e,t,n,r)}getScissorTest(){return this._scissorTest}setScissorTest(e){this._scissorTest=e,this.backend.setScissorTest(e)}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,n,r,i=0,s=1){const a=this._viewport;e.isVector4?a.copy(e):a.set(e,t,n,r),a.minDepth=i,a.maxDepth=s}getClearColor(e){return e.copy(this._clearColor)}setClearColor(e,t=1){this._clearColor.set(e),this._clearColor.a=t}getClearAlpha(){return this._clearColor.a}setClearAlpha(e){this._clearColor.a=e}getClearDepth(){return this._clearDepth}setClearDepth(e){this._clearDepth=e}getClearStencil(){return this._clearStencil}setClearStencil(e){this._clearStencil=e}isOccluded(e){const t=this._currentRenderContext;return t&&this.backend.isOccluded(t,e)}clear(e=!0,t=!0,n=!0){if(!1===this._initialized)return console.warn("THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead."),this.clearAsync(e,t,n);const r=this._renderTarget||this._getFrameBufferTarget();let i=null;if(null!==r){this._textures.updateRenderTarget(r);const e=this._textures.get(r);i=this._renderContexts.getForClear(r),i.textures=e.textures,i.depthTexture=e.depthTexture,i.width=e.width,i.height=e.height,i.renderTarget=r,i.depth=r.depthBuffer,i.stencil=r.stencilBuffer,i.clearColorValue=this.backend.getClearColor(),i.activeCubeFace=this.getActiveCubeFace(),i.activeMipmapLevel=this.getActiveMipmapLevel()}this.backend.clear(e,t,n,i),null!==r&&null===this._renderTarget&&this._renderOutput(r)}clearColor(){return this.clear(!0,!1,!1)}clearDepth(){return this.clear(!1,!0,!1)}clearStencil(){return this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,n=!0){!1===this._initialized&&await this.init(),this.clear(e,t,n)}async clearColorAsync(){this.clearAsync(!0,!1,!1)}async clearDepthAsync(){this.clearAsync(!1,!0,!1)}async clearStencilAsync(){this.clearAsync(!1,!1,!0)}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:0}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:it}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||null===this._renderTarget}dispose(){this.info.dispose(),this.backend.dispose(),this._animation.dispose(),this._objects.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose(),this._textures.dispose(),null!==this._frameBufferTarget&&this._frameBufferTarget.dispose(),Object.values(this.backend.timestampQueryPool).forEach(e=>{null!==e&&e.dispose()}),this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,n=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=n}getRenderTarget(){return this._renderTarget}setOutputRenderTarget(e){this._outputRenderTarget=e}getOutputRenderTarget(){return this._outputRenderTarget}_resetXRState(){this.backend.setXRTarget(null),this.setOutputRenderTarget(null),this.setRenderTarget(null),this._frameBufferTarget.dispose(),this._frameBufferTarget=null}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}compute(e){if(!0===this._isDeviceLost)return;if(!1===this._initialized)return console.warn("THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead."),this.computeAsync(e);const t=this._nodes.nodeFrame,n=t.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,t.renderId=this.info.calls;const r=this.backend,i=this._pipelines,s=this._bindings,a=this._nodes,o=Array.isArray(e)?e:[e];if(void 0===o[0]||!0!==o[0].isComputeNode)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");r.beginCompute(e);for(const t of o){if(!1===i.has(t)){const e=()=>{t.removeEventListener("dispose",e),i.delete(t),s.delete(t),a.delete(t)};t.addEventListener("dispose",e);const n=t.onInitFunction;null!==n&&n.call(t,{renderer:this})}a.updateForCompute(t),s.updateForCompute(t);const n=s.getForCompute(t),o=i.getForCompute(t,n);r.compute(e,t,n,o)}r.finishCompute(e),t.renderId=n}async computeAsync(e){!1===this._initialized&&await this.init(),this.compute(e)}async hasFeatureAsync(e){return!1===this._initialized&&await this.init(),this.backend.hasFeature(e)}async resolveTimestampsAsync(e="render"){return!1===this._initialized&&await this.init(),this.backend.resolveTimestampsAsync(e)}hasFeature(e){return!1===this._initialized?(console.warn("THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead."),!1):this.backend.hasFeature(e)}hasInitialized(){return this._initialized}async initTextureAsync(e){!1===this._initialized&&await this.init(),this._textures.updateTexture(e)}initTexture(e){!1===this._initialized&&console.warn("THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead."),this._textures.updateTexture(e)}copyFramebufferToTexture(e,t=null){if(null!==t)if(t.isVector2)t=vR.set(t.x,t.y,e.image.width,e.image.height).floor();else{if(!t.isVector4)return void console.error("THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.");t=vR.copy(t).floor()}else t=vR.set(0,0,e.image.width,e.image.height);let n,r=this._currentRenderContext;null!==r?n=r.renderTarget:(n=this._renderTarget||this._getFrameBufferTarget(),null!==n&&(this._textures.updateRenderTarget(n),r=this._textures.get(n))),this._textures.updateTexture(e,{renderTarget:n}),this.backend.copyFramebufferToTexture(e,r,t)}copyTextureToTexture(e,t,n=null,r=null,i=0,s=0){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,n,r,i,s)}async readRenderTargetPixelsAsync(e,t,n,r,i,s=0,a=0){return this.backend.copyTextureToBuffer(e.textures[s],t,n,r,i,a)}_projectObject(e,t,n,r,i){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)n=e.renderOrder,e.isClippingGroup&&e.enabled&&(i=i.getGroupContext(e));else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)r.pushLight(e);else if(e.isSprite){const s=t.isArrayCamera?gR:mR;if(!e.frustumCulled||s.intersectsSprite(e,t)){!0===this.sortObjects&&vR.setFromMatrixPosition(e.matrixWorld).applyMatrix4(_R);const{geometry:t,material:s}=e;s.visible&&r.push(e,t,s,n,vR.z,null,i)}}else if(e.isLineLoop)console.error("THREE.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 s=t.isArrayCamera?gR:mR;if(!e.frustumCulled||s.intersectsObject(e,t)){const{geometry:t,material:s}=e;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),vR.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(_R)),Array.isArray(s)){const a=t.groups;for(let o=0,l=a.length;o<l;o++){const l=a[o],u=s[l.materialIndex];u&&u.visible&&r.push(e,t,u,n,vR.z,l,i)}}else s.visible&&r.push(e,t,s,n,vR.z,null,i)}}if(!0===e.isBundleGroup&&void 0!==this.backend.beginBundle){const n=r;(r=this._renderLists.get(e,t)).begin(),n.pushBundle({bundleGroup:e,camera:t,renderList:r}),r.finish()}const s=e.children;for(let e=0,a=s.length;e<a;e++)this._projectObject(s[e],t,n,r,i)}_renderBundles(e,t,n){for(const r of e)this._renderBundle(r,t,n)}_renderTransparents(e,t,n,r,i){if(t.length>0){for(const{material:e}of t)e.side=1;this._renderObjects(t,n,r,i,"backSide");for(const{material:e}of t)e.side=0;this._renderObjects(e,n,r,i);for(const{material:e}of t)e.side=2}else this._renderObjects(e,n,r,i)}_renderObjects(e,t,n,r,i=null){for(let s=0,a=e.length;s<a;s++){const{object:a,geometry:o,material:l,group:u,clippingContext:c}=e[s];this._currentRenderObjectFunction(a,n,t,o,l,u,r,c,i)}}renderObject(e,t,n,r,i,s,a,o=null,l=null){let u,c,h;if(e.onBeforeRender(this,t,n,r,i,s),!0===i.allowOverride&&null!==t.overrideMaterial){const e=t.overrideMaterial;i.positionNode&&i.positionNode.isNode&&(u=e.positionNode,e.positionNode=i.positionNode),e.alphaTest=i.alphaTest,e.alphaMap=i.alphaMap,e.transparent=i.transparent||i.transmission>0,e.isShadowPassMaterial&&(e.side=null===i.shadowSide?i.side:i.shadowSide,i.depthNode&&i.depthNode.isNode&&(h=e.depthNode,e.depthNode=i.depthNode),i.castShadowNode&&i.castShadowNode.isNode&&(c=e.colorNode,e.colorNode=i.castShadowNode),i.castShadowPositionNode&&i.castShadowPositionNode.isNode&&(u=e.positionNode,e.positionNode=i.castShadowPositionNode)),i=e}!0===i.transparent&&2===i.side&&!1===i.forceSinglePass?(i.side=1,this._handleObjectFunction(e,i,t,n,a,s,o,"backSide"),i.side=0,this._handleObjectFunction(e,i,t,n,a,s,o,l),i.side=2):this._handleObjectFunction(e,i,t,n,a,s,o,l),void 0!==u&&(t.overrideMaterial.positionNode=u),void 0!==h&&(t.overrideMaterial.depthNode=h),void 0!==c&&(t.overrideMaterial.colorNode=c),e.onAfterRender(this,t,n,r,i,s)}_renderObjectDirect(e,t,n,r,i,s,a,o){const l=this._objects.get(e,t,n,r,i,this._currentRenderContext,a,o);l.drawRange=e.geometry.drawRange,l.group=s;const u=this._nodes.needsRefresh(l);if(u&&(this._nodes.updateBefore(l),this._geometries.updateForRender(l),this._nodes.updateForRender(l),this._bindings.updateForRender(l)),this._pipelines.updateForRender(l),null!==this._currentRenderBundle){this.backend.get(this._currentRenderBundle).renderObjects.push(l),l.bundle=this._currentRenderBundle.bundleGroup}this.backend.draw(l,this.info),u&&this._nodes.updateAfter(l)}_createObjectPipeline(e,t,n,r,i,s,a,o){const l=this._objects.get(e,t,n,r,i,this._currentRenderContext,a,o);l.drawRange=e.geometry.drawRange,l.group=s,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)}get compile(){return this.compileAsync}}class xR{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}clone(){return Object.assign(new this.constructor,this)}}class bR extends xR{constructor(e,t=null){super(e),this.isBuffer=!0,this.bytesPerElement=Float32Array.BYTES_PER_ELEMENT,this._buffer=t}get byteLength(){return(e=this._buffer.byteLength)+(GM-e%GM)%GM;var e}get buffer(){return this._buffer}update(){return!0}}class TR extends bR{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let SR=0;class MR extends TR{constructor(e,t){super("UniformBuffer_"+SR++,e?e.value:null),this.nodeUniform=e,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class wR extends TR{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[]}addUniform(e){return this.uniforms.push(e),this}removeUniform(e){const t=this.uniforms.indexOf(e);return-1!==t&&this.uniforms.splice(t,1),this}get values(){return null===this._values&&(this._values=Array.from(this.buffer)),this._values}get buffer(){let e=this._buffer;if(null===e){const t=this.byteLength;e=new Float32Array(new ArrayBuffer(t)),this._buffer=e}return e}get byteLength(){const e=this.bytesPerElement;let t=0;for(let n=0,r=this.uniforms.length;n<r;n++){const r=this.uniforms[n],i=r.boundary,s=r.itemSize*e,a=t%GM,o=a%i,l=a+o;t+=o,0!==l&&GM-l<s&&(t+=GM-l),r.offset=t/e,t+=s}return Math.ceil(t/GM)*GM}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 console.error("THREE.WebGPUUniformsGroup: Unsupported uniform type.",e)}updateNumber(e){let t=!1;const n=this.values,r=e.getValue(),i=e.offset,s=e.getType();if(n[i]!==r){this._getBufferForType(s)[i]=n[i]=r,t=!0}return t}updateVector2(e){let t=!1;const n=this.values,r=e.getValue(),i=e.offset,s=e.getType();if(n[i+0]!==r.x||n[i+1]!==r.y){const e=this._getBufferForType(s);e[i+0]=n[i+0]=r.x,e[i+1]=n[i+1]=r.y,t=!0}return t}updateVector3(e){let t=!1;const n=this.values,r=e.getValue(),i=e.offset,s=e.getType();if(n[i+0]!==r.x||n[i+1]!==r.y||n[i+2]!==r.z){const e=this._getBufferForType(s);e[i+0]=n[i+0]=r.x,e[i+1]=n[i+1]=r.y,e[i+2]=n[i+2]=r.z,t=!0}return t}updateVector4(e){let t=!1;const n=this.values,r=e.getValue(),i=e.offset,s=e.getType();if(n[i+0]!==r.x||n[i+1]!==r.y||n[i+2]!==r.z||n[i+4]!==r.w){const e=this._getBufferForType(s);e[i+0]=n[i+0]=r.x,e[i+1]=n[i+1]=r.y,e[i+2]=n[i+2]=r.z,e[i+3]=n[i+3]=r.w,t=!0}return t}updateColor(e){let t=!1;const n=this.values,r=e.getValue(),i=e.offset;if(n[i+0]!==r.r||n[i+1]!==r.g||n[i+2]!==r.b){const e=this.buffer;e[i+0]=n[i+0]=r.r,e[i+1]=n[i+1]=r.g,e[i+2]=n[i+2]=r.b,t=!0}return t}updateMatrix3(e){let t=!1;const n=this.values,r=e.getValue().elements,i=e.offset;if(n[i+0]!==r[0]||n[i+1]!==r[1]||n[i+2]!==r[2]||n[i+4]!==r[3]||n[i+5]!==r[4]||n[i+6]!==r[5]||n[i+8]!==r[6]||n[i+9]!==r[7]||n[i+10]!==r[8]){const e=this.buffer;e[i+0]=n[i+0]=r[0],e[i+1]=n[i+1]=r[1],e[i+2]=n[i+2]=r[2],e[i+4]=n[i+4]=r[3],e[i+5]=n[i+5]=r[4],e[i+6]=n[i+6]=r[5],e[i+8]=n[i+8]=r[6],e[i+9]=n[i+9]=r[7],e[i+10]=n[i+10]=r[8],t=!0}return t}updateMatrix4(e){let t=!1;const n=this.values,r=e.getValue().elements,i=e.offset;if(!1===function(e,t,n){for(let r=0,i=t.length;r<i;r++)if(e[n+r]!==t[r])return!1;return!0}(n,r,i)){this.buffer.set(r,i),function(e,t,n){for(let r=0,i=t.length;r<i;r++)e[n+r]=t[r]}(n,r,i),t=!0}return t}_getBufferForType(e){return"int"===e||"ivec2"===e||"ivec3"===e||"ivec4"===e?new Int32Array(this.buffer.buffer):"uint"===e||"uvec2"===e||"uvec3"===e||"uvec4"===e?new Uint32Array(this.buffer.buffer):this.buffer}}let ER=0;class AR extends wR{constructor(e,t){super(e),this.id=ER++,this.groupNode=t,this.isNodeUniformsGroup=!0}}let RR=0;class CR extends xR{constructor(e,t){super(e),this.id=RR++,this.texture=t,this.version=t?t.version:0,this.store=!1,this.generation=null,this.isSampledTexture=!0}needsBindingsUpdate(e){const{texture:t}=this;return e!==this.generation?(this.generation=e,!0):t.isVideoTexture}update(){const{texture:e,version:t}=this;return t!==e.version&&(this.version=e.version,!0)}}class NR extends CR{constructor(e,t,n,r=null){super(e,t?t.value:null),this.textureNode=t,this.groupNode=n,this.access=r}needsBindingsUpdate(e){return this.textureNode.value!==this.texture||super.needsBindingsUpdate(e)}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class PR extends NR{constructor(e,t,n,r=null){super(e,t,n,r),this.isSampledCubeTexture=!0}}class LR extends NR{constructor(e,t,n,r=null){super(e,t,n,r),this.isSampledTexture3D=!0}}const DR={textureDimensions:"textureSize",equals:"equal"},IR={low:"lowp",medium:"mediump",high:"highp"},UR={swizzleAssign:!0,storageBuffer:!1},OR={perspective:"smooth",linear:"noperspective"},FR={centroid:"centroid"},BR="\nprecision highp float;\nprecision highp int;\nprecision highp sampler2D;\nprecision highp sampler3D;\nprecision highp samplerCube;\nprecision highp sampler2DArray;\n\nprecision highp usampler2D;\nprecision highp usampler3D;\nprecision highp usamplerCube;\nprecision highp usampler2DArray;\n\nprecision highp isampler2D;\nprecision highp isampler3D;\nprecision highp isamplerCube;\nprecision highp isampler2DArray;\n\nprecision lowp sampler2DShadow;\nprecision lowp sampler2DArrayShadow;\nprecision lowp samplerCubeShadow;\n";class kR extends bA{constructor(e,t){super(e,t,new GA),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]}}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==nt}getMethod(e){return DR[e]||e}getOutputStructName(){return""}buildFunctionCode(e){const t=e.layout,n=this.flowShaderNode(e),r=[];for(const e of t.inputs)r.push(this.getType(e.type)+" "+e.name);return`${this.getType(t.type)} ${t.name}( ${r.join(", ")} ) {\n\n\t${n.vars}\n\n${n.code}\n\treturn ${n.result};\n\n}`}setupPBO(e){const t=e.value;if(void 0===t.pbo){const e=t.array,n=t.count*t.itemSize,{itemSize:r}=t,i=t.array.constructor.name.toLowerCase().includes("int");let s=i?xe:ye;2===r?s=i?Te:be:3===r?s=i?1032:me:4===r&&(s=i?Se:ge);const a={Float32Array:le,Uint8Array:ne,Uint16Array:se,Uint32Array:oe,Int8Array:re,Int16Array:ie,Int32Array:ae,Uint8ClampedArray:ne},o=Math.pow(2,Math.ceil(Math.log2(Math.sqrt(n/r))));let l=Math.ceil(n/r/o);o*l*r<n&&l++;const u=o*l*r,c=new e.constructor(u);c.set(e,0),t.array=c;const h=new Fi(t.array,o,l,s,a[t.array.constructor.name]||le);h.needsUpdate=!0,h.isPBOTexture=!0;const d=new Dv(h,null,null);d.setPrecision("high"),t.pboNode=d,t.pbo=d.value,this.getUniformFromNode(t.pboNode,"texture",this.shaderStage,this.context.label)}}getPropertyName(e,t=this.shaderStage){return e.isNodeUniform&&!0!==e.node.isTextureNode&&!0!==e.node.isBufferNode?t.charAt(0)+"_"+e.name:super.getPropertyName(e,t)}generatePBO(e){const{node:t,indexNode:n}=e,r=t.value;if(this.renderer.backend.has(r)){this.renderer.backend.get(r).pbo=r.pbo}const i=this.getUniformFromNode(r.pboNode,"texture",this.shaderStage,this.context.label),s=this.getPropertyName(i);this.increaseUsage(n);const a=n.build(this,"uint"),o=this.getDataFromNode(e);let l=o.propertyName;if(void 0===l){const n=this.getVarFromNode(e);l=this.getPropertyName(n);const i=this.getDataFromNode(t);let u=i.propertySizeName;void 0===u&&(u=l+"Size",this.getVarFromNode(t,u,"uint"),this.addLineFlowCode(`${u} = uint( textureSize( ${s}, 0 ).x )`,e),i.propertySizeName=u);const{itemSize:c}=r,h="."+af.join("").slice(0,c),d=`ivec2(${a} % ${u}, ${a} / ${u})`,p=this.generateTextureLoad(null,s,d,null,"0");let f="vec4";r.pbo.type===oe?f="uvec4":r.pbo.type===ae&&(f="ivec4"),this.addLineFlowCode(`${l} = ${f}(${p})${h}`,e),o.propertyName=l}return l}generateTextureLoad(e,t,n,r,i="0"){return r?`texelFetch( ${t}, ivec3( ${n}, ${r} ), ${i} )`:`texelFetch( ${t}, ${n}, ${i} )`}generateTexture(e,t,n,r){return e.isDepthTexture?(r&&(n=`vec4( ${n}, ${r} )`),`texture( ${t}, ${n} ).x`):(r&&(n=`vec3( ${n}, ${r} )`),`texture( ${t}, ${n} )`)}generateTextureLevel(e,t,n,r){return`textureLod( ${t}, ${n}, ${r} )`}generateTextureBias(e,t,n,r){return`texture( ${t}, ${n}, ${r} )`}generateTextureGrad(e,t,n,r){return`textureGrad( ${t}, ${n}, ${r[0]}, ${r[1]} )`}generateTextureCompare(e,t,n,r,i,s=this.shaderStage){if("fragment"===s)return i?`texture( ${t}, vec4( ${n}, ${i}, ${r} ) )`:`texture( ${t}, vec3( ${n}, ${r} ) )`;console.error(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${s} shader.`)}getVars(e){const t=[],n=this.vars[e];if(void 0!==n)for(const e of n)t.push(`${this.getVar(e.type,e.name,e.count)};`);return t.join("\n\t")}getUniforms(e){const t=this.uniforms[e],n=[],r={};for(const i of t){let t=null,s=!1;if("texture"===i.type||"texture3D"===i.type){const e=i.node.value;let n="";!0!==e.isDataTexture&&!0!==e.isData3DTexture||(e.type===oe?n="u":e.type===ae&&(n="i")),t="texture3D"===i.type&&!1===e.isArrayTexture?`${n}sampler3D ${i.name};`:e.compareFunction?!0===e.isArrayTexture?`sampler2DArrayShadow ${i.name};`:`sampler2DShadow ${i.name};`:!0===e.isArrayTexture||!0===e.isDataArrayTexture||!0===e.isCompressedArrayTexture?`${n}sampler2DArray ${i.name};`:`${n}sampler2D ${i.name};`}else if("cubeTexture"===i.type)t=`samplerCube ${i.name};`;else if("buffer"===i.type){const e=i.node,n=this.getType(e.bufferType),r=e.bufferCount,s=r>0?r:"";t=`${e.name} {\n\t${n} ${i.name}[${s}];\n};\n`}else{t=`${this.getVectorType(i.type)} ${this.getPropertyName(i,e)};`,s=!0}const a=i.node.precision;if(null!==a&&(t=IR[a]+" "+t),s){t="\t"+t;const e=i.groupNode.name;(r[e]||(r[e]=[])).push(t)}else t="uniform "+t,n.push(t)}let i="";for(const t in r){const n=r[t];i+=this._getGLSLUniformStruct(e+"_"+t,n.join("\n"))+"\n"}return i+=n.join("\n"),i}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==ae){let n=e;e.isInterleavedBufferAttribute&&(n=e.data);const r=n.array;!1==(r instanceof Uint32Array||r instanceof Int32Array)&&(t=t.slice(1))}return t}getAttributes(e){let t="";if("vertex"===e||"compute"===e){const e=this.getAttributesArray();let n=0;for(const r of e)t+=`layout( location = ${n++} ) in ${r.type} ${r.name};\n`}return t}getStructMembers(e){const t=[];for(const n of e.members)t.push(`\t${n.type} ${n.name};`);return t.join("\n")}getStructs(e){const t=[],n=this.structs[e],r=[];for(const e of n)if(e.output)for(const t of e.members)r.push(`layout( location = ${t.index} ) out ${t.type} ${t.name};`);else{let n="struct "+e.name+" {\n";n+=this.getStructMembers(e),n+="\n};\n",t.push(n)}return 0===r.length&&r.push("layout( location = 0 ) out vec4 fragColor;"),"\n"+r.join("\n")+"\n\n"+t.join("\n")}getVaryings(e){let t="";const n=this.varyings;if("vertex"===e||"compute"===e)for(const r of n){"compute"===e&&(r.needsInterpolation=!0);const n=this.getType(r.type);if(r.needsInterpolation)if(r.interpolationType){t+=`${OR[r.interpolationType]||r.interpolationType} ${FR[r.interpolationSampling]||""} out ${n} ${r.name};\n`}else{t+=`${n.includes("int")||n.includes("uv")||n.includes("iv")?"flat ":""}out ${n} ${r.name};\n`}else t+=`${n} ${r.name};\n`}else if("fragment"===e)for(const e of n)if(e.needsInterpolation){const n=this.getType(e.type);if(e.interpolationType){t+=`${OR[e.interpolationType]||e.interpolationType} ${FR[e.interpolationSampling]||""} in ${n} ${e.name};\n`}else{t+=`${n.includes("int")||n.includes("uv")||n.includes("iv")?"flat ":""}in ${n} ${e.name};\n`}}for(const n of this.builtins[e])t+=`${n};\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`}getDrawIndex(){return this.renderer.backend.extensions.has("WEBGL_multi_draw")?"uint( gl_DrawID )":null}getFrontFacing(){return"gl_FrontFacing"}getFragCoord(){return"gl_FragCoord.xy"}getFragDepth(){return"gl_FragDepth"}enableExtension(e,t,n=this.shaderStage){const r=this.extensions[n]||(this.extensions[n]=new Map);!1===r.has(e)&&r.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 n=this.extensions[e];if(void 0!==n)for(const{name:e,behavior:r}of n.values())t.push(`#extension ${e} : ${r}`);return t.join("\n")}getClipDistance(){return"gl_ClipDistance"}isAvailable(e){let t=UR[e];if(void 0===t){let n;switch(t=!1,e){case"float32Filterable":n="OES_texture_float_linear";break;case"clipDistance":n="WEBGL_clip_cull_distance"}if(void 0!==n){const e=this.renderer.backend.extensions;e.has(n)&&(e.get(n),t=!0)}UR[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 n=0;n<e.length;n++){const r=e[n],i=this.getPropertyName(r.attributeNode);i&&(t+=`${r.varyingName} = ${i};\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${BR}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\n\n// attributes\n${e.attributes}\n\n// codes\n${e.codes}\n\nvoid main() {\n\n\t// vars\n\t${e.vars}\n\n\t// transforms\n\t${e.transforms}\n\n\t// flow\n\t${e.flow}\n\n\tgl_PointSize = 1.0;\n\n}\n`}_getGLSLFragmentCode(e){return`#version 300 es\n\n${this.getSignature()}\n\n// extensions\n${e.extensions}\n\n// precision\n${BR}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\n\n// codes\n${e.codes}\n\n// structs\n${e.structs}\n\nvoid main() {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){let n="// code\n\n";n+=this.flowCode[t];const r=this.flowNodes[t],i=r[r.length-1];for(const e of r){const r=this.getFlowData(e),s=e.name;s&&(n.length>0&&(n+="\n"),n+=`\t// flow -> ${s}\n\t`),n+=`${r.code}\n\t`,e===i&&"compute"!==t&&(n+="// result\n\t","vertex"===t?(n+="gl_Position = ",n+=`${r.result};`):"fragment"===t&&(e.outputNode.isOutputStructNode||(n+="fragColor = ",n+=`${r.result};`)))}const s=e[t];s.extensions=this.getExtensions(t),s.uniforms=this.getUniforms(t),s.attributes=this.getAttributes(t),s.varyings=this.getVaryings(t),s.vars=this.getVars(t),s.structs=this.getStructs(t),s.codes=this.getCodes(t),s.transforms=this.getTransforms(t),s.flow=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,n,r=null){const i=super.getUniformFromNode(e,t,n,r),s=this.getDataFromNode(e,n,this.globalCache);let a=s.uniformGPU;if(void 0===a){const r=e.groupNode,o=r.name,l=this.getBindGroupArray(o,n);if("texture"===t)a=new NR(i.name,i.node,r),l.push(a);else if("cubeTexture"===t)a=new PR(i.name,i.node,r),l.push(a);else if("texture3D"===t)a=new LR(i.name,i.node,r),l.push(a);else if("buffer"===t){e.name=`NodeBuffer_${e.id}`,i.name=`buffer${e.id}`;const t=new MR(e,r);t.name=e.name,l.push(t),a=t}else{const e=this.uniformGroups[n]||(this.uniformGroups[n]={});let s=e[o];void 0===s&&(s=new AR(n+"_"+o,r),e[o]=s,l.push(s)),a=this.getNodeUniform(i,t),s.addUniform(a)}s.uniformGPU=a}return i}}let zR=null,VR=null;class GR{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={render:null,compute: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(){}createSampler(){}destroySampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}isOccluded(){}async resolveTimestampsAsync(e="render"){if(!this.trackTimestamp)return void jt("WebGPURenderer: Timestamp tracking is disabled.");const t=this.timestampQueryPool[e];if(!t)return void jt(`WebGPURenderer: No timestamp query pool for type '${e}' found.`);const n=await t.resolveQueriesAsync();return this.renderer.info[e].timestamp=n,n}async waitForGPU(){}async getArrayBufferAsync(){}async hasFeatureAsync(){}hasFeature(){}getMaxAnisotropy(){}getDrawingBufferSize(){return zR=zR||new Dt,this.renderer.getDrawingBufferSize(zR)}setScissorTest(){}getClearColor(){const e=this.renderer;return VR=VR||new gw,e.getClearColor(VR),VR.getRGB(VR),VR}getDomElement(){let e=this.domElement;return null===e&&(e=void 0!==this.parameters.canvas?this.parameters.canvas:Gt(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${s} webgpu`),this.domElement=e),e}set(e,t){this.data.set(e,t)}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}has(e){return this.data.has(e)}delete(e){this.data.delete(e)}dispose(){}}let HR,jR,WR=0;class XR{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 qR{constructor(e){this.backend=e}createAttribute(e,t){const n=this.backend,{gl:r}=n,i=e.array,s=e.usage||r.STATIC_DRAW,a=e.isInterleavedBufferAttribute?e.data:e,o=n.get(a);let l,u=o.bufferGPU;if(void 0===u&&(u=this._createBuffer(r,t,i,s),o.bufferGPU=u,o.bufferType=t,o.version=a.version),i instanceof Float32Array)l=r.FLOAT;else if("undefined"!=typeof Float16Array&&i instanceof Float16Array)l=r.HALF_FLOAT;else if(i instanceof Uint16Array)l=e.isFloat16BufferAttribute?r.HALF_FLOAT:r.UNSIGNED_SHORT;else if(i instanceof Int16Array)l=r.SHORT;else if(i instanceof Uint32Array)l=r.UNSIGNED_INT;else if(i instanceof Int32Array)l=r.INT;else if(i instanceof Int8Array)l=r.BYTE;else if(i instanceof Uint8Array)l=r.UNSIGNED_BYTE;else{if(!(i instanceof Uint8ClampedArray))throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+i);l=r.UNSIGNED_BYTE}let c={bufferGPU:u,bufferType:t,type:l,byteLength:i.byteLength,bytesPerElement:i.BYTES_PER_ELEMENT,version:e.version,pbo:e.pbo,isInteger:l===r.INT||l===r.UNSIGNED_INT||e.gpuType===ae,id:WR++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(r,t,i,s);c=new XR(c,e)}n.set(e,c)}updateAttribute(e){const t=this.backend,{gl:n}=t,r=e.array,i=e.isInterleavedBufferAttribute?e.data:e,s=t.get(i),a=s.bufferType,o=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(n.bindBuffer(a,s.bufferGPU),0===o.length)n.bufferSubData(a,0,r);else{for(let e=0,t=o.length;e<t;e++){const t=o[e];n.bufferSubData(a,t.start*r.BYTES_PER_ELEMENT,r,t.start,t.count)}i.clearUpdateRanges()}n.bindBuffer(a,null),s.version=i.version}destroyAttribute(e){const t=this.backend,{gl:n}=t;e.isInterleavedBufferAttribute&&t.delete(e.data);const r=t.get(e);n.deleteBuffer(r.bufferGPU),t.delete(e)}async getArrayBufferAsync(e){const t=this.backend,{gl:n}=t,r=e.isInterleavedBufferAttribute?e.data:e,{bufferGPU:i}=t.get(r),s=e.array,a=s.byteLength;n.bindBuffer(n.COPY_READ_BUFFER,i);const o=n.createBuffer();n.bindBuffer(n.COPY_WRITE_BUFFER,o),n.bufferData(n.COPY_WRITE_BUFFER,a,n.STREAM_READ),n.copyBufferSubData(n.COPY_READ_BUFFER,n.COPY_WRITE_BUFFER,0,0,a),await t.utils._clientWaitAsync();const l=new e.array.constructor(s.length);return n.bindBuffer(n.COPY_WRITE_BUFFER,o),n.getBufferSubData(n.COPY_WRITE_BUFFER,0,l),n.deleteBuffer(o),n.bindBuffer(n.COPY_READ_BUFFER,null),n.bindBuffer(n.COPY_WRITE_BUFFER,null),l.buffer}_createBuffer(e,t,n,r){const i=e.createBuffer();return e.bindBuffer(t,i),e.bufferData(t,n,r),e.bindBuffer(t,null),i}}class $R{constructor(e){this.backend=e,this.gl=this.backend.gl,this.enabled={},this.currentFlipSided=null,this.currentCullFace=null,this.currentProgram=null,this.currentBlendingEnabled=!1,this.currentBlending=null,this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentPremultipledAlpha=null,this.currentPolygonOffsetFactor=null,this.currentPolygonOffsetUnits=null,this.currentColorMask=null,this.currentDepthFunc=null,this.currentDepthMask=null,this.currentStencilFunc=null,this.currentStencilRef=null,this.currentStencilFuncMask=null,this.currentStencilFail=null,this.currentStencilZFail=null,this.currentStencilZPass=null,this.currentStencilMask=null,this.currentLineWidth=null,this.currentClippingPlanes=0,this.currentVAO=null,this.currentIndex=null,this.currentBoundFramebuffers={},this.currentDrawbuffers=new WeakMap,this.maxTextures=this.gl.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.currentTextureSlot=null,this.currentBoundTextures={},this.currentBoundBufferBases={},this._init()}_init(){const e=this.gl;HR={[g]:e.FUNC_ADD,[_]:e.FUNC_SUBTRACT,[v]:e.FUNC_REVERSE_SUBTRACT},jR={[y]:e.ZERO,[x]:e.ONE,[b]:e.SRC_COLOR,[S]:e.SRC_ALPHA,[C]:e.SRC_ALPHA_SATURATE,[A]:e.DST_COLOR,[w]:e.DST_ALPHA,[T]:e.ONE_MINUS_SRC_COLOR,[M]:e.ONE_MINUS_SRC_ALPHA,[R]:e.ONE_MINUS_DST_COLOR,[E]:e.ONE_MINUS_DST_ALPHA};const t=e.getParameter(e.SCISSOR_BOX),n=e.getParameter(e.VIEWPORT);this.currentScissor=(new an).fromArray(t),this.currentViewport=(new an).fromArray(n),this._tempVec4=new an}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:n}=this;e!==t&&(n.lineWidth(e),this.currentLineWidth=e)}setBlending(e,t,n,r,i,s,a,o){const{gl:l}=this;if(0!==e){if(!1===this.currentBlendingEnabled&&(this.enable(l.BLEND),this.currentBlendingEnabled=!0),5===e)i=i||t,s=s||n,a=a||r,t===this.currentBlendEquation&&i===this.currentBlendEquationAlpha||(l.blendEquationSeparate(HR[t],HR[i]),this.currentBlendEquation=t,this.currentBlendEquationAlpha=i),n===this.currentBlendSrc&&r===this.currentBlendDst&&s===this.currentBlendSrcAlpha&&a===this.currentBlendDstAlpha||(l.blendFuncSeparate(jR[n],jR[r],jR[s],jR[a]),this.currentBlendSrc=n,this.currentBlendDst=r,this.currentBlendSrcAlpha=s,this.currentBlendDstAlpha=a),this.currentBlending=e,this.currentPremultipledAlpha=!1;else if(e!==this.currentBlending||o!==this.currentPremultipledAlpha){if(this.currentBlendEquation===g&&this.currentBlendEquationAlpha===g||(l.blendEquation(l.FUNC_ADD),this.currentBlendEquation=g,this.currentBlendEquationAlpha=g),o)switch(e){case 1:l.blendFuncSeparate(l.ONE,l.ONE_MINUS_SRC_ALPHA,l.ONE,l.ONE_MINUS_SRC_ALPHA);break;case 2:l.blendFunc(l.ONE,l.ONE);break;case 3:l.blendFuncSeparate(l.ZERO,l.ONE_MINUS_SRC_COLOR,l.ZERO,l.ONE);break;case 4:l.blendFuncSeparate(l.DST_COLOR,l.ONE_MINUS_SRC_ALPHA,l.ZERO,l.ONE);break;default:console.error("THREE.WebGLState: Invalid blending: ",e)}else switch(e){case 1:l.blendFuncSeparate(l.SRC_ALPHA,l.ONE_MINUS_SRC_ALPHA,l.ONE,l.ONE_MINUS_SRC_ALPHA);break;case 2:l.blendFuncSeparate(l.SRC_ALPHA,l.ONE,l.ONE,l.ONE);break;case 3:console.error("THREE.WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case 4:console.error("THREE.WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:console.error("THREE.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(l.BLEND),this.currentBlendingEnabled=!1)}setColorMask(e){this.currentColorMask!==e&&(this.gl.colorMask(e,e,e,e),this.currentColorMask=e)}setDepthTest(e){const{gl:t}=this;e?this.enable(t.DEPTH_TEST):this.disable(t.DEPTH_TEST)}setDepthMask(e){this.currentDepthMask!==e&&(this.gl.depthMask(e),this.currentDepthMask=e)}setDepthFunc(e){if(this.currentDepthFunc!==e){const{gl:t}=this;switch(e){case 0:t.depthFunc(t.NEVER);break;case 1:t.depthFunc(t.ALWAYS);break;case 2:t.depthFunc(t.LESS);break;case 3:default:t.depthFunc(t.LEQUAL);break;case 4:t.depthFunc(t.EQUAL);break;case 5:t.depthFunc(t.GEQUAL);break;case 6:t.depthFunc(t.GREATER);break;case 7:t.depthFunc(t.NOTEQUAL)}this.currentDepthFunc=e}}scissor(e,t,n,r){const i=this._tempVec4.set(e,t,n,r);if(!1===this.currentScissor.equals(i)){const{gl:e}=this;e.scissor(i.x,i.y,i.z,i.w),this.currentScissor.copy(i)}}viewport(e,t,n,r){const i=this._tempVec4.set(e,t,n,r);if(!1===this.currentViewport.equals(i)){const{gl:e}=this;e.viewport(i.x,i.y,i.z,i.w),this.currentViewport.copy(i)}}setScissorTest(e){const t=this.gl;e?t.enable(t.SCISSOR_TEST):t.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,n){this.currentStencilFunc===e&&this.currentStencilRef===t&&this.currentStencilFuncMask===n||(this.gl.stencilFunc(e,t,n),this.currentStencilFunc=e,this.currentStencilRef=t,this.currentStencilFuncMask=n)}setStencilOp(e,t,n){this.currentStencilFail===e&&this.currentStencilZFail===t&&this.currentStencilZPass===n||(this.gl.stencilOp(e,t,n),this.currentStencilFail=e,this.currentStencilZFail=t,this.currentStencilZPass=n)}setMaterial(e,t,n){const{gl:r}=this;2===e.side?this.disable(r.CULL_FACE):this.enable(r.CULL_FACE);let i=1===e.side;t&&(i=!i),this.setFlipSided(i),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 s=e.stencilWrite;if(this.setStencilTest(s),s&&(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.samples>1?this.enable(r.SAMPLE_ALPHA_TO_COVERAGE):this.disable(r.SAMPLE_ALPHA_TO_COVERAGE),n>0&&this.currentClippingPlanes!==n){const e=12288;for(let t=0;t<8;t++)t<n?this.enable(e+t):this.disable(e+t)}}setPolygonOffset(e,t,n){const{gl:r}=this;e?(this.enable(r.POLYGON_OFFSET_FILL),this.currentPolygonOffsetFactor===t&&this.currentPolygonOffsetUnits===n||(r.polygonOffset(t,n),this.currentPolygonOffsetFactor=t,this.currentPolygonOffsetUnits=n)):this.disable(r.POLYGON_OFFSET_FILL)}useProgram(e){return this.currentProgram!==e&&(this.gl.useProgram(e),this.currentProgram=e,!0)}setVertexState(e,t=null){const n=this.gl;return(this.currentVAO!==e||this.currentIndex!==t)&&(n.bindVertexArray(e),null!==t&&n.bindBuffer(n.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:n,currentBoundFramebuffers:r}=this;return r[e]!==t&&(n.bindFramebuffer(e,t),r[e]=t,e===n.DRAW_FRAMEBUFFER&&(r[n.FRAMEBUFFER]=t),e===n.FRAMEBUFFER&&(r[n.DRAW_FRAMEBUFFER]=t),!0)}drawBuffers(e,t){const{gl:n}=this;let r=[],i=!1;if(null!==e.textures){r=this.currentDrawbuffers.get(t),void 0===r&&(r=[],this.currentDrawbuffers.set(t,r));const s=e.textures;if(r.length!==s.length||r[0]!==n.COLOR_ATTACHMENT0){for(let e=0,t=s.length;e<t;e++)r[e]=n.COLOR_ATTACHMENT0+e;r.length=s.length,i=!0}}else r[0]!==n.BACK&&(r[0]=n.BACK,i=!0);i&&n.drawBuffers(r)}activeTexture(e){const{gl:t,currentTextureSlot:n,maxTextures:r}=this;void 0===e&&(e=t.TEXTURE0+r-1),n!==e&&(t.activeTexture(e),this.currentTextureSlot=e)}bindTexture(e,t,n){const{gl:r,currentTextureSlot:i,currentBoundTextures:s,maxTextures:a}=this;void 0===n&&(n=null===i?r.TEXTURE0+a-1:i);let o=s[n];void 0===o&&(o={type:void 0,texture:void 0},s[n]=o),o.type===e&&o.texture===t||(i!==n&&(r.activeTexture(n),this.currentTextureSlot=n),r.bindTexture(e,t),o.type=e,o.texture=t)}bindBufferBase(e,t,n){const{gl:r}=this,i=`${e}-${t}`;return this.currentBoundBufferBases[i]!==n&&(r.bindBufferBase(e,t,n),this.currentBoundBufferBases[i]=n,!0)}unbindTexture(){const{gl:e,currentTextureSlot:t,currentBoundTextures:n}=this,r=n[t];void 0!==r&&void 0!==r.type&&(e.bindTexture(r.type,null),r.type=void 0,r.texture=void 0)}}class YR{constructor(e){this.backend=e,this.gl=this.backend.gl,this.extensions=e.extensions}convert(e,t=""){const{gl:n,extensions:r}=this;let i;const s=$t.getTransfer(t);if(e===ne)return n.UNSIGNED_BYTE;if(e===ce)return n.UNSIGNED_SHORT_4_4_4_4;if(e===he)return n.UNSIGNED_SHORT_5_5_5_1;if(e===pe)return n.UNSIGNED_INT_5_9_9_9_REV;if(e===re)return n.BYTE;if(e===ie)return n.SHORT;if(e===se)return n.UNSIGNED_SHORT;if(e===ae)return n.INT;if(e===oe)return n.UNSIGNED_INT;if(e===le)return n.FLOAT;if(e===ue)return n.HALF_FLOAT;if(e===fe)return n.ALPHA;if(e===me)return n.RGB;if(e===ge)return n.RGBA;if(e===_e)return n.DEPTH_COMPONENT;if(e===ve)return n.DEPTH_STENCIL;if(e===ye)return n.RED;if(e===xe)return n.RED_INTEGER;if(e===be)return n.RG;if(e===Te)return n.RG_INTEGER;if(e===Se)return n.RGBA_INTEGER;if(e===Me||e===we||e===Ee||e===Ae)if(s===at){if(i=r.get("WEBGL_compressed_texture_s3tc_srgb"),null===i)return null;if(e===Me)return i.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(e===we)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(e===Ee)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(e===Ae)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(i=r.get("WEBGL_compressed_texture_s3tc"),null===i)return null;if(e===Me)return i.COMPRESSED_RGB_S3TC_DXT1_EXT;if(e===we)return i.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(e===Ee)return i.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(e===Ae)return i.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(e===Re||e===Ce||e===Ne||e===Pe){if(i=r.get("WEBGL_compressed_texture_pvrtc"),null===i)return null;if(e===Re)return i.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(e===Ce)return i.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(e===Ne)return i.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(e===Pe)return i.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(e===Le||e===De||e===Ie){if(i=r.get("WEBGL_compressed_texture_etc"),null===i)return null;if(e===Le||e===De)return s===at?i.COMPRESSED_SRGB8_ETC2:i.COMPRESSED_RGB8_ETC2;if(e===Ie)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:i.COMPRESSED_RGBA8_ETC2_EAC}if(e===Ue||e===Oe||e===Fe||e===Be||e===ke||e===ze||e===Ve||e===Ge||e===He||e===je||e===We||e===Xe||e===qe||e===$e){if(i=r.get("WEBGL_compressed_texture_astc"),null===i)return null;if(e===Ue)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:i.COMPRESSED_RGBA_ASTC_4x4_KHR;if(e===Oe)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:i.COMPRESSED_RGBA_ASTC_5x4_KHR;if(e===Fe)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:i.COMPRESSED_RGBA_ASTC_5x5_KHR;if(e===Be)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:i.COMPRESSED_RGBA_ASTC_6x5_KHR;if(e===ke)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:i.COMPRESSED_RGBA_ASTC_6x6_KHR;if(e===ze)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:i.COMPRESSED_RGBA_ASTC_8x5_KHR;if(e===Ve)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:i.COMPRESSED_RGBA_ASTC_8x6_KHR;if(e===Ge)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:i.COMPRESSED_RGBA_ASTC_8x8_KHR;if(e===He)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:i.COMPRESSED_RGBA_ASTC_10x5_KHR;if(e===je)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:i.COMPRESSED_RGBA_ASTC_10x6_KHR;if(e===We)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:i.COMPRESSED_RGBA_ASTC_10x8_KHR;if(e===Xe)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:i.COMPRESSED_RGBA_ASTC_10x10_KHR;if(e===qe)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:i.COMPRESSED_RGBA_ASTC_12x10_KHR;if(e===$e)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:i.COMPRESSED_RGBA_ASTC_12x12_KHR}if(e===Ye){if(i=r.get("EXT_texture_compression_bptc"),null===i)return null;if(e===Ye)return s===at?i.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:i.COMPRESSED_RGBA_BPTC_UNORM_EXT}if(e===Ze||e===Je||e===et||e===tt){if(i=r.get("EXT_texture_compression_rgtc"),null===i)return null;if(e===Ye)return i.COMPRESSED_RED_RGTC1_EXT;if(e===Je)return i.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(e===et)return i.COMPRESSED_RED_GREEN_RGTC2_EXT;if(e===tt)return i.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}return e===de?n.UNSIGNED_INT_24_8:void 0!==n[e]?n[e]:null}_clientWaitAsync(){const{gl:e}=this,t=e.fenceSync(e.SYNC_GPU_COMMANDS_COMPLETE,0);return e.flush(),new Promise((n,r)=>{!function i(){const s=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(s===e.WAIT_FAILED)return e.deleteSync(t),void r();s!==e.TIMEOUT_EXPIRED?(e.deleteSync(t),n()):requestAnimationFrame(i)}()})}}let KR,QR,ZR,JR=!1;class eC{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},!1===JR&&(this._init(),JR=!0)}_init(){const e=this.gl;KR={[q]:e.REPEAT,[$]:e.CLAMP_TO_EDGE,[Y]:e.MIRRORED_REPEAT},QR={[K]:e.NEAREST,[Q]:e.NEAREST_MIPMAP_NEAREST,[Z]:e.NEAREST_MIPMAP_LINEAR,[J]:e.LINEAR,[ee]:e.LINEAR_MIPMAP_NEAREST,[te]:e.LINEAR_MIPMAP_LINEAR},ZR={[lt]:e.NEVER,[mt]:e.ALWAYS,[ut]:e.LESS,[ht]:e.LEQUAL,[ct]:e.EQUAL,[ft]:e.GEQUAL,[dt]:e.GREATER,[pt]:e.NOTEQUAL}}getGLTextureType(e){const{gl:t}=this;let n;return n=!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,n}getInternalFormat(e,t,n,r,i=!1){const{gl:s,extensions:a}=this;if(null!==e){if(void 0!==s[e])return s[e];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+e+"'")}let o=t;if(t===s.RED&&(n===s.FLOAT&&(o=s.R32F),n===s.HALF_FLOAT&&(o=s.R16F),n===s.UNSIGNED_BYTE&&(o=s.R8),n===s.UNSIGNED_SHORT&&(o=s.R16),n===s.UNSIGNED_INT&&(o=s.R32UI),n===s.BYTE&&(o=s.R8I),n===s.SHORT&&(o=s.R16I),n===s.INT&&(o=s.R32I)),t===s.RED_INTEGER&&(n===s.UNSIGNED_BYTE&&(o=s.R8UI),n===s.UNSIGNED_SHORT&&(o=s.R16UI),n===s.UNSIGNED_INT&&(o=s.R32UI),n===s.BYTE&&(o=s.R8I),n===s.SHORT&&(o=s.R16I),n===s.INT&&(o=s.R32I)),t===s.RG&&(n===s.FLOAT&&(o=s.RG32F),n===s.HALF_FLOAT&&(o=s.RG16F),n===s.UNSIGNED_BYTE&&(o=s.RG8),n===s.UNSIGNED_SHORT&&(o=s.RG16),n===s.UNSIGNED_INT&&(o=s.RG32UI),n===s.BYTE&&(o=s.RG8I),n===s.SHORT&&(o=s.RG16I),n===s.INT&&(o=s.RG32I)),t===s.RG_INTEGER&&(n===s.UNSIGNED_BYTE&&(o=s.RG8UI),n===s.UNSIGNED_SHORT&&(o=s.RG16UI),n===s.UNSIGNED_INT&&(o=s.RG32UI),n===s.BYTE&&(o=s.RG8I),n===s.SHORT&&(o=s.RG16I),n===s.INT&&(o=s.RG32I)),t===s.RGB){const e=i?st:$t.getTransfer(r);n===s.FLOAT&&(o=s.RGB32F),n===s.HALF_FLOAT&&(o=s.RGB16F),n===s.UNSIGNED_BYTE&&(o=s.RGB8),n===s.UNSIGNED_SHORT&&(o=s.RGB16),n===s.UNSIGNED_INT&&(o=s.RGB32UI),n===s.BYTE&&(o=s.RGB8I),n===s.SHORT&&(o=s.RGB16I),n===s.INT&&(o=s.RGB32I),n===s.UNSIGNED_BYTE&&(o=e===at?s.SRGB8:s.RGB8),n===s.UNSIGNED_SHORT_5_6_5&&(o=s.RGB565),n===s.UNSIGNED_SHORT_5_5_5_1&&(o=s.RGB5_A1),n===s.UNSIGNED_SHORT_4_4_4_4&&(o=s.RGB4),n===s.UNSIGNED_INT_5_9_9_9_REV&&(o=s.RGB9_E5)}if(t===s.RGB_INTEGER&&(n===s.UNSIGNED_BYTE&&(o=s.RGB8UI),n===s.UNSIGNED_SHORT&&(o=s.RGB16UI),n===s.UNSIGNED_INT&&(o=s.RGB32UI),n===s.BYTE&&(o=s.RGB8I),n===s.SHORT&&(o=s.RGB16I),n===s.INT&&(o=s.RGB32I)),t===s.RGBA){const e=i?st:$t.getTransfer(r);n===s.FLOAT&&(o=s.RGBA32F),n===s.HALF_FLOAT&&(o=s.RGBA16F),n===s.UNSIGNED_BYTE&&(o=s.RGBA8),n===s.UNSIGNED_SHORT&&(o=s.RGBA16),n===s.UNSIGNED_INT&&(o=s.RGBA32UI),n===s.BYTE&&(o=s.RGBA8I),n===s.SHORT&&(o=s.RGBA16I),n===s.INT&&(o=s.RGBA32I),n===s.UNSIGNED_BYTE&&(o=e===at?s.SRGB8_ALPHA8:s.RGBA8),n===s.UNSIGNED_SHORT_4_4_4_4&&(o=s.RGBA4),n===s.UNSIGNED_SHORT_5_5_5_1&&(o=s.RGB5_A1)}return t===s.RGBA_INTEGER&&(n===s.UNSIGNED_BYTE&&(o=s.RGBA8UI),n===s.UNSIGNED_SHORT&&(o=s.RGBA16UI),n===s.UNSIGNED_INT&&(o=s.RGBA32UI),n===s.BYTE&&(o=s.RGBA8I),n===s.SHORT&&(o=s.RGBA16I),n===s.INT&&(o=s.RGBA32I)),t===s.DEPTH_COMPONENT&&(n===s.UNSIGNED_SHORT&&(o=s.DEPTH_COMPONENT16),n===s.UNSIGNED_INT&&(o=s.DEPTH_COMPONENT24),n===s.FLOAT&&(o=s.DEPTH_COMPONENT32F)),t===s.DEPTH_STENCIL&&n===s.UNSIGNED_INT_24_8&&(o=s.DEPTH24_STENCIL8),o!==s.R16F&&o!==s.R32F&&o!==s.RG16F&&o!==s.RG32F&&o!==s.RGBA16F&&o!==s.RGBA32F||a.get("EXT_color_buffer_float"),o}setTextureParameters(e,t){const{gl:n,extensions:r,backend:i}=this,s=$t.getPrimaries($t.workingColorSpace),a=t.colorSpace===nt?null:$t.getPrimaries(t.colorSpace),o=t.colorSpace===nt||s===a?n.NONE:n.BROWSER_DEFAULT_WEBGL;n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,t.flipY),n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),n.pixelStorei(n.UNPACK_ALIGNMENT,t.unpackAlignment),n.pixelStorei(n.UNPACK_COLORSPACE_CONVERSION_WEBGL,o),n.texParameteri(e,n.TEXTURE_WRAP_S,KR[t.wrapS]),n.texParameteri(e,n.TEXTURE_WRAP_T,KR[t.wrapT]),e!==n.TEXTURE_3D&&e!==n.TEXTURE_2D_ARRAY||t.isArrayTexture||n.texParameteri(e,n.TEXTURE_WRAP_R,KR[t.wrapR]),n.texParameteri(e,n.TEXTURE_MAG_FILTER,QR[t.magFilter]);const l=void 0!==t.mipmaps&&t.mipmaps.length>0,u=t.minFilter===J&&l?te:t.minFilter;if(n.texParameteri(e,n.TEXTURE_MIN_FILTER,QR[u]),t.compareFunction&&(n.texParameteri(e,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE),n.texParameteri(e,n.TEXTURE_COMPARE_FUNC,ZR[t.compareFunction])),!0===r.has("EXT_texture_filter_anisotropic")){if(t.magFilter===K)return;if(t.minFilter!==Z&&t.minFilter!==te)return;if(t.type===le&&!1===r.has("OES_texture_float_linear"))return;if(t.anisotropy>1){const s=r.get("EXT_texture_filter_anisotropic");n.texParameterf(e,s.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,i.getMaxAnisotropy()))}}}createDefaultTexture(e){const{gl:t,backend:n,defaultTextures:r}=this,i=this.getGLTextureType(e);let s=r[i];void 0===s&&(s=t.createTexture(),n.state.bindTexture(i,s),t.texParameteri(i,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(i,t.TEXTURE_MAG_FILTER,t.NEAREST),r[i]=s),n.set(e,{textureGPU:s,glTextureType:i,isDefault:!0})}createTexture(e,t){const{gl:n,backend:r}=this,{levels:i,width:s,height:a,depth:o}=t,l=r.utils.convert(e.format,e.colorSpace),u=r.utils.convert(e.type),c=this.getInternalFormat(e.internalFormat,l,u,e.colorSpace,e.isVideoTexture),h=n.createTexture(),d=this.getGLTextureType(e);r.state.bindTexture(d,h),this.setTextureParameters(d,e),e.isArrayTexture||e.isDataArrayTexture||e.isCompressedArrayTexture?n.texStorage3D(n.TEXTURE_2D_ARRAY,i,c,s,a,o):e.isData3DTexture?n.texStorage3D(n.TEXTURE_3D,i,c,s,a,o):e.isVideoTexture||n.texStorage2D(d,i,c,s,a),r.set(e,{textureGPU:h,glTextureType:d,glFormat:l,glType:u,glInternalFormat:c})}copyBufferToTexture(e,t){const{gl:n,backend:r}=this,{textureGPU:i,glTextureType:s,glFormat:a,glType:o}=r.get(t),{width:l,height:u}=t.source.data;n.bindBuffer(n.PIXEL_UNPACK_BUFFER,e),r.state.bindTexture(s,i),n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!1),n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),n.texSubImage2D(s,0,0,0,l,u,a,o,0),n.bindBuffer(n.PIXEL_UNPACK_BUFFER,null),r.state.unbindTexture()}updateTexture(e,t){const{gl:n}=this,{width:r,height:i}=t,{textureGPU:s,glTextureType:a,glFormat:o,glType:l,glInternalFormat:u}=this.backend.get(e);if(!e.isRenderTargetTexture&&void 0!==s)if(this.backend.state.bindTexture(a,s),this.setTextureParameters(a,e),e.isCompressedTexture){const r=e.mipmaps,i=t.image;for(let t=0;t<r.length;t++){const s=r[t];e.isCompressedArrayTexture?e.format!==n.RGBA?null!==o?n.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,t,0,0,0,s.width,s.height,i.depth,o,s.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):n.texSubImage3D(n.TEXTURE_2D_ARRAY,t,0,0,0,s.width,s.height,i.depth,o,l,s.data):null!==o?n.compressedTexSubImage2D(n.TEXTURE_2D,t,0,0,s.width,s.height,o,s.data):console.warn("Unsupported compressed texture format")}}else if(e.isCubeTexture){const e=t.images;for(let t=0;t<6;t++){const s=tC(e[t]);n.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,r,i,o,l,s)}}else if(e.isDataArrayTexture||e.isArrayTexture){const e=t.image;n.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,0,e.width,e.height,e.depth,o,l,e.data)}else if(e.isData3DTexture){const e=t.image;n.texSubImage3D(n.TEXTURE_3D,0,0,0,0,e.width,e.height,e.depth,o,l,e.data)}else if(e.isVideoTexture)e.update(),n.texImage2D(a,0,u,o,l,t.image);else{const e=tC(t.image);n.texSubImage2D(a,0,0,0,r,i,o,l,e)}}generateMipmaps(e){const{gl:t,backend:n}=this,{textureGPU:r,glTextureType:i}=n.get(e);n.state.bindTexture(i,r),t.generateMipmap(i)}deallocateRenderBuffers(e){const{gl:t,backend:n}=this;if(e){const r=n.get(e);if(r.renderBufferStorageSetup=void 0,r.framebuffers){for(const e in r.framebuffers)t.deleteFramebuffer(r.framebuffers[e]);delete r.framebuffers}if(r.depthRenderbuffer&&(t.deleteRenderbuffer(r.depthRenderbuffer),delete r.depthRenderbuffer),r.stencilRenderbuffer&&(t.deleteRenderbuffer(r.stencilRenderbuffer),delete r.stencilRenderbuffer),r.msaaFrameBuffer&&(t.deleteFramebuffer(r.msaaFrameBuffer),delete r.msaaFrameBuffer),r.msaaRenderbuffers){for(let e=0;e<r.msaaRenderbuffers.length;e++)t.deleteRenderbuffer(r.msaaRenderbuffers[e]);delete r.msaaRenderbuffers}}}destroyTexture(e){const{gl:t,backend:n}=this,{textureGPU:r,renderTarget:i}=n.get(e);this.deallocateRenderBuffers(i),t.deleteTexture(r),n.delete(e)}copyTextureToTexture(e,t,n=null,r=null,i=0,s=0){const{gl:a,backend:o}=this,{state:l}=this.backend,{textureGPU:u,glTextureType:c,glType:h,glFormat:d}=o.get(t);let p,f,m,g,_,v,y,x,b;l.bindTexture(c,u);const T=e.isCompressedTexture?e.mipmaps[s]:e.image;if(null!==n)p=n.max.x-n.min.x,f=n.max.y-n.min.y,m=n.isBox3?n.max.z-n.min.z:1,g=n.min.x,_=n.min.y,v=n.isBox3?n.min.z:0;else{const t=Math.pow(2,-i);p=Math.floor(T.width*t),f=Math.floor(T.height*t),m=e.isDataArrayTexture||e.isArrayTexture?T.depth:e.isData3DTexture?Math.floor(T.depth*t):1,g=0,_=0,v=0}null!==r?(y=r.x,x=r.y,b=r.z):(y=0,x=0,b=0),a.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,t.flipY),a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),a.pixelStorei(a.UNPACK_ALIGNMENT,t.unpackAlignment);const S=a.getParameter(a.UNPACK_ROW_LENGTH),M=a.getParameter(a.UNPACK_IMAGE_HEIGHT),w=a.getParameter(a.UNPACK_SKIP_PIXELS),E=a.getParameter(a.UNPACK_SKIP_ROWS),A=a.getParameter(a.UNPACK_SKIP_IMAGES);a.pixelStorei(a.UNPACK_ROW_LENGTH,T.width),a.pixelStorei(a.UNPACK_IMAGE_HEIGHT,T.height),a.pixelStorei(a.UNPACK_SKIP_PIXELS,g),a.pixelStorei(a.UNPACK_SKIP_ROWS,_),a.pixelStorei(a.UNPACK_SKIP_IMAGES,v);const R=t.isDataArrayTexture||t.isData3DTexture||t.isArrayTexture;if(e.isRenderTargetTexture||e.isDepthTexture){const n=o.get(e),r=o.get(t),i=o.get(n.renderTarget),s=o.get(r.renderTarget),u=i.framebuffers[n.cacheKey],c=s.framebuffers[r.cacheKey];l.bindFramebuffer(a.READ_FRAMEBUFFER,u),l.bindFramebuffer(a.DRAW_FRAMEBUFFER,c);let h=a.COLOR_BUFFER_BIT;e.isDepthTexture&&(h=a.DEPTH_BUFFER_BIT),a.blitFramebuffer(g,_,p,f,y,x,p,f,h,a.NEAREST),l.bindFramebuffer(a.READ_FRAMEBUFFER,null),l.bindFramebuffer(a.DRAW_FRAMEBUFFER,null)}else R?e.isDataTexture||e.isData3DTexture?a.texSubImage3D(c,s,y,x,b,p,f,m,d,h,T.data):t.isCompressedArrayTexture?a.compressedTexSubImage3D(c,s,y,x,b,p,f,m,d,T.data):a.texSubImage3D(c,s,y,x,b,p,f,m,d,h,T):e.isDataTexture?a.texSubImage2D(c,s,y,x,p,f,d,h,T.data):e.isCompressedTexture?a.compressedTexSubImage2D(c,s,y,x,T.width,T.height,d,T.data):a.texSubImage2D(c,s,y,x,p,f,d,h,T);a.pixelStorei(a.UNPACK_ROW_LENGTH,S),a.pixelStorei(a.UNPACK_IMAGE_HEIGHT,M),a.pixelStorei(a.UNPACK_SKIP_PIXELS,w),a.pixelStorei(a.UNPACK_SKIP_ROWS,E),a.pixelStorei(a.UNPACK_SKIP_IMAGES,A),0===s&&t.generateMipmaps&&a.generateMipmap(c),l.unbindTexture()}copyFramebufferToTexture(e,t,n){const{gl:r}=this,{state:i}=this.backend,{textureGPU:s}=this.backend.get(e),{x:a,y:o,z:l,w:u}=n,c=!0===e.isDepthTexture||t.renderTarget&&t.renderTarget.samples>0,h=t.renderTarget?t.renderTarget.height:this.backend.getDrawingBufferSize().y;if(c){const n=0!==a||0!==o;let c,d;if(!0===e.isDepthTexture?(c=r.DEPTH_BUFFER_BIT,d=r.DEPTH_ATTACHMENT,t.stencil&&(c|=r.STENCIL_BUFFER_BIT)):(c=r.COLOR_BUFFER_BIT,d=r.COLOR_ATTACHMENT0),n){const e=this.backend.get(t.renderTarget),n=e.framebuffers[t.getCacheKey()],d=e.msaaFrameBuffer;i.bindFramebuffer(r.DRAW_FRAMEBUFFER,n),i.bindFramebuffer(r.READ_FRAMEBUFFER,d);const p=h-o-u;r.blitFramebuffer(a,p,a+l,p+u,a,p,a+l,p+u,c,r.NEAREST),i.bindFramebuffer(r.READ_FRAMEBUFFER,n),i.bindTexture(r.TEXTURE_2D,s),r.copyTexSubImage2D(r.TEXTURE_2D,0,0,0,a,p,l,u),i.unbindTexture()}else{const e=r.createFramebuffer();i.bindFramebuffer(r.DRAW_FRAMEBUFFER,e),r.framebufferTexture2D(r.DRAW_FRAMEBUFFER,d,r.TEXTURE_2D,s,0),r.blitFramebuffer(0,0,l,u,0,0,l,u,c,r.NEAREST),r.deleteFramebuffer(e)}}else i.bindTexture(r.TEXTURE_2D,s),r.copyTexSubImage2D(r.TEXTURE_2D,0,0,0,a,h-u-o,l,u),i.unbindTexture();e.generateMipmaps&&this.generateMipmaps(e),this.backend._setFramebuffer(t)}setupRenderBufferStorage(e,t,n,r=!1){const{gl:i}=this,s=t.renderTarget,{depthTexture:a,depthBuffer:o,stencilBuffer:l,width:u,height:c}=s;if(i.bindRenderbuffer(i.RENDERBUFFER,e),o&&!l){let t=i.DEPTH_COMPONENT24;if(!0===r){this.extensions.get("WEBGL_multisampled_render_to_texture").renderbufferStorageMultisampleEXT(i.RENDERBUFFER,s.samples,t,u,c)}else n>0?(a&&a.isDepthTexture&&a.type===i.FLOAT&&(t=i.DEPTH_COMPONENT32F),i.renderbufferStorageMultisample(i.RENDERBUFFER,n,t,u,c)):i.renderbufferStorage(i.RENDERBUFFER,t,u,c);i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,e)}else o&&l&&(n>0?i.renderbufferStorageMultisample(i.RENDERBUFFER,n,i.DEPTH24_STENCIL8,u,c):i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH_STENCIL,u,c),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.RENDERBUFFER,e));i.bindRenderbuffer(i.RENDERBUFFER,null)}async copyTextureToBuffer(e,t,n,r,i,s){const{backend:a,gl:o}=this,{textureGPU:l,glFormat:u,glType:c}=this.backend.get(e),h=o.createFramebuffer();o.bindFramebuffer(o.READ_FRAMEBUFFER,h);const d=e.isCubeTexture?o.TEXTURE_CUBE_MAP_POSITIVE_X+s:o.TEXTURE_2D;o.framebufferTexture2D(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,d,l,0);const p=this._getTypedArrayType(c),f=r*i*this._getBytesPerTexel(c,u),m=o.createBuffer();o.bindBuffer(o.PIXEL_PACK_BUFFER,m),o.bufferData(o.PIXEL_PACK_BUFFER,f,o.STREAM_READ),o.readPixels(t,n,r,i,u,c,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),await a.utils._clientWaitAsync();const g=new p(f/p.BYTES_PER_ELEMENT);return o.bindBuffer(o.PIXEL_PACK_BUFFER,m),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,g),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),o.deleteFramebuffer(h),g}_getTypedArrayType(e){const{gl:t}=this;if(e===t.UNSIGNED_BYTE)return Uint8Array;if(e===t.UNSIGNED_SHORT_4_4_4_4)return Uint16Array;if(e===t.UNSIGNED_SHORT_5_5_5_1)return Uint16Array;if(e===t.UNSIGNED_SHORT_5_6_5)return Uint16Array;if(e===t.UNSIGNED_SHORT)return Uint16Array;if(e===t.UNSIGNED_INT)return Uint32Array;if(e===t.HALF_FLOAT)return Uint16Array;if(e===t.FLOAT)return Float32Array;throw new Error(`Unsupported WebGL type: ${e}`)}_getBytesPerTexel(e,t){const{gl:n}=this;let r=0;return e===n.UNSIGNED_BYTE&&(r=1),e!==n.UNSIGNED_SHORT_4_4_4_4&&e!==n.UNSIGNED_SHORT_5_5_5_1&&e!==n.UNSIGNED_SHORT_5_6_5&&e!==n.UNSIGNED_SHORT&&e!==n.HALF_FLOAT||(r=2),e!==n.UNSIGNED_INT&&e!==n.FLOAT||(r=4),t===n.RGBA?4*r:t===n.RGB?3*r:t===n.ALPHA?r:void 0}}function tC(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 nC{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 rC{constructor(e){this.backend=e,this.maxAnisotropy=null}getMaxAnisotropy(){if(null!==this.maxAnisotropy)return this.maxAnisotropy;const e=this.backend.gl,t=this.backend.extensions;if(!0===t.has("EXT_texture_filter_anisotropic")){const n=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else this.maxAnisotropy=0;return this.maxAnisotropy}}const iC={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",WEBKIT_WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBGL_compressed_texture_s3tc:"texture-compression-bc",EXT_texture_compression_bptc:"texture-compression-bptc",EXT_disjoint_timer_query_webgl2:"timestamp-query",OVR_multiview2:"OVR_multiview2"};class sC{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:n,mode:r,object:i,type:s,info:a,index:o}=this;0!==o?n.drawElements(r,t,s,e):n.drawArrays(r,e,t),a.update(i,t,1)}renderInstances(e,t,n){const{gl:r,mode:i,type:s,index:a,object:o,info:l}=this;0!==n&&(0!==a?r.drawElementsInstanced(i,t,s,e,n):r.drawArraysInstanced(i,e,t,n),l.update(o,t,n))}renderMultiDraw(e,t,n){const{extensions:r,mode:i,object:s,info:a}=this;if(0===n)return;const o=r.get("WEBGL_multi_draw");if(null===o)for(let r=0;r<n;r++)this.render(e[r],t[r]);else{0!==this.index?o.multiDrawElementsWEBGL(i,t,0,this.type,e,0,n):o.multiDrawArraysWEBGL(i,e,0,t,0,n);let r=0;for(let e=0;e<n;e++)r+=t[e];a.update(s,r,1)}}renderMultiDrawInstances(e,t,n,r){const{extensions:i,mode:s,object:a,info:o}=this;if(0===n)return;const l=i.get("WEBGL_multi_draw");if(null===l)for(let i=0;i<n;i++)this.renderInstances(e[i],t[i],r[i]);else{0!==this.index?l.multiDrawElementsInstancedWEBGL(s,t,0,this.type,e,0,r,0,n):l.multiDrawArraysInstancedWEBGL(s,e,0,t,0,r,0,n);let i=0;for(let e=0;e<n;e++)i+=t[e]*r[e];o.update(a,i,1)}}}class aC{constructor(e=256){this.trackTimestamp=!0,this.maxQueries=e,this.currentQueryIndex=0,this.queryOffsets=new Map,this.isDisposed=!1,this.lastValue=0,this.pendingResolve=!1}allocateQueriesForContext(){}async resolveQueriesAsync(){}dispose(){}}class oC extends aC{constructor(e,t,n=2048){if(super(n),this.gl=e,this.type=t,this.ext=e.getExtension("EXT_disjoint_timer_query_webgl2")||e.getExtension("EXT_disjoint_timer_query"),!this.ext)return console.warn("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 jt(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryStates.set(t,"inactive"),this.queryOffsets.set(e.id,t),t}beginQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e.id);if(null==t)return;if(null!==this.activeQuery)return;const n=this.queries[t];if(n)try{"inactive"===this.queryStates.get(t)&&(this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,n),this.activeQuery=t,this.queryStates.set(t,"started"))}catch(e){console.error("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.id);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){console.error("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=[];for(const[t,n]of this.queryStates)if("ended"===n){const n=this.queries[t];e.push(this.resolveQuery(n))}if(0===e.length)return this.lastValue;const t=(await Promise.all(e)).reduce((e,t)=>e+t,0);return this.lastValue=t,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,t}catch(e){return console.error("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 n,r=!1;const i=e=>{r||(r=!0,n&&(clearTimeout(n),n=null),t(e))},s=()=>{if(this.isDisposed)i(this.lastValue);else try{if(this.gl.getParameter(this.ext.GPU_DISJOINT_EXT))return void i(this.lastValue);if(!this.gl.getQueryParameter(e,this.gl.QUERY_RESULT_AVAILABLE))return void(n=setTimeout(s,1));const r=this.gl.getQueryParameter(e,this.gl.QUERY_RESULT);t(Number(r)/1e6)}catch(e){console.error("Error checking query:",e),t(this.lastValue)}};s()})}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}}}const lC=new Dt;class uC extends GR{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,n={antialias:e.samples>0,alpha:!0,depth:e.depth,stencil:e.stencil},r=void 0!==t.context?t.context:e.domElement.getContext("webgl2",n);function i(t){t.preventDefault();const n={api:"WebGL",message:t.statusMessage||"Unknown reason",reason:null,originalEvent:t};e.onDeviceLost(n)}this._onContextLost=i,e.domElement.addEventListener("webglcontextlost",i,!1),this.gl=r,this.extensions=new nC(this),this.capabilities=new rC(this),this.attributeUtils=new qR(this),this.textureUtils=new eC(this),this.bufferRenderer=new sC(this),this.state=new $R(this),this.utils=new YR(this),this.extensions.get("EXT_color_buffer_float"),this.extensions.get("WEBGL_clip_cull_distance"),this.extensions.get("OES_texture_float_linear"),this.extensions.get("EXT_color_buffer_half_float"),this.extensions.get("WEBGL_multisampled_render_to_texture"),this.extensions.get("WEBGL_render_shared_exponent"),this.extensions.get("WEBGL_multi_draw"),this.extensions.get("OVR_multiview2"),this.disjoint=this.extensions.get("EXT_disjoint_timer_query_webgl2"),this.parallel=this.extensions.get("KHR_parallel_shader_compile")}get coordinateSystem(){return yt}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}async waitForGPU(){await this.utils._clientWaitAsync()}async makeXRCompatible(){!0!==this.gl.getContextAttributes().xrCompatible&&await this.gl.makeXRCompatible()}setXRTarget(e){this._xrFramebuffer=e}setXRRenderTargetTextures(e,t,n=null){const r=this.gl;if(this.set(e.texture,{textureGPU:t,glInternalFormat:r.RGBA8}),null!==n){const t=e.stencilBuffer?r.DEPTH24_STENCIL8:r.DEPTH_COMPONENT24;this.set(e.depthTexture,{textureGPU:n,glInternalFormat:t}),!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!0===e._autoAllocateDepthBuffer&&!1===e.multiview&&console.warn("THREE.WebGLBackend: Render-to-texture extension was disabled because an external texture was provided"),e._autoAllocateDepthBuffer=!1}}initTimestampQuery(e){if(!this.disjoint||!this.trackTimestamp)return;const t=e.isComputeNode?"compute":"render";this.timestampQueryPool[t]||(this.timestampQueryPool[t]=new oC(this.gl,t,2048));const n=this.timestampQueryPool[t];null!==n.allocateQueriesForContext(e)&&n.beginQuery(e)}prepareTimestampBuffer(e){if(!this.disjoint||!this.trackTimestamp)return;const t=e.isComputeNode?"compute":"render";this.timestampQueryPool[t].endQuery(e)}getContext(){return this.gl}beginRender(e){const{state:t}=this,n=this.get(e);if(e.viewport)this.updateViewport(e);else{const{width:e,height:n}=this.getDrawingBufferSize(lC);t.viewport(0,0,e,n)}if(e.scissor){const{x:n,y:r,width:i,height:s}=e.scissorValue;t.scissor(n,e.height-s-r,i,s)}this.initTimestampQuery(e),n.previousContext=this._currentContext,this._currentContext=e,this._setFramebuffer(e),this.clear(e.clearColor,e.clearDepth,e.clearStencil,e,!1);const r=e.occlusionQueryCount;r>0&&(n.currentOcclusionQueries=n.occlusionQueries,n.currentOcclusionQueryObjects=n.occlusionQueryObjects,n.lastOcclusionObject=null,n.occlusionQueries=new Array(r),n.occlusionQueryObjects=new Array(r),n.occlusionQueryIndex=0)}finishRender(e){const{gl:t,state:n}=this,r=this.get(e),i=r.previousContext;n.resetVertexState();const s=e.occlusionQueryCount;s>0&&(s>r.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)}this._currentContext=i;const o=e.renderTarget;if(null!==e.textures&&o){const r=this.get(o);if(o.samples>0&&!1===this._useMultisampledExtension(o)){const i=r.framebuffers[e.getCacheKey()];let s=t.COLOR_BUFFER_BIT;o.resolveDepthBuffer&&(o.depthBuffer&&(s|=t.DEPTH_BUFFER_BIT),o.stencilBuffer&&o.resolveStencilBuffer&&(s|=t.STENCIL_BUFFER_BIT));const a=r.msaaFrameBuffer,l=r.msaaRenderbuffers,u=e.textures,c=u.length>1;if(n.bindFramebuffer(t.READ_FRAMEBUFFER,a),n.bindFramebuffer(t.DRAW_FRAMEBUFFER,i),c)for(let e=0;e<u.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 n=0;n<u.length;n++){if(c){const{textureGPU:e}=this.get(u[n]);t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,l[n]),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0)}if(e.scissor){const{x:n,y:r,width:i,height:a}=e.scissorValue,o=e.height-a-r;t.blitFramebuffer(n,o,n+i,o+a,n,o,n+i,o+a,s,t.NEAREST)}else t.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,s,t.NEAREST)}if(c)for(let e=0;e<u.length;e++){const{textureGPU:n}=this.get(u[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,n,0)}!0===this._supportsInvalidateFramebuffer&&t.invalidateFramebuffer(t.READ_FRAMEBUFFER,r.invalidationArray)}else if(!1===o.resolveDepthBuffer&&r.framebuffers){const i=r.framebuffers[e.getCacheKey()];n.bindFramebuffer(t.DRAW_FRAMEBUFFER,i),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,r.depthInvalidationArray)}}if(null!==i)if(this._setFramebuffer(i),i.viewport)this.updateViewport(i);else{const{width:e,height:t}=this.getDrawingBufferSize(lC);n.viewport(0,0,e,t)}this.prepareTimestampBuffer(e)}resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueries:n,currentOcclusionQueryObjects:r}=t;if(n&&r){const e=new WeakSet,{gl:i}=this;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueries=null;const s=()=>{let a=0;for(let t=0;t<n.length;t++){const s=n[t];null!==s&&(i.getQueryParameter(s,i.QUERY_RESULT_AVAILABLE)&&(0===i.getQueryParameter(s,i.QUERY_RESULT)&&e.add(r[t]),n[t]=null,i.deleteQuery(s),a++))}a<n.length?requestAnimationFrame(s):t.occluded=e};s()}}isOccluded(e,t){const n=this.get(e);return n.occluded&&n.occluded.has(t)}updateViewport(e){const{state:t}=this,{x:n,y:r,width:i,height:s}=e.viewportValue;t.viewport(n,e.height-s-r,i,s)}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,n,r=null,i=!0){const{gl:s,renderer:a}=this;if(null===r){r={textures:null,clearColorValue:this.getClearColor()}}let o=0;if(e&&(o|=s.COLOR_BUFFER_BIT),t&&(o|=s.DEPTH_BUFFER_BIT),n&&(o|=s.STENCIL_BUFFER_BIT),0!==o){let l;l=r.clearColorValue?r.clearColorValue:this.getClearColor();const u=a.getClearDepth(),c=a.getClearStencil();if(t&&this.state.setDepthMask(!0),null===r.textures)s.clearColor(l.r,l.g,l.b,l.a),s.clear(o);else{if(i&&this._setFramebuffer(r),e)for(let e=0;e<r.textures.length;e++)0===e?s.clearBufferfv(s.COLOR,e,[l.r,l.g,l.b,l.a]):s.clearBufferfv(s.COLOR,e,[0,0,0,1]);t&&n?s.clearBufferfi(s.DEPTH_STENCIL,0,u,c):t?s.clearBufferfv(s.DEPTH,0,[u]):n&&s.clearBufferiv(s.STENCIL,0,[c])}}}beginCompute(e){const{state:t,gl:n}=this;t.bindFramebuffer(n.FRAMEBUFFER,null),this.initTimestampQuery(e)}compute(e,t,n,r){const{state:i,gl:s}=this;!1===this.discard&&(s.enable(s.RASTERIZER_DISCARD),this.discard=!0);const{programGPU:a,transformBuffers:o,attributes:l}=this.get(r),u=this._getVaoKey(l),c=this.vaoCache[u];void 0===c?this.vaoCache[u]=this._createVao(l):i.setVertexState(c),i.useProgram(a),this._bindUniforms(n);const h=this._getTransformFeedback(o);s.bindTransformFeedback(s.TRANSFORM_FEEDBACK,h),s.beginTransformFeedback(s.POINTS),l[0].isStorageInstancedBufferAttribute?s.drawArraysInstanced(s.POINTS,0,1,t.count):s.drawArrays(s.POINTS,0,t.count),s.endTransformFeedback(),s.bindTransformFeedback(s.TRANSFORM_FEEDBACK,null);for(let e=0;e<o.length;e++){const t=o[e];t.pbo&&this.has(t.pbo)&&this.textureUtils.copyBufferToTexture(t.transformBuffer,t.pbo),t.switchBuffers()}}finishCompute(e){const t=this.gl;this.discard=!1,t.disable(t.RASTERIZER_DISCARD),this.prepareTimestampBuffer(e),this._currentContext&&this._setFramebuffer(this._currentContext)}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.isArrayTexture&&e.camera.isArrayCamera}draw(e){const{object:t,pipeline:n,material:r,context:i,hardwareClippingPlanes:s}=e,{programGPU:a}=this.get(n),{gl:o,state:l}=this,u=this.get(i),c=e.getDrawParameters();if(null===c)return;this._bindUniforms(e.getBindings());const h=t.isMesh&&t.matrixWorld.determinant()<0;l.setMaterial(r,h,s),l.useProgram(a);const d=e.getAttributes(),p=this.get(d);let f=p.vaoGPU;if(void 0===f){const e=this._getVaoKey(d);f=this.vaoCache[e],void 0===f&&(f=this._createVao(d),this.vaoCache[e]=f,p.vaoGPU=f)}const m=e.getIndex(),g=null!==m?this.get(m).bufferGPU:null;l.setVertexState(f,g);const _=u.lastOcclusionObject;if(_!==t&&void 0!==_){if(null!==_&&!0===_.occlusionTest&&(o.endQuery(o.ANY_SAMPLES_PASSED),u.occlusionQueryIndex++),!0===t.occlusionTest){const e=o.createQuery();o.beginQuery(o.ANY_SAMPLES_PASSED,e),u.occlusionQueries[u.occlusionQueryIndex]=e,u.occlusionQueryObjects[u.occlusionQueryIndex]=t}u.lastOcclusionObject=t}const v=this.bufferRenderer;t.isPoints?v.mode=o.POINTS:t.isLineSegments?v.mode=o.LINES:t.isLine?v.mode=o.LINE_STRIP:t.isLineLoop?v.mode=o.LINE_LOOP:!0===r.wireframe?(l.setLineWidth(r.wireframeLinewidth*this.renderer.getPixelRatio()),v.mode=o.LINES):v.mode=o.TRIANGLES;const{vertexCount:y,instanceCount:x}=c;let{firstVertex:b}=c;if(v.object=t,null!==m){b*=m.array.BYTES_PER_ELEMENT;const e=this.get(m);v.index=m.count,v.type=e.type}else v.index=0;const T=()=>{t.isBatchedMesh?null!==t._multiDrawInstances?(jt("THREE.WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),v.renderMultiDrawInstances(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount,t._multiDrawInstances)):this.hasFeature("WEBGL_multi_draw")?v.renderMultiDraw(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount):jt("THREE.WebGLRenderer: WEBGL_multi_draw not supported."):x>1?v.renderInstances(b,y,x):v.render(b,y)};if(!0===e.camera.isArrayCamera&&e.camera.cameras.length>0&&!1===e.camera.isMultiViewCamera){const n=this.get(e.camera),r=e.camera.cameras,i=e.getBindingGroup("cameraIndex").bindings[0];if(void 0===n.indexesGPU||n.indexesGPU.length!==r.length){const e=new Uint32Array([0,0,0,0]),t=[];for(let n=0,i=r.length;n<i;n++){const r=o.createBuffer();e[0]=n,o.bindBuffer(o.UNIFORM_BUFFER,r),o.bufferData(o.UNIFORM_BUFFER,e,o.STATIC_DRAW),t.push(r)}n.indexesGPU=t}const s=this.get(i),a=this.renderer.getPixelRatio(),u=this._currentContext.renderTarget,c=this._isRenderCameraDepthArray(this._currentContext),h=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,n=r.length;e<n;e++)this.renderer._activeCubeFace=e,this._currentContext.activeCubeFace=e,this._setFramebuffer(this._currentContext),this.clear(!1,!0,t,this._currentContext,!1);this.renderer._activeCubeFace=h,this._currentContext.activeCubeFace=h}}for(let i=0,u=r.length;i<u;i++){const u=r[i];if(t.layers.test(u.layers)){c&&(this.renderer._activeCubeFace=i,this._currentContext.activeCubeFace=i,this._setFramebuffer(this._currentContext));const t=u.viewport;if(void 0!==t){const n=t.x*a,r=t.y*a,i=t.width*a,s=t.height*a;l.viewport(Math.floor(n),Math.floor(e.context.height-s-r),Math.floor(i),Math.floor(s))}l.bindBufferBase(o.UNIFORM_BUFFER,s.index,n.indexesGPU[i]),T()}this._currentContext.activeCubeFace=h,this.renderer._activeCubeFace=h}}else T()}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){this.textureUtils.destroyTexture(e)}async copyTextureToBuffer(e,t,n,r,i,s){return this.textureUtils.copyTextureToBuffer(e,t,n,r,i,s)}createSampler(){}destroySampler(){}createNodeBuilder(e,t){return new kR(e,t)}createProgram(e){const t=this.gl,{stage:n,code:r}=e,i="fragment"===n?t.createShader(t.FRAGMENT_SHADER):t.createShader(t.VERTEX_SHADER);t.shaderSource(i,r),t.compileShader(i),this.set(e,{shaderGPU:i})}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){const n=this.gl,r=e.pipeline,{fragmentProgram:i,vertexProgram:s}=r,a=n.createProgram(),o=this.get(i).shaderGPU,l=this.get(s).shaderGPU;if(n.attachShader(a,o),n.attachShader(a,l),n.linkProgram(a),this.set(r,{programGPU:a,fragmentShader:o,vertexShader:l}),null!==t&&this.parallel){const i=new Promise(t=>{const i=this.parallel,s=()=>{n.getProgramParameter(a,i.COMPLETION_STATUS_KHR)?(this._completeCompile(e,r),t()):requestAnimationFrame(s)};s()});return void t.push(i)}this._completeCompile(e,r)}_handleSource(e,t){const n=e.split("\n"),r=[],i=Math.max(t-6,0),s=Math.min(t+6,n.length);for(let e=i;e<s;e++){const i=e+1;r.push(`${i===t?">":" "} ${i}: ${n[e]}`)}return r.join("\n")}_getShaderErrors(e,t,n){const r=e.getShaderParameter(t,e.COMPILE_STATUS),i=e.getShaderInfoLog(t).trim();if(r&&""===i)return"";const s=/ERROR: 0:(\d+)/.exec(i);if(s){const r=parseInt(s[1]);return n.toUpperCase()+"\n\n"+i+"\n\n"+this._handleSource(e.getShaderSource(t),r)}return i}_logProgramError(e,t,n){if(this.renderer.debug.checkShaderErrors){const r=this.gl,i=r.getProgramInfoLog(e).trim();if(!1===r.getProgramParameter(e,r.LINK_STATUS))if("function"==typeof this.renderer.debug.onShaderError)this.renderer.debug.onShaderError(r,e,n,t);else{const s=this._getShaderErrors(r,n,"vertex"),a=this._getShaderErrors(r,t,"fragment");console.error("THREE.WebGLProgram: Shader Error "+r.getError()+" - VALIDATE_STATUS "+r.getProgramParameter(e,r.VALIDATE_STATUS)+"\n\nProgram Info Log: "+i+"\n"+s+"\n"+a)}else""!==i&&console.warn("THREE.WebGLProgram: Program Info Log:",i)}}_completeCompile(e,t){const{state:n,gl:r}=this,i=this.get(t),{programGPU:s,fragmentShader:a,vertexShader:o}=i;!1===r.getProgramParameter(s,r.LINK_STATUS)&&this._logProgramError(s,a,o),n.useProgram(s);const l=e.getBindings();this._setupBindings(l,s),this.set(t,{programGPU:s})}createComputePipeline(e,t){const{state:n,gl:r}=this,i={stage:"fragment",code:"#version 300 es\nprecision highp float;\nvoid main() {}"};this.createProgram(i);const{computeProgram:s}=e,a=r.createProgram(),o=this.get(i).shaderGPU,l=this.get(s).shaderGPU,u=s.transforms,c=[],h=[];for(let e=0;e<u.length;e++){const t=u[e];c.push(t.varyingName),h.push(t.attributeNode)}r.attachShader(a,o),r.attachShader(a,l),r.transformFeedbackVaryings(a,c,r.SEPARATE_ATTRIBS),r.linkProgram(a),!1===r.getProgramParameter(a,r.LINK_STATUS)&&this._logProgramError(a,o,l),n.useProgram(a),this._setupBindings(t,a);const d=s.attributes,p=[],f=[];for(let e=0;e<d.length;e++){const t=d[e].node.attribute;p.push(t),this.has(t)||this.attributeUtils.createAttribute(t,r.ARRAY_BUFFER)}for(let e=0;e<h.length;e++){const t=h[e].attribute;this.has(t)||this.attributeUtils.createAttribute(t,r.ARRAY_BUFFER);const n=this.get(t);f.push(n)}this.set(e,{programGPU:a,transformBuffers:f,attributes:p})}createBindings(e,t){if(!1===this._knownBindings.has(t)){this._knownBindings.add(t);let e=0,n=0;for(const r of t){this.set(r,{textures:n,uniformBuffers:e});for(const t of r.bindings)t.isUniformBuffer&&e++,t.isSampledTexture&&n++}}this.updateBindings(e,t)}updateBindings(e){const{gl:t}=this,n=this.get(e);let r=n.uniformBuffers,i=n.textures;for(const n of e.bindings)if(n.isUniformsGroup||n.isUniformBuffer){const e=n.buffer,i=t.createBuffer();t.bindBuffer(t.UNIFORM_BUFFER,i),t.bufferData(t.UNIFORM_BUFFER,e,t.DYNAMIC_DRAW),this.set(n,{index:r++,bufferGPU:i})}else if(n.isSampledTexture){const{textureGPU:e,glTextureType:t}=this.get(n.texture);this.set(n,{index:i++,textureGPU:e,glTextureType:t})}}updateBinding(e){const t=this.gl;if(e.isUniformsGroup||e.isUniformBuffer){const n=this.get(e).bufferGPU,r=e.buffer;t.bindBuffer(t.UNIFORM_BUFFER,n),t.bufferData(t.UNIFORM_BUFFER,r,t.DYNAMIC_DRAW)}}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(iC).filter(t=>iC[t]===e),n=this.extensions;for(let e=0;e<t.length;e++)if(n.has(t[e]))return!0;return!1}getMaxAnisotropy(){return this.capabilities.getMaxAnisotropy()}copyTextureToTexture(e,t,n=null,r=null,i=0,s=0){this.textureUtils.copyTextureToTexture(e,t,n,r,i,s)}copyFramebufferToTexture(e,t,n){this.textureUtils.copyFramebufferToTexture(e,t,n)}_setFramebuffer(e){const{gl:t,state:n}=this;let r=null;if(null!==e.textures){const i=e.renderTarget,s=this.get(i),{samples:a,depthBuffer:o,stencilBuffer:l}=i,u=!0===i.isWebGLCubeRenderTarget,c=!0===i.isRenderTarget3D,h=i.depth>1,d=!0===i.isXRRenderTarget,p=!0===d&&!0===i._hasExternalTextures;let f=s.msaaFrameBuffer,m=s.depthRenderbuffer;const g=this.extensions.get("WEBGL_multisampled_render_to_texture"),_=this.extensions.get("OVR_multiview2"),v=this._useMultisampledExtension(i),y=uw(e);let x;if(u?(s.cubeFramebuffers||(s.cubeFramebuffers={}),x=s.cubeFramebuffers[y]):d&&!1===p?x=this._xrFramebuffer:(s.framebuffers||(s.framebuffers={}),x=s.framebuffers[y]),void 0===x){x=t.createFramebuffer(),n.bindFramebuffer(t.FRAMEBUFFER,x);const r=e.textures,o=[];if(u){s.cubeFramebuffers[y]=x;const{textureGPU:e}=this.get(r[0]),n=this.renderer._activeCubeFace;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+n,e,0)}else{s.framebuffers[y]=x;for(let n=0;n<r.length;n++){const s=r[n],o=this.get(s);o.renderTarget=e.renderTarget,o.cacheKey=y;const l=t.COLOR_ATTACHMENT0+n;if(i.multiview)_.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,l,o.textureGPU,0,a,0,2);else if(c||h){const e=this.renderer._activeCubeFace;t.framebufferTextureLayer(t.FRAMEBUFFER,l,o.textureGPU,0,e)}else v?g.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,l,t.TEXTURE_2D,o.textureGPU,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,l,t.TEXTURE_2D,o.textureGPU,0)}}const d=l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(!0===i._autoAllocateDepthBuffer){const n=t.createRenderbuffer();this.textureUtils.setupRenderBufferStorage(n,e,0,v),s.xrDepthRenderbuffer=n,o.push(l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT),t.bindRenderbuffer(t.RENDERBUFFER,n),t.framebufferRenderbuffer(t.FRAMEBUFFER,d,t.RENDERBUFFER,n)}else if(null!==e.depthTexture){o.push(l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT);const n=this.get(e.depthTexture);if(n.renderTarget=e.renderTarget,n.cacheKey=y,i.multiview)_.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,d,n.textureGPU,0,a,0,2);else if(p&&v)g.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,d,t.TEXTURE_2D,n.textureGPU,0,a);else if(e.depthTexture.isArrayTexture){const e=this.renderer._activeCubeFace;t.framebufferTextureLayer(t.FRAMEBUFFER,d,n.textureGPU,0,e)}else t.framebufferTexture2D(t.FRAMEBUFFER,d,t.TEXTURE_2D,n.textureGPU,0)}s.depthInvalidationArray=o}else{if(this._isRenderCameraDepthArray(e)){n.bindFramebuffer(t.FRAMEBUFFER,x);const r=this.renderer._activeCubeFace,i=this.get(e.depthTexture),s=l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;t.framebufferTextureLayer(t.FRAMEBUFFER,s,i.textureGPU,0,r)}if((d||v||i.multiview)&&!0!==i._isOpaqueFramebuffer){n.bindFramebuffer(t.FRAMEBUFFER,x);const r=this.get(e.textures[0]);i.multiview?_.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,r.textureGPU,0,a,0,2):v?g.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r.textureGPU,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r.textureGPU,0);const o=l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(!0===i._autoAllocateDepthBuffer){const e=s.xrDepthRenderbuffer;t.bindRenderbuffer(t.RENDERBUFFER,e),t.framebufferRenderbuffer(t.FRAMEBUFFER,o,t.RENDERBUFFER,e)}else{const n=this.get(e.depthTexture);i.multiview?_.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,o,n.textureGPU,0,a,0,2):v?g.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,o,t.TEXTURE_2D,n.textureGPU,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,o,t.TEXTURE_2D,n.textureGPU,0)}}}if(a>0&&!1===v&&!i.multiview){if(void 0===f){const r=[];f=t.createFramebuffer(),n.bindFramebuffer(t.FRAMEBUFFER,f);const i=[],u=e.textures;for(let n=0;n<u.length;n++){i[n]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,i[n]),r.push(t.COLOR_ATTACHMENT0+n);const s=e.textures[n],o=this.get(s);t.renderbufferStorageMultisample(t.RENDERBUFFER,a,o.glInternalFormat,e.width,e.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+n,t.RENDERBUFFER,i[n])}if(t.bindRenderbuffer(t.RENDERBUFFER,null),s.msaaFrameBuffer=f,s.msaaRenderbuffers=i,o&&void 0===m){m=t.createRenderbuffer(),this.textureUtils.setupRenderBufferStorage(m,e,a),s.depthRenderbuffer=m;const n=l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;r.push(n)}s.invalidationArray=r}r=s.msaaFrameBuffer}else r=x;n.drawBuffers(e,x)}n.bindFramebuffer(t.FRAMEBUFFER,r)}_getVaoKey(e){let t="";for(let n=0;n<e.length;n++){t+=":"+this.get(e[n]).id}return t}_createVao(e){const{gl:t}=this,n=t.createVertexArray();t.bindVertexArray(n);for(let n=0;n<e.length;n++){const r=e[n],i=this.get(r);let s,a;t.bindBuffer(t.ARRAY_BUFFER,i.bufferGPU),t.enableVertexAttribArray(n),!0===r.isInterleavedBufferAttribute?(s=r.data.stride*i.bytesPerElement,a=r.offset*i.bytesPerElement):(s=0,a=0),i.isInteger?t.vertexAttribIPointer(n,r.itemSize,i.type,s,a):t.vertexAttribPointer(n,r.itemSize,i.type,r.normalized,s,a),r.isInstancedBufferAttribute&&!r.isInterleavedBufferAttribute?t.vertexAttribDivisor(n,r.meshPerAttribute):r.isInterleavedBufferAttribute&&r.data.isInstancedInterleavedBuffer&&t.vertexAttribDivisor(n,r.data.meshPerAttribute)}return t.bindBuffer(t.ARRAY_BUFFER,null),n}_getTransformFeedback(e){let t="";for(let n=0;n<e.length;n++)t+=":"+e[n].id;let n=this.transformFeedbackCache[t];if(void 0!==n)return n;const{gl:r}=this;n=r.createTransformFeedback(),r.bindTransformFeedback(r.TRANSFORM_FEEDBACK,n);for(let t=0;t<e.length;t++){const n=e[t];r.bindBufferBase(r.TRANSFORM_FEEDBACK_BUFFER,t,n.transformBuffer)}return r.bindTransformFeedback(r.TRANSFORM_FEEDBACK,null),this.transformFeedbackCache[t]=n,n}_setupBindings(e,t){const n=this.gl;for(const r of e)for(const e of r.bindings){const r=this.get(e).index;if(e.isUniformsGroup||e.isUniformBuffer){const i=n.getUniformBlockIndex(t,e.name);n.uniformBlockBinding(t,i,r)}else if(e.isSampledTexture){const i=n.getUniformLocation(t,e.name);n.uniform1i(i,r)}}}_bindUniforms(e){const{gl:t,state:n}=this;for(const r of e)for(const e of r.bindings){const r=this.get(e),i=r.index;e.isUniformsGroup||e.isUniformBuffer?n.bindBufferBase(t.UNIFORM_BUFFER,i,r.bufferGPU):e.isSampledTexture&&n.bindTexture(r.glTextureType,r.textureGPU,t.TEXTURE0+i)}}_useMultisampledExtension(e){return!0===e.multiview||e.samples>0&&!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!1!==e._autoAllocateDepthBuffer}dispose(){const e=this.extensions.get("WEBGL_lose_context");e&&e.loseContext(),this.renderer.domElement.removeEventListener("webglcontextlost",this._onContextLost)}}const cC="point-list",hC="line-list",dC="line-strip",pC="triangle-list",fC="triangle-strip",mC="never",gC="less",_C="equal",vC="less-equal",yC="greater",xC="not-equal",bC="greater-equal",TC="always",SC="store",MC="load",wC="clear",EC="ccw",AC="none",RC="front",CC="back",NC="uint16",PC="uint32",LC="r8unorm",DC="r8snorm",IC="r8uint",UC="r8sint",OC="r16uint",FC="r16sint",BC="r16float",kC="rg8unorm",zC="rg8snorm",VC="rg8uint",GC="rg8sint",HC="r32uint",jC="r32sint",WC="r32float",XC="rg16uint",qC="rg16sint",$C="rg16float",YC="rgba8unorm",KC="rgba8unorm-srgb",QC="rgba8snorm",ZC="rgba8uint",JC="rgba8sint",eN="bgra8unorm",tN="bgra8unorm-srgb",nN="rgb9e5ufloat",rN="rgb10a2unorm",iN="rgb10a2unorm",sN="rg32uint",aN="rg32sint",oN="rg32float",lN="rgba16uint",uN="rgba16sint",cN="rgba16float",hN="rgba32uint",dN="rgba32sint",pN="rgba32float",fN="depth16unorm",mN="depth24plus",gN="depth24plus-stencil8",_N="depth32float",vN="depth32float-stencil8",yN="bc1-rgba-unorm",xN="bc1-rgba-unorm-srgb",bN="bc2-rgba-unorm",TN="bc2-rgba-unorm-srgb",SN="bc3-rgba-unorm",MN="bc3-rgba-unorm-srgb",wN="bc4-r-unorm",EN="bc4-r-snorm",AN="bc5-rg-unorm",RN="bc5-rg-snorm",CN="bc6h-rgb-ufloat",NN="bc6h-rgb-float",PN="bc7-rgba-unorm",LN="bc7-rgba-srgb",DN="etc2-rgb8unorm",IN="etc2-rgb8unorm-srgb",UN="etc2-rgb8a1unorm",ON="etc2-rgb8a1unorm-srgb",FN="etc2-rgba8unorm",BN="etc2-rgba8unorm-srgb",kN="eac-r11unorm",zN="eac-r11snorm",VN="eac-rg11unorm",GN="eac-rg11snorm",HN="astc-4x4-unorm",jN="astc-4x4-unorm-srgb",WN="astc-5x4-unorm",XN="astc-5x4-unorm-srgb",qN="astc-5x5-unorm",$N="astc-5x5-unorm-srgb",YN="astc-6x5-unorm",KN="astc-6x5-unorm-srgb",QN="astc-6x6-unorm",ZN="astc-6x6-unorm-srgb",JN="astc-8x5-unorm",eP="astc-8x5-unorm-srgb",tP="astc-8x6-unorm",nP="astc-8x6-unorm-srgb",rP="astc-8x8-unorm",iP="astc-8x8-unorm-srgb",sP="astc-10x5-unorm",aP="astc-10x5-unorm-srgb",oP="astc-10x6-unorm",lP="astc-10x6-unorm-srgb",uP="astc-10x8-unorm",cP="astc-10x8-unorm-srgb",hP="astc-10x10-unorm",dP="astc-10x10-unorm-srgb",pP="astc-12x10-unorm",fP="astc-12x10-unorm-srgb",mP="astc-12x12-unorm",gP="astc-12x12-unorm-srgb",_P="clamp-to-edge",vP="repeat",yP="mirror-repeat",xP="linear",bP="nearest",TP="zero",SP="one",MP="src",wP="one-minus-src",EP="src-alpha",AP="one-minus-src-alpha",RP="dst",CP="one-minus-dst",NP="dst-alpha",PP="one-minus-dst-alpha",LP="src-alpha-saturated",DP="constant",IP="one-minus-constant",UP="add",OP="subtract",FP="reverse-subtract",BP="min",kP="max",zP=0,VP=15,GP="keep",HP="zero",jP="replace",WP="invert",XP="increment-clamp",qP="decrement-clamp",$P="increment-wrap",YP="decrement-wrap",KP="storage",QP="read-only-storage",ZP="write-only",JP="read-only",eL="read-write",tL="non-filtering",nL="comparison",rL="float",iL="unfilterable-float",sL="depth",aL="sint",oL="uint",lL="2d",uL="3d",cL="2d",hL="2d-array",dL="cube",pL="3d",fL="all",mL="vertex",gL="instance",_L={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"};class vL extends xR{constructor(e,t){super(e),this.texture=t,this.version=t?t.version:0,this.isSampler=!0}}class yL extends vL{constructor(e,t,n){super(e,t?t.value:null),this.textureNode=t,this.groupNode=n}update(){this.texture=this.textureNode.value}}class xL extends bR{constructor(e,t){super(e,t?t.array:null),this.attribute=t,this.isStorageBuffer=!0}}let bL=0;class TL extends xL{constructor(e,t){super("StorageBuffer_"+bL++,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:nf,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class SL extends FM{constructor(e){super(),this.device=e;this.mipmapSampler=e.createSampler({minFilter:xP}),this.flipYSampler=e.createSampler({minFilter:bP}),this.transferPipelines={},this.flipYPipelines={},this.mipmapVertexShaderModule=e.createShaderModule({label:"mipmapVertex",code:"\nstruct VarysStruct {\n\t@builtin( position ) Position: vec4<f32>,\n\t@location( 0 ) vTex : vec2<f32>\n};\n\n@vertex\nfn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {\n\n\tvar Varys : VarysStruct;\n\n\tvar pos = array< vec2<f32>, 4 >(\n\t\tvec2<f32>( -1.0, 1.0 ),\n\t\tvec2<f32>( 1.0, 1.0 ),\n\t\tvec2<f32>( -1.0, -1.0 ),\n\t\tvec2<f32>( 1.0, -1.0 )\n\t);\n\n\tvar tex = array< vec2<f32>, 4 >(\n\t\tvec2<f32>( 0.0, 0.0 ),\n\t\tvec2<f32>( 1.0, 0.0 ),\n\t\tvec2<f32>( 0.0, 1.0 ),\n\t\tvec2<f32>( 1.0, 1.0 )\n\t);\n\n\tVarys.vTex = tex[ vertexIndex ];\n\tVarys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );\n\n\treturn Varys;\n\n}\n"}),this.mipmapFragmentShaderModule=e.createShaderModule({label:"mipmapFragment",code:"\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img : texture_2d<f32>;\n\n@fragment\nfn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {\n\n\treturn textureSample( img, imgSampler, vTex );\n\n}\n"}),this.flipYFragmentShaderModule=e.createShaderModule({label:"flipYFragment",code:"\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img : texture_2d<f32>;\n\n@fragment\nfn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {\n\n\treturn textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );\n\n}\n"})}getTransferPipeline(e){let t=this.transferPipelines[e];return void 0===t&&(t=this.device.createRenderPipeline({label:`mipmap-${e}`,vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.mipmapFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:fC,stripIndexFormat:PC},layout:"auto"}),this.transferPipelines[e]=t),t}getFlipYPipeline(e){let t=this.flipYPipelines[e];return void 0===t&&(t=this.device.createRenderPipeline({label:`flipY-${e}`,vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.flipYFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:fC,stripIndexFormat:PC},layout:"auto"}),this.flipYPipelines[e]=t),t}flipY(e,t,n=0){const r=t.format,{width:i,height:s}=t.size,a=this.getTransferPipeline(r),o=this.getFlipYPipeline(r),l=this.device.createTexture({size:{width:i,height:s,depthOrArrayLayers:1},format:r,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),u=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:cL,baseArrayLayer:n}),c=l.createView({baseMipLevel:0,mipLevelCount:1,dimension:cL,baseArrayLayer:0}),h=this.device.createCommandEncoder({}),d=(e,t,n)=>{const r=e.getBindGroupLayout(0),i=this.device.createBindGroup({layout:r,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:t}]}),s=h.beginRenderPass({colorAttachments:[{view:n,loadOp:wC,storeOp:SC,clearValue:[0,0,0,0]}]});s.setPipeline(e),s.setBindGroup(0,i),s.draw(4,1,0,0),s.end()};d(a,u,c),d(o,c,u),this.device.queue.submit([h.finish()]),l.destroy()}generateMipmaps(e,t,n=0){const r=this.get(e);void 0===r.useCount&&(r.useCount=0,r.layers=[]);const i=r.layers[n]||this._mipmapCreateBundles(e,t,n),s=this.device.createCommandEncoder({});this._mipmapRunBundles(s,i),this.device.queue.submit([s.finish()]),0!==r.useCount&&(r.layers[n]=i),r.useCount++}_mipmapCreateBundles(e,t,n){const r=this.getTransferPipeline(t.format),i=r.getBindGroupLayout(0);let s=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:cL,baseArrayLayer:n});const a=[];for(let o=1;o<t.mipLevelCount;o++){const l=this.device.createBindGroup({layout:i,entries:[{binding:0,resource:this.mipmapSampler},{binding:1,resource:s}]}),u=e.createView({baseMipLevel:o,mipLevelCount:1,dimension:cL,baseArrayLayer:n}),c={colorAttachments:[{view:u,loadOp:wC,storeOp:SC,clearValue:[0,0,0,0]}]},h=this.device.createRenderBundleEncoder({colorFormats:[t.format]});h.setPipeline(r),h.setBindGroup(0,l),h.draw(4,1,0,0),a.push({renderBundles:[h.finish()],passDescriptor:c}),s=u}return a}_mipmapRunBundles(e,t){const n=t.length;for(let r=0;r<n;r++){const n=t[r],i=e.beginRenderPass(n.passDescriptor);i.executeBundles(n.renderBundles),i.end()}}}const ML={[lt]:"never",[ut]:"less",[ct]:"equal",[ht]:"less-equal",[dt]:"greater",[ft]:"greater-equal",[mt]:"always",[pt]:"not-equal"},wL=[0,1,3,2,4,5];class EL{constructor(e){this.backend=e,this._passUtils=null,this.defaultTexture={},this.defaultCubeTexture={},this.defaultVideoFrame=null,this.colorBuffer=null,this.depthTexture=new os,this.depthTexture.name="depthBuffer"}createSampler(e){const t=this.backend,n=t.device,r=t.get(e),i={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};i.magFilter===xP&&i.minFilter===xP&&i.mipmapFilter===xP&&(i.maxAnisotropy=e.anisotropy),e.isDepthTexture&&null!==e.compareFunction&&(i.compare=ML[e.compareFunction]),r.sampler=n.createSampler(i)}createDefaultTexture(e){let t;const n=AL(e);e.isCubeTexture?t=this._getDefaultCubeTextureGPU(n):e.isVideoTexture?this.backend.get(e).externalTexture=this._getDefaultVideoFrame():t=this._getDefaultTextureGPU(n),this.backend.get(e).texture=t}createTexture(e,t={}){const n=this.backend,r=n.get(e);if(r.initialized)throw new Error("WebGPUTextureUtils: Texture already initialized.");void 0===t.needsMipmaps&&(t.needsMipmaps=!1),void 0===t.levels&&(t.levels=1),void 0===t.depth&&(t.depth=1);const{width:i,height:s,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),u=e.internalFormat||t.format||AL(e,n.device);r.format=u;const{samples:c,primarySamples:h,isMSAA:d}=n.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&&(p|=GPUTextureUsage.RENDER_ATTACHMENT);const f={label:e.name,size:{width:i,height:s,depthOrArrayLayers:a},mipLevelCount:o,sampleCount:h,dimension:l,format:u,usage:p};if(e.isVideoTexture){const t=e.source.data,n=new VideoFrame(t);f.size.width=n.displayWidth,f.size.height=n.displayHeight,n.close(),r.externalTexture=t}else{if(void 0===u)return console.warn("WebGPURenderer: Texture format not supported."),void this.createDefaultTexture(e);e.isCubeTexture&&(f.textureBindingViewDimension=dL),r.texture=n.device.createTexture(f)}if(d){const e=Object.assign({},f);e.label=e.label+"-msaa",e.sampleCount=c,r.msaaTexture=n.device.createTexture(e)}r.initialized=!0,r.textureDescriptorGPU=f}destroyTexture(e){const t=this.backend,n=t.get(e);void 0!==n.texture&&n.texture.destroy(),void 0!==n.msaaTexture&&n.msaaTexture.destroy(),t.delete(e)}destroySampler(e){delete this.backend.get(e).sampler}generateMipmaps(e){const t=this.backend.get(e);if(e.isCubeTexture)for(let e=0;e<6;e++)this._generateMipmaps(t.texture,t.textureDescriptorGPU,e);else{const n=e.image.depth||1;for(let e=0;e<n;e++)this._generateMipmaps(t.texture,t.textureDescriptorGPU,e)}}getColorBuffer(){this.colorBuffer&&this.colorBuffer.destroy();const e=this.backend,{width:t,height:n}=e.getDrawingBufferSize();return this.colorBuffer=e.device.createTexture({label:"colorBuffer",size:{width:t,height:n,depthOrArrayLayers:1},sampleCount:e.utils.getSampleCount(e.renderer.samples),format:e.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC}),this.colorBuffer}getDepthBuffer(e=!0,t=!1){const n=this.backend,{width:r,height:i}=n.getDrawingBufferSize(),s=this.depthTexture,a=n.get(s).texture;let o,l;if(t?(o=ve,l=de):e&&(o=_e,l=oe),void 0!==a){if(s.image.width===r&&s.image.height===i&&s.format===o&&s.type===l)return a;this.destroyTexture(s)}return s.name="depthBuffer",s.format=o,s.type=l,s.image.width=r,s.image.height=i,this.createTexture(s,{width:r,height:i}),n.get(s).texture}updateTexture(e,t){const n=this.backend.get(e),{textureDescriptorGPU:r}=n;if(!e.isRenderTargetTexture&&void 0!==r){if(e.isDataTexture)this._copyBufferToTexture(t.image,n.texture,r,0,e.flipY);else if(e.isArrayTexture||e.isDataArrayTexture||e.isData3DTexture)for(let i=0;i<t.image.depth;i++)this._copyBufferToTexture(t.image,n.texture,r,i,e.flipY,i);else if(e.isCompressedTexture||e.isCompressedArrayTexture)this._copyCompressedBufferToTexture(e.mipmaps,n.texture,r);else if(e.isCubeTexture)this._copyCubeMapToTexture(t.images,n.texture,r,e.flipY,e.premultiplyAlpha);else if(e.isVideoTexture){const t=e.source.data;n.externalTexture=t}else this._copyImageToTexture(t.image,n.texture,r,0,e.flipY,e.premultiplyAlpha);n.version=e.version,e.onUpdate&&e.onUpdate(e)}}async copyTextureToBuffer(e,t,n,r,i,s){const a=this.backend.device,o=this.backend.get(e),l=o.texture,u=o.textureDescriptorGPU.format,c=this._getBytesPerTexel(u);let h=r*c;h=256*Math.ceil(h/256);const d=a.createBuffer({size:r*i*c,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),p=a.createCommandEncoder();p.copyTextureToBuffer({texture:l,origin:{x:t,y:n,z:s}},{buffer:d,bytesPerRow:h},{width:r,height:i});const f=this._getTypedArrayType(u);a.queue.submit([p.finish()]),await d.mapAsync(GPUMapMode.READ);return new f(d.getMappedRange())}_getDefaultTextureGPU(e){let t=this.defaultTexture[e];if(void 0===t){const n=new sn;n.minFilter=K,n.magFilter=K,this.createTexture(n,{width:1,height:1,format:e}),this.defaultTexture[e]=t=n}return this.backend.get(t).texture}_getDefaultCubeTextureGPU(e){let t=this.defaultTexture[e];if(void 0===t){const n=new Ai;n.minFilter=K,n.magFilter=K,this.createTexture(n,{width:1,height:1,depth:6}),this.defaultCubeTexture[e]=t=n}return this.backend.get(t).texture}_getDefaultVideoFrame(){let e=this.defaultVideoFrame;if(null===e){const t={timestamp:0,codedWidth:1,codedHeight:1,format:"RGBA"};this.defaultVideoFrame=e=new VideoFrame(new Uint8Array([0,0,0,255]),t)}return e}_copyCubeMapToTexture(e,t,n,r,i){for(let s=0;s<6;s++){const a=e[s],o=!0===r?wL[s]:s;a.isDataTexture?this._copyBufferToTexture(a.image,t,n,o,r):this._copyImageToTexture(a,t,n,o,r,i)}}_copyImageToTexture(e,t,n,r,i,s){this.backend.device.queue.copyExternalImageToTexture({source:e,flipY:i},{texture:t,mipLevel:0,origin:{x:0,y:0,z:r},premultipliedAlpha:s},{width:e.width,height:e.height,depthOrArrayLayers:1})}_getPassUtils(){let e=this._passUtils;return null===e&&(this._passUtils=e=new SL(this.backend.device)),e}_generateMipmaps(e,t,n=0){this._getPassUtils().generateMipmaps(e,t,n)}_flipY(e,t,n=0){this._getPassUtils().flipY(e,t,n)}_copyBufferToTexture(e,t,n,r,i,s=0){const a=this.backend.device,o=e.data,l=this._getBytesPerTexel(n.format),u=e.width*l;a.queue.writeTexture({texture:t,mipLevel:0,origin:{x:0,y:0,z:r}},o,{offset:e.width*e.height*l*s,bytesPerRow:u},{width:e.width,height:e.height,depthOrArrayLayers:1}),!0===i&&this._flipY(t,n,r)}_copyCompressedBufferToTexture(e,t,n){const r=this.backend.device,i=this._getBlockData(n.format),s=n.size.depthOrArrayLayers>1;for(let a=0;a<e.length;a++){const o=e[a],l=o.width,u=o.height,c=s?n.size.depthOrArrayLayers:1,h=Math.ceil(l/i.width)*i.byteLength,d=h*Math.ceil(u/i.height);for(let e=0;e<c;e++)r.queue.writeTexture({texture:t,mipLevel:a,origin:{x:0,y:0,z:e}},o.data,{offset:e*d,bytesPerRow:h,rowsPerImage:Math.ceil(u/i.height)},{width:Math.ceil(l/i.width)*i.width,height:Math.ceil(u/i.height)*i.height,depthOrArrayLayers:1})}}_getBlockData(e){return e===yN||e===xN?{byteLength:8,width:4,height:4}:e===bN||e===TN||e===SN||e===MN?{byteLength:16,width:4,height:4}:e===wN||e===EN?{byteLength:8,width:4,height:4}:e===AN||e===RN||e===CN||e===NN||e===PN||e===LN?{byteLength:16,width:4,height:4}:e===DN||e===IN||e===UN||e===ON?{byteLength:8,width:4,height:4}:e===FN||e===BN?{byteLength:16,width:4,height:4}:e===kN||e===zN?{byteLength:8,width:4,height:4}:e===VN||e===GN||e===HN||e===jN?{byteLength:16,width:4,height:4}:e===WN||e===XN?{byteLength:16,width:5,height:4}:e===qN||e===$N?{byteLength:16,width:5,height:5}:e===YN||e===KN?{byteLength:16,width:6,height:5}:e===QN||e===ZN?{byteLength:16,width:6,height:6}:e===JN||e===eP?{byteLength:16,width:8,height:5}:e===tP||e===nP?{byteLength:16,width:8,height:6}:e===rP||e===iP?{byteLength:16,width:8,height:8}:e===sP||e===aP?{byteLength:16,width:10,height:5}:e===oP||e===lP?{byteLength:16,width:10,height:6}:e===uP||e===cP?{byteLength:16,width:10,height:8}:e===hP||e===dP?{byteLength:16,width:10,height:10}:e===pP||e===fP?{byteLength:16,width:12,height:10}:e===mP||e===gP?{byteLength:16,width:12,height:12}:void 0}_convertAddressMode(e){let t=_P;return e===q?t=vP:e===Y&&(t=yP),t}_convertFilterMode(e){let t=xP;return e!==K&&e!==Q&&e!==Z||(t=bP),t}_getBytesPerTexel(e){return e===LC||e===DC||e===IC||e===UC?1:e===OC||e===FC||e===BC||e===kC||e===zC||e===VC||e===GC?2:e===HC||e===jC||e===WC||e===XC||e===qC||e===$C||e===YC||e===KC||e===QC||e===ZC||e===JC||e===eN||e===tN||e===nN||e===rN||e===iN||e===_N||e===mN||e===gN||e===vN?4:e===sN||e===aN||e===oN||e===lN||e===uN||e===cN?8:e===hN||e===dN||e===pN?16:void 0}_getTypedArrayType(e){return e===IC?Uint8Array:e===UC?Int8Array:e===LC?Uint8Array:e===DC?Int8Array:e===VC?Uint8Array:e===GC?Int8Array:e===kC?Uint8Array:e===zC?Int8Array:e===ZC?Uint8Array:e===JC?Int8Array:e===YC?Uint8Array:e===QC?Int8Array:e===OC?Uint16Array:e===FC?Int16Array:e===XC?Uint16Array:e===qC?Int16Array:e===lN?Uint16Array:e===uN?Int16Array:e===BC||e===$C||e===cN?Uint16Array:e===HC?Uint32Array:e===jC?Int32Array:e===WC?Float32Array:e===sN?Uint32Array:e===aN?Int32Array:e===oN?Float32Array:e===hN?Uint32Array:e===dN?Int32Array:e===pN?Float32Array:e===eN||e===tN?Uint8Array:e===rN||e===nN||e===iN?Uint32Array:e===_N?Float32Array:e===mN||e===gN?Uint32Array:e===vN?Float32Array:void 0}_getDimension(e){let t;return t=e.is3DTexture||e.isData3DTexture?uL:lL,t}}function AL(e,t=null){const n=e.format,r=e.type,i=e.colorSpace,s=$t.getTransfer(i);let a;if(!0===e.isCompressedTexture||!0===e.isCompressedArrayTexture)switch(n){case we:a=s===at?xN:yN;break;case Ee:a=s===at?TN:bN;break;case Ae:a=s===at?MN:SN;break;case De:a=s===at?IN:DN;break;case Ie:a=s===at?BN:FN;break;case Ue:a=s===at?jN:HN;break;case Oe:a=s===at?XN:WN;break;case Fe:a=s===at?$N:qN;break;case Be:a=s===at?KN:YN;break;case ke:a=s===at?ZN:QN;break;case ze:a=s===at?eP:JN;break;case Ve:a=s===at?nP:tP;break;case Ge:a=s===at?iP:rP;break;case He:a=s===at?aP:sP;break;case je:a=s===at?lP:oP;break;case We:a=s===at?cP:uP;break;case Xe:a=s===at?dP:hP;break;case qe:a=s===at?fP:pP;break;case $e:a=s===at?gP:mP;break;case ge:a=s===at?KC:YC;break;default:console.error("WebGPURenderer: Unsupported texture format.",n)}else switch(n){case ge:switch(r){case re:a=QC;break;case ie:a=uN;break;case se:a=lN;break;case oe:a=hN;break;case ae:a=dN;break;case ne:a=s===at?KC:YC;break;case ue:a=cN;break;case le:a=pN;break;default:console.error("WebGPURenderer: Unsupported texture type with RGBAFormat.",r)}break;case me:if(r===pe)a=nN;else console.error("WebGPURenderer: Unsupported texture type with RGBFormat.",r);break;case ye:switch(r){case re:a=DC;break;case ie:a=FC;break;case se:a=OC;break;case oe:a=HC;break;case ae:a=jC;break;case ne:a=LC;break;case ue:a=BC;break;case le:a=WC;break;default:console.error("WebGPURenderer: Unsupported texture type with RedFormat.",r)}break;case be:switch(r){case re:a=zC;break;case ie:a=qC;break;case se:a=XC;break;case oe:a=sN;break;case ae:a=aN;break;case ne:a=kC;break;case ue:a=$C;break;case le:a=oN;break;default:console.error("WebGPURenderer: Unsupported texture type with RGFormat.",r)}break;case _e:switch(r){case se:a=fN;break;case oe:a=mN;break;case le:a=_N;break;default:console.error("WebGPURenderer: Unsupported texture type with DepthFormat.",r)}break;case ve:switch(r){case de:a=gN;break;case le:t&&!1===t.features.has(_L.Depth32FloatStencil8)&&console.error('WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.'),a=vN;break;default:console.error("WebGPURenderer: Unsupported texture type with DepthStencilFormat.",r)}break;case xe:switch(r){case ae:a=jC;break;case oe:a=HC;break;default:console.error("WebGPURenderer: Unsupported texture type with RedIntegerFormat.",r)}break;case Te:switch(r){case ae:a=aN;break;case oe:a=sN;break;default:console.error("WebGPURenderer: Unsupported texture type with RGIntegerFormat.",r)}break;case Se:switch(r){case ae:a=dN;break;case oe:a=hN;break;default:console.error("WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.",r)}break;default:console.error("WebGPURenderer: Unsupported texture format.",n)}return a}const RL=/^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,CL=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,NL={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 PL extends FA{constructor(e){const{type:t,inputs:n,name:r,inputsCode:i,blockCode:s,outputType:a}=(e=>{const t=(e=e.trim()).match(RL);if(null!==t&&4===t.length){const n=t[2],r=[];let i=null;for(;null!==(i=CL.exec(n));)r.push({name:i[1],type:i[2]});const s=[];for(let e=0;e<r.length;e++){const{name:t,type:n}=r[e];let i=n;i.startsWith("ptr")?i="pointer":(i.startsWith("texture")&&(i=n.split("<")[0]),i=NL[i]),s.push(new SA(i,t))}const a=e.substring(t[0].length),o=t[3]||"void",l=void 0!==t[1]?t[1]:"";return{type:NL[o]||o,inputs:s,name:l,inputsCode:n,blockCode:a,outputType:o}}throw new Error("FunctionNode: Function is not a WGSL code.")})(e);super(t,n,r),this.inputsCode=i,this.blockCode=s,this.outputType=a}getCode(e=this.name){const t="void"!==this.outputType?"-> "+this.outputType:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class LL extends OA{parseFunction(e){return new PL(e)}}const DL="undefined"!=typeof self?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},IL={[ef]:"read",[tf]:"write",[nf]:"read_write"},UL={[q]:"repeat",[$]:"clamp",[Y]:"mirror"},OL={vertex:DL?DL.VERTEX:1,fragment:DL?DL.FRAGMENT:2,compute:DL?DL.COMPUTE:4},FL={instance:!0,swizzleAssign:!1,storageBuffer:!0},BL={"^^":"tsl_xor"},kL={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>"},zL={},VL={tsl_xor:new $w("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new $w("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new $w("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new $w("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new $w("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new $w("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new $w("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new $w("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 $w("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 $w("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new $w("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 $w("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),biquadraticTexture:new $w("\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")},GL={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>"};"undefined"!=typeof navigator&&/Windows/g.test(navigator.userAgent)&&(VL.pow_float=new $w("fn tsl_pow_float( a : f32, b : f32 ) -> f32 { return select( -pow( -a, b ), pow( a, b ), a > 0.0 ); }"),VL.pow_vec2=new $w("fn tsl_pow_vec2( a : vec2f, b : vec2f ) -> vec2f { return vec2f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ) ); }",[VL.pow_float]),VL.pow_vec3=new $w("fn tsl_pow_vec3( a : vec3f, b : vec3f ) -> vec3f { return vec3f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ) ); }",[VL.pow_float]),VL.pow_vec4=new $w("fn tsl_pow_vec4( a : vec4f, b : vec4f ) -> vec4f { return vec4f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ), tsl_pow_float( a.w, b.w ) ); }",[VL.pow_float]),GL.pow_float="tsl_pow_float",GL.pow_vec2="tsl_pow_vec2",GL.pow_vec3="tsl_pow_vec3",GL.pow_vec4="tsl_pow_vec4");let HL="";!0!==("undefined"!=typeof navigator&&/Firefox|Deno/g.test(navigator.userAgent))&&(HL+="diagnostic( off, derivative_uniformity );\n");class jL extends bA{constructor(e,t){super(e,t,new LL),this.uniformGroups={},this.builtins={},this.directives={},this.scopedArrays=new Map}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==nt}_generateTextureSample(e,t,n,r,i=this.shaderStage){return"fragment"===i?r?`textureSample( ${t}, ${t}_sampler, ${n}, ${r} )`:`textureSample( ${t}, ${t}_sampler, ${n} )`:this._generateTextureSampleLevel(e,t,n,"0",r)}_generateVideoSample(e,t,n=this.shaderStage){if("fragment"===n)return`textureSampleBaseClampToEdge( ${e}, ${e}_sampler, vec2<f32>( ${t}.x, 1.0 - ${t}.y ) )`;console.error(`WebGPURenderer: THREE.VideoTexture does not support ${n} shader.`)}_generateTextureSampleLevel(e,t,n,r,i){return!1===this.isUnfilterable(e)?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${r} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,n,r):this.generateTextureLod(e,t,n,i,r)}generateWrapFunction(e){const t=`tsl_coord_${UL[e.wrapS]}S_${UL[e.wrapT]}_${e.isData3DTexture?"3d":"2d"}T`;let n=zL[t];if(void 0===n){const r=[],i=e.isData3DTexture?"vec3f":"vec2f";let s=`fn ${t}( coord : ${i} ) -> ${i} {\n\n\treturn ${i}(\n`;const a=(e,t)=>{e===q?(r.push(VL.repeatWrapping_float),s+=`\t\ttsl_repeatWrapping_float( coord.${t} )`):e===$?(r.push(VL.clampWrapping_float),s+=`\t\ttsl_clampWrapping_float( coord.${t} )`):e===Y?(r.push(VL.mirrorWrapping_float),s+=`\t\ttsl_mirrorWrapping_float( coord.${t} )`):(s+=`\t\tcoord.${t}`,console.warn(`WebGPURenderer: Unsupported texture wrap type "${e}" for vertex shader.`))};a(e.wrapS,"x"),s+=",\n",a(e.wrapT,"y"),e.isData3DTexture&&(s+=",\n",a(e.wrapR,"z")),s+="\n\t);\n\n}\n",zL[t]=n=new $w(s,r)}return n.build(this),t}generateArrayDeclaration(e,t){return`array< ${this.getType(e)}, ${t} >`}generateTextureDimension(e,t,n){const r=this.getDataFromNode(e,this.shaderStage,this.globalCache);void 0===r.dimensionsSnippet&&(r.dimensionsSnippet={});let i=r.dimensionsSnippet[n];if(void 0===r.dimensionsSnippet[n]){let s,a;const{primarySamples:o}=this.renderer.backend.utils.getTextureSampleData(e),l=o>1;a=e.isData3DTexture?"vec3<u32>":"vec2<u32>",s=l||e.isVideoTexture||e.isStorageTexture?t:`${t}${n?`, u32( ${n} )`:""}`,i=new q_(new bv(`textureDimensions( ${s} )`,a)),r.dimensionsSnippet[n]=i,(e.isArrayTexture||e.isDataArrayTexture||e.isData3DTexture)&&(r.arrayLayerCount=new q_(new bv(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(r.cubeFaceCount=new q_(new bv("6u","u32")))}return i.build(this)}generateFilteredTexture(e,t,n,r="0u"){this._include("biquadraticTexture");return`tsl_biquadraticTexture( ${t}, ${this.generateWrapFunction(e)}( ${n} ), ${this.generateTextureDimension(e,t,r)}, u32( ${r} ) )`}generateTextureLod(e,t,n,r,i="0u"){const s=this.generateWrapFunction(e),a=this.generateTextureDimension(e,t,i),o=e.isData3DTexture?"vec3":"vec2",l=`${o}<u32>( ${s}( ${n} ) * ${o}<f32>( ${a} ) )`;return this.generateTextureLoad(e,t,l,r,i)}generateTextureLoad(e,t,n,r,i="0u"){let s;return!0===e.isVideoTexture?s=`textureLoad( ${t}, ${n} )`:r?s=`textureLoad( ${t}, ${n}, ${r}, u32( ${i} ) )`:(s=`textureLoad( ${t}, ${n}, u32( ${i} ) )`,this.renderer.backend.compatibilityMode&&e.isDepthTexture&&(s+=".x")),s}generateTextureStore(e,t,n,r,i){let s;return s=r?`textureStore( ${t}, ${n}, ${r}, ${i} )`:`textureStore( ${t}, ${n}, ${i} )`,s}isSampleCompare(e){return!0===e.isDepthTexture&&null!==e.compareFunction}isUnfilterable(e){return"float"!==this.getComponentTypeFromTexture(e)||!this.isAvailable("float32Filterable")&&!0===e.isDataTexture&&e.type===le||!1===this.isSampleCompare(e)&&e.minFilter===K&&e.magFilter===K||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1}generateTexture(e,t,n,r,i=this.shaderStage){let s=null;return s=!0===e.isVideoTexture?this._generateVideoSample(t,n,i):this.isUnfilterable(e)?this.generateTextureLod(e,t,n,r,"0",i):this._generateTextureSample(e,t,n,r,i),s}generateTextureGrad(e,t,n,r,i,s=this.shaderStage){if("fragment"===s)return`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${r[0]}, ${r[1]} )`;console.error(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${s} shader.`)}generateTextureCompare(e,t,n,r,i,s=this.shaderStage){if("fragment"===s)return!0===e.isDepthTexture&&!0===e.isArrayTexture?`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${i}, ${r} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${r} )`;console.error(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${s} shader.`)}generateTextureLevel(e,t,n,r,i,s=this.shaderStage){let a=null;return a=!0===e.isVideoTexture?this._generateVideoSample(t,n,s):this._generateTextureSampleLevel(e,t,n,r,i),a}generateTextureBias(e,t,n,r,i,s=this.shaderStage){if("fragment"===s)return`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${r} )`;console.error(`WebGPURenderer: THREE.TextureNode.biasNode does not support ${s} 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,n=e.type;return"texture"===n||"cubeTexture"===n||"storageTexture"===n||"texture3D"===n?t:"buffer"===n||"storageBuffer"===n||"indirectStorageBuffer"===n?this.isCustomStruct(e)?t:t+".value":e.groupNode.name+"."+t}return super.getPropertyName(e)}getOutputStructName(){return"output"}getFunctionOperator(e){const t=BL[e];return void 0!==t?(this._include(t),t):null}getNodeAccess(e,t){return"compute"!==t?ef:e.access}getStorageAccess(e,t){return IL[this.getNodeAccess(e,t)]}getUniformFromNode(e,t,n,r=null){const i=super.getUniformFromNode(e,t,n,r),s=this.getDataFromNode(e,n,this.globalCache);if(void 0===s.uniformGPU){let a;const o=e.groupNode,l=o.name,u=this.getBindGroupArray(l,n);if("texture"===t||"cubeTexture"===t||"storageTexture"===t||"texture3D"===t){let r=null;const s=this.getNodeAccess(e,n);if("texture"===t||"storageTexture"===t?r=new NR(i.name,i.node,o,s):"cubeTexture"===t?r=new PR(i.name,i.node,o,s):"texture3D"===t&&(r=new LR(i.name,i.node,o,s)),r.store=!0===e.isStorageTextureNode,r.setVisibility(OL[n]),!1===this.isUnfilterable(e.value)&&!1===r.store){const e=new yL(`${i.name}_sampler`,i.node,o);e.setVisibility(OL[n]),u.push(e,r),a=[e,r]}else u.push(r),a=[r]}else if("buffer"===t||"storageBuffer"===t||"indirectStorageBuffer"===t){const s=new("buffer"===t?MR:TL)(e,o);s.setVisibility(OL[n]),u.push(s),a=s,i.name=r||"NodeBuffer_"+i.id}else{const e=this.uniformGroups[n]||(this.uniformGroups[n]={});let r=e[l];void 0===r&&(r=new AR(l,o),r.setVisibility(OL[n]),e[l]=r,u.push(r)),a=this.getNodeUniform(i,t),r.addUniform(a)}s.uniformGPU=a}return i}getBuiltin(e,t,n,r=this.shaderStage){const i=this.builtins[r]||(this.builtins[r]=new Map);return!1===i.has(e)&&i.set(e,{name:e,property:t,type:n}),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,n=this.flowShaderNode(e),r=[];for(const e of t.inputs)r.push(e.name+" : "+this.getType(e.type));let i=`fn ${t.name}( ${r.join(", ")} ) -> ${this.getType(t.type)} {\n${n.vars}\n${n.code}\n`;return n.result&&(i+=`\treturn ${n.result};\n`),i+="\n}\n",i}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=[],n=this.directives[e];if(void 0!==n)for(const e of n)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=[],n=this.builtins[e];if(void 0!==n)for(const{name:e,property:r,type:i}of n.values())t.push(`@builtin( ${e} ) ${r} : ${i}`);return t.join(",\n\t")}getScopedArray(e,t,n,r){return!1===this.scopedArrays.has(e)&&this.scopedArrays.set(e,{name:e,scope:t,bufferType:n,bufferCount:r}),e}getScopedArrays(e){if("compute"!==e)return;const t=[];for(const{name:e,scope:n,bufferType:r,bufferCount:i}of this.scopedArrays.values()){const s=this.getType(r);t.push(`var<${n}> ${e}: array< ${s}, ${i} >;`)}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 n=this.getAttributesArray();for(let e=0,r=n.length;e<r;e++){const r=n[e],i=r.name,s=this.getType(r.type);t.push(`@location( ${e} ) ${i} : ${s}`)}}return t.join(",\n\t")}getStructMembers(e){const t=[];for(const n of e.members){const r=e.output?"@location( "+n.index+" ) ":"";let i=this.getType(n.type);n.atomic&&(i="atomic< "+i+" >"),t.push(`\t${r+n.name} : ${i}`)}return e.output&&t.push(`\t${this.getBuiltins("output")}`),t.join(",\n")}getStructs(e){let t="";const n=this.structs[e];if(n.length>0){const e=[];for(const t of n){let n=`struct ${t.name} {\n`;n+=this.getStructMembers(t),n+="\n};",e.push(n)}t="\n"+e.join("\n\n")+"\n"}return t}getVar(e,t,n=null){let r=`var ${t} : `;return r+=null!==n?this.generateArrayDeclaration(e,n):this.getType(e),r}getVars(e){const t=[],n=this.vars[e];if(void 0!==n)for(const e of n)t.push(`\t${this.getVar(e.type,e.name,e.count)};`);return`\n${t.join("\n")}\n`}getVaryings(e){const t=[];if("vertex"===e&&this.getBuiltin("position","Vertex","vec4<f32>","vertex"),"vertex"===e||"fragment"===e){const n=this.varyings,r=this.vars[e];for(let i=0;i<n.length;i++){const s=n[i];if(s.needsInterpolation){let e=`@location( ${i} )`;if(s.interpolationType){const t=null!==s.interpolationSampling?`, ${s.interpolationSampling} )`:" )";e+=` @interpolate( ${s.interpolationType}${t}`}else/^(int|uint|ivec|uvec)/.test(s.type)&&(e+=` @interpolate( ${this.renderer.backend.compatibilityMode?"flat, either":"flat"} )`);t.push(`${e} ${s.name} : ${this.getType(s.type)}`)}else"vertex"===e&&!1===r.includes(s)&&r.push(s)}}const n=this.getBuiltins(e);n&&t.push(n);const r=t.join(",\n\t");return"vertex"===e?this._getWGSLStruct("VaryingsStruct","\t"+r):r}isCustomStruct(e){const t=e.value,n=e.node,r=(t.isBufferAttribute||t.isInstancedBufferAttribute)&&null!==n.structTypeNode,i=n.value&&n.value.array&&"number"==typeof n.value.itemSize&&n.value.array.length>n.value.itemSize;return r&&!i}getUniforms(e){const t=this.uniforms[e],n=[],r=[],i=[],s={};for(const i of t){const t=i.groupNode.name,a=this.bindingsIndexes[t];if("texture"===i.type||"cubeTexture"===i.type||"storageTexture"===i.type||"texture3D"===i.type){const t=i.node.value;let r;!1===this.isUnfilterable(t)&&!0!==i.node.isStorageTextureNode&&(this.isSampleCompare(t)?n.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var ${i.name}_sampler : sampler_comparison;`):n.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var ${i.name}_sampler : sampler;`));let s="";const{primarySamples:o}=this.renderer.backend.utils.getTextureSampleData(t);if(o>1&&(s="_multisampled"),!0===t.isCubeTexture)r="texture_cube<f32>";else if(!0===t.isDepthTexture)r=this.renderer.backend.compatibilityMode&&null===t.compareFunction?`texture${s}_2d<f32>`:`texture_depth${s}_2d${!0===t.isArrayTexture?"_array":""}`;else if(!0===i.node.isStorageTextureNode){const n=AL(t),s=this.getStorageAccess(i.node,e),a=i.node.value.is3DTexture,o=i.node.value.isArrayTexture;r=`texture_storage_${a?"3d":"2d"+(o?"_array":"")}<${n}, ${s}>`}else if(!0===t.isArrayTexture||!0===t.isDataArrayTexture||!0===t.isCompressedArrayTexture)r="texture_2d_array<f32>";else if(!0===t.is3DTexture||!0===t.isData3DTexture)r="texture_3d<f32>";else if(!0===t.isVideoTexture)r="texture_external";else{r=`texture${s}_2d<${this.getComponentTypeFromTexture(t).charAt(0)}32>`}n.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var ${i.name} : ${r};`)}else if("buffer"===i.type||"storageBuffer"===i.type||"indirectStorageBuffer"===i.type){const t=i.node,n=this.getType(t.getNodeType(this)),s=t.bufferCount,o=s>0&&"buffer"===i.type?", "+s:"",l=t.isStorageBufferNode?`storage, ${this.getStorageAccess(t,e)}`:"uniform";if(this.isCustomStruct(i))r.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var<${l}> ${i.name} : ${n};`);else{const e=`\tvalue : array< ${t.isAtomic?`atomic<${n}>`:`${n}`}${o} >`;r.push(this._getWGSLStructBinding(i.name,e,l,a.binding++,a.group))}}else{const e=this.getType(this.getVectorType(i.type)),t=i.groupNode.name;(s[t]||(s[t]={index:a.binding++,id:a.group,snippets:[]})).snippets.push(`\t${i.name} : ${e}`)}}for(const e in s){const t=s[e];i.push(this._getWGSLStructBinding(e,t.snippets.join(",\n"),"uniform",t.index,t.id))}let a=n.join("\n");return a+=r.join("\n"),a+=i.join("\n"),a}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){this.shaderStage=t;const n=e[t];n.uniforms=this.getUniforms(t),n.attributes=this.getAttributes(t),n.varyings=this.getVaryings(t),n.structs=this.getStructs(t),n.vars=this.getVars(t),n.codes=this.getCodes(t),n.directives=this.getDirectives(t),n.scopedArrays=this.getScopedArrays(t);let r="// code\n\n";r+=this.flowCode[t];const i=this.flowNodes[t],s=i[i.length-1],a=s.outputNode,o=void 0!==a&&!0===a.isOutputStructNode;for(const e of i){const i=this.getFlowData(e),l=e.name;if(l&&(r.length>0&&(r+="\n"),r+=`\t// flow -> ${l}\n`),r+=`${i.code}\n\t`,e===s&&"compute"!==t)if(r+="// result\n\n\t","vertex"===t)r+=`varyings.Vertex = ${i.result};`;else if("fragment"===t)if(o)n.returnType=a.getNodeType(this),n.structs+="var<private> output : "+n.returnType+";",r+=`return ${i.result};`;else{let e="\t@location(0) color: vec4<f32>";const t=this.getBuiltins("output");t&&(e+=",\n\t"+t),n.returnType="OutputStruct",n.structs+=this._getWGSLStruct("OutputStruct",e),n.structs+="\nvar<private> output : OutputStruct;",r+=`output.color = ${i.result};\n\n\treturn output;`}}n.flow=r}this.shaderStage=null,null!==this.material?(this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment)):this.computeShader=this._getWGSLComputeCode(e.compute,(this.object.workgroupSize||[64]).join(", "))}getMethod(e,t=null){let n;return null!==t&&(n=this._getWGSLMethod(e+"_"+t)),void 0===n&&(n=this._getWGSLMethod(e)),n||e}getType(e){return kL[e]||e}isAvailable(e){let t=FL[e];return void 0===t&&("float32Filterable"===e?t=this.renderer.hasFeature("float32-filterable"):"clipDistance"===e&&(t=this.renderer.hasFeature("clip-distances")),FL[e]=t),t}_getWGSLMethod(e){return void 0!==VL[e]&&this._include(e),GL[e]}_include(e){const t=VL[e];return t.build(this),null!==this.currentFunctionNode&&this.currentFunctionNode.includes.push(t),t}_getWGSLVertexCode(e){return`${this.getSignature()}\n// directives\n${e.directives}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\nvar<private> varyings : VaryingsStruct;\n\n// codes\n${e.codes}\n\n@vertex\nfn main( ${e.attributes} ) -> VaryingsStruct {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n\treturn varyings;\n\n}\n`}_getWGSLFragmentCode(e){return`${this.getSignature()}\n// global\n${HL}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@fragment\nfn main( ${e.varyings} ) -> ${e.returnType} {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLComputeCode(e,t){return`${this.getSignature()}\n// directives\n${e.directives}\n\n// system\nvar<private> instanceIndex : u32;\n\n// locals\n${e.scopedArrays}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@compute @workgroup_size( ${t} )\nfn main( ${e.attributes} ) {\n\n\t// system\n\tinstanceIndex = globalId.x + globalId.y * numWorkgroups.x * u32(${t}) + globalId.z * numWorkgroups.x * numWorkgroups.y * u32(${t});\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLStruct(e,t){return`\nstruct ${e} {\n${t}\n};`}_getWGSLStructBinding(e,t,n,r=0,i=0){const s=e+"Struct";return`${this._getWGSLStruct(s,t)}\n@binding( ${r} ) @group( ${i} )\nvar<${n}> ${e} : ${s};`}}class WL{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return null!==e.depthTexture?t=this.getTextureFormatGPU(e.depthTexture):e.depth&&e.stencil?t=gN:e.depth&&(t=mN),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,n=e.getRenderTarget();t=n?n.samples:e.samples}else e.renderTarget&&(t=e.renderTarget.samples);t=t||1;const n=t>1&&null!==e.renderTarget&&!0!==e.isDepthTexture&&!0!==e.isFramebufferTexture;return{samples:t,primarySamples:n?1:t,isMSAA:n}}getCurrentColorFormat(e){let t;return t=null!==e.textures?this.getTextureFormatGPU(e.textures[0]):this.getPreferredCanvasFormat(),t}getCurrentColorSpace(e){return null!==e.textures?e.textures[0].colorSpace:this.backend.renderer.outputColorSpace}getPrimitiveTopology(e,t){return e.isPoints?cC:e.isLineSegments||e.isMesh&&!0===t.wireframe?hC:e.isLine?dC:e.isMesh?pC:void 0}getSampleCount(e){let t=1;return e>1&&(t=Math.pow(2,Math.floor(Math.log2(e))),2===t&&(t=4)),t}getSampleCountRenderContext(e){return null!==e.textures?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.samples)}getPreferredCanvasFormat(){const e=this.backend.parameters.outputType;if(void 0===e)return navigator.gpu.getPreferredCanvasFormat();if(e===ne)return eN;if(e===ue)return cN;throw new Error("Unsupported outputType")}}const XL=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&&XL.set(Float16Array,["float16"]);const qL=new Map([[Wr,["float16"]]]),$L=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class YL{constructor(e){this.backend=e}createAttribute(e,t){const n=this._getBufferAttribute(e),r=this.backend,i=r.get(n);let s=i.buffer;if(void 0===s){const a=r.device;let o=n.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(n.array=o,(n.isStorageBufferAttribute||n.isStorageInstancedBufferAttribute)&&3===n.itemSize){o=new o.constructor(4*n.count);for(let e=0;e<n.count;e++)o.set(n.array.subarray(3*e,3*e+3),4*e);n.itemSize=4,n.array=o,i._force3to4BytesAlignment=!0}const l=o.byteLength,u=l+(4-l%4)%4;s=a.createBuffer({label:n.name,size:u,usage:t,mappedAtCreation:!0}),new o.constructor(s.getMappedRange()).set(o),s.unmap(),i.buffer=s}}updateAttribute(e){const t=this._getBufferAttribute(e),n=this.backend,r=n.device,i=n.get(t),s=n.get(t).buffer;let a=t.array;if(!0===i._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=this._isTypedArray(a),l=t.updateRanges;if(0===l.length)r.queue.writeBuffer(s,0,a,0);else{const e=o?1:a.BYTES_PER_ELEMENT;for(let t=0,n=l.length;t<n;t++){const n=l[t];let u,c;if(!0===i._force3to4BytesAlignment){u=4*Math.floor(n.start/3)*e,c=4*Math.ceil(n.count/3)*e}else u=n.start*e,c=n.count*e;const h=u*(o?a.BYTES_PER_ELEMENT:1);r.queue.writeBuffer(s,h,a,u,c)}t.clearUpdateRanges()}}createShaderVertexBuffers(e){const t=e.getAttributes(),n=new Map;for(let e=0;e<t.length;e++){const r=t[e],i=r.array.BYTES_PER_ELEMENT,s=this._getBufferAttribute(r);let a=n.get(s);if(void 0===a){let e,t;!0===r.isInterleavedBufferAttribute?(e=r.data.stride*i,t=r.data.isInstancedInterleavedBuffer?gL:mL):(e=r.itemSize*i,t=r.isInstancedBufferAttribute?gL:mL),!1!==r.normalized||r.array.constructor!==Int16Array&&r.array.constructor!==Uint16Array||(e=4),a={arrayStride:e,attributes:[],stepMode:t},n.set(s,a)}const o=this._getVertexFormat(r),l=!0===r.isInterleavedBufferAttribute?r.offset*i:0;a.attributes.push({shaderLocation:e,offset:l,format:o})}return Array.from(n.values())}destroyAttribute(e){const t=this.backend;t.get(this._getBufferAttribute(e)).buffer.destroy(),t.delete(e)}async getArrayBufferAsync(e){const t=this.backend,n=t.device,r=t.get(this._getBufferAttribute(e)).buffer,i=r.size,s=n.createBuffer({label:`${e.name}_readback`,size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),a=n.createCommandEncoder({label:`readback_encoder_${e.name}`});a.copyBufferToBuffer(r,0,s,0,i);const o=a.finish();n.queue.submit([o]),await s.mapAsync(GPUMapMode.READ);const l=s.getMappedRange(),u=new e.array.constructor(l.slice(0));return s.unmap(),u.buffer}_getVertexFormat(e){const{itemSize:t,normalized:n}=e,r=e.array.constructor,i=e.constructor;let s;if(1===t)s=$L.get(r);else{const e=(qL.get(i)||XL.get(r))[n?1:0];if(e){const n=r.BYTES_PER_ELEMENT*t,i=4*Math.floor((n+3)/4)/r.BYTES_PER_ELEMENT;if(i%1)throw new Error("THREE.WebGPUAttributeUtils: Bad vertex format item size.");s=`${e}x${i}`}}return s||console.error("THREE.WebGPUAttributeUtils: Vertex format not supported yet."),s}_isTypedArray(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}class KL{constructor(e){this.backend=e,this.bindGroupLayoutCache=new WeakMap}createBindingsLayout(e){const t=this.backend,n=t.device,r=[];let i=0;for(const n of e.bindings){const e={binding:i++,visibility:n.visibility};if(n.isUniformBuffer||n.isStorageBuffer){const t={};n.isStorageBuffer&&(4&n.visibility&&(n.access===nf||n.access===tf)?t.type=KP:t.type=QP),e.buffer=t}else if(n.isSampler){const r={};n.texture.isDepthTexture&&(null!==n.texture.compareFunction?r.type=nL:t.compatibilityMode&&(r.type=tL)),e.sampler=r}else if(n.isSampledTexture&&n.texture.isVideoTexture)e.externalTexture={};else if(n.isSampledTexture&&n.store){const t={};t.format=this.backend.get(n.texture).texture.format;const r=n.access;t.access=r===nf?eL:r===tf?ZP:JP,n.texture.isArrayTexture?t.viewDimension=hL:n.texture.is3DTexture&&(t.viewDimension=pL),e.storageTexture=t}else if(n.isSampledTexture){const r={},{primarySamples:i}=t.utils.getTextureSampleData(n.texture);if(i>1&&(r.multisampled=!0,n.texture.isDepthTexture||(r.sampleType=iL)),n.texture.isDepthTexture)t.compatibilityMode&&null===n.texture.compareFunction?r.sampleType=iL:r.sampleType=sL;else if(n.texture.isDataTexture||n.texture.isDataArrayTexture||n.texture.isData3DTexture){const e=n.texture.type;e===ae?r.sampleType=aL:e===oe?r.sampleType=oL:e===le&&(this.backend.hasFeature("float32-filterable")?r.sampleType=rL:r.sampleType=iL)}n.isSampledCubeTexture?r.viewDimension=dL:n.texture.isArrayTexture||n.texture.isDataArrayTexture||n.texture.isCompressedArrayTexture?r.viewDimension=hL:n.isSampledTexture3D&&(r.viewDimension=pL),e.texture=r}else console.error(`WebGPUBindingUtils: Unsupported binding "${n}".`);r.push(e)}return n.createBindGroupLayout({entries:r})}createBindings(e,t,n,r=0){const{backend:i,bindGroupLayoutCache:s}=this,a=i.get(e);let o,l=s.get(e.bindingsReference);void 0===l&&(l=this.createBindingsLayout(e),s.set(e.bindingsReference,l)),n>0&&(void 0===a.groups&&(a.groups=[],a.versions=[]),a.versions[n]===r&&(o=a.groups[n])),void 0===o&&(o=this.createBindGroup(e,l),n>0&&(a.groups[n]=o,a.versions[n]=r)),a.group=o,a.layout=l}updateBinding(e){const t=this.backend,n=t.device,r=e.buffer,i=t.get(e).buffer;n.queue.writeBuffer(i,0,r,0)}createBindGroupIndex(e,t){const n=this.backend.device,r=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,i=e[0],s=n.createBuffer({label:"bindingCameraIndex_"+i,size:16,usage:r});n.queue.writeBuffer(s,0,e,0);const a=[{binding:0,resource:{buffer:s}}];return n.createBindGroup({label:"bindGroupCameraIndex_"+i,layout:t,entries:a})}createBindGroup(e,t){const n=this.backend,r=n.device;let i=0;const s=[];for(const t of e.bindings){if(t.isUniformBuffer){const e=n.get(t);if(void 0===e.buffer){const n=t.byteLength,i=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,s=r.createBuffer({label:"bindingBuffer_"+t.name,size:n,usage:i});e.buffer=s}s.push({binding:i,resource:{buffer:e.buffer}})}else if(t.isStorageBuffer){const e=n.get(t);if(void 0===e.buffer){const r=t.attribute;e.buffer=n.get(r).buffer}s.push({binding:i,resource:{buffer:e.buffer}})}else if(t.isSampler){const e=n.get(t.texture);s.push({binding:i,resource:e.sampler})}else if(t.isSampledTexture){const e=n.get(t.texture);let a;if(void 0!==e.externalTexture)a=r.importExternalTexture({source:e.externalTexture});else{const n=t.store?1:e.texture.mipLevelCount,r=`view-${e.texture.width}-${e.texture.height}-${n}`;if(a=e[r],void 0===a){const i=fL;let s;s=t.isSampledCubeTexture?dL:t.isSampledTexture3D?pL:t.texture.isArrayTexture||t.texture.isDataArrayTexture||t.texture.isCompressedArrayTexture?hL:cL,a=e[r]=e.texture.createView({aspect:i,dimension:s,mipLevelCount:n})}}s.push({binding:i,resource:a})}i++}return r.createBindGroup({label:"bindGroup_"+e.name,layout:t,entries:s})}}class QL{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:n,material:r,geometry:i,pipeline:s}=e,{vertexProgram:a,fragmentProgram:o}=s,l=this.backend,u=l.device,c=l.utils,h=l.get(s),d=[];for(const t of e.getBindings()){const e=l.get(t);d.push(e.layout)}const p=l.attributeUtils.createShaderVertexBuffers(e);let f;0===r.blending||1===r.blending&&!1===r.transparent||(f=this._getBlending(r));let m={};!0===r.stencilWrite&&(m={compare:this._getStencilCompare(r),failOp:this._getStencilOperation(r.stencilFail),depthFailOp:this._getStencilOperation(r.stencilZFail),passOp:this._getStencilOperation(r.stencilZPass)});const g=this._getColorWriteMask(r),_=[];if(null!==e.context.textures){const t=e.context.textures;for(let e=0;e<t.length;e++){const n=c.getTextureFormatGPU(t[e]);_.push({format:n,blend:f,writeMask:g})}}else{const t=c.getCurrentColorFormat(e.context);_.push({format:t,blend:f,writeMask:g})}const v=l.get(a).module,y=l.get(o).module,x=this._getPrimitiveState(n,i,r),b=this._getDepthCompare(r),T=c.getCurrentDepthStencilFormat(e.context),S=this._getSampleCount(e.context),M={label:`renderPipeline_${r.name||r.type}_${r.id}`,vertex:Object.assign({},v,{buffers:p}),fragment:Object.assign({},y,{targets:_}),primitive:x,multisample:{count:S,alphaToCoverageEnabled:r.alphaToCoverage&&S>1},layout:u.createPipelineLayout({bindGroupLayouts:d})},w={},E=e.context.depth,A=e.context.stencil;if(!0!==E&&!0!==A||(!0===E&&(w.format=T,w.depthWriteEnabled=r.depthWrite,w.depthCompare=b),!0===A&&(w.stencilFront=m,w.stencilBack={},w.stencilReadMask=r.stencilFuncMask,w.stencilWriteMask=r.stencilWriteMask),!0===r.polygonOffset&&(w.depthBias=r.polygonOffsetUnits,w.depthBiasSlopeScale=r.polygonOffsetFactor,w.depthBiasClamp=0),M.depthStencil=w),null===t)h.pipeline=u.createRenderPipeline(M);else{const e=new Promise(e=>{u.createRenderPipelineAsync(M).then(t=>{h.pipeline=t,e()})});t.push(e)}}createBundleEncoder(e,t="renderBundleEncoder"){const n=this.backend,{utils:r,device:i}=n,s=r.getCurrentDepthStencilFormat(e),a={label:t,colorFormats:[r.getCurrentColorFormat(e)],depthStencilFormat:s,sampleCount:this._getSampleCount(e)};return i.createRenderBundleEncoder(a)}createComputePipeline(e,t){const n=this.backend,r=n.device,i=n.get(e.computeProgram).module,s=n.get(e),a=[];for(const e of t){const t=n.get(e);a.push(t.layout)}s.pipeline=r.createComputePipeline({compute:i,layout:r.createPipelineLayout({bindGroupLayouts:a})})}_getBlending(e){let t,n;const r=e.blending,i=e.blendSrc,s=e.blendDst,a=e.blendEquation;if(5===r){const r=null!==e.blendSrcAlpha?e.blendSrcAlpha:i,o=null!==e.blendDstAlpha?e.blendDstAlpha:s,l=null!==e.blendEquationAlpha?e.blendEquationAlpha:a;t={srcFactor:this._getBlendFactor(i),dstFactor:this._getBlendFactor(s),operation:this._getBlendOperation(a)},n={srcFactor:this._getBlendFactor(r),dstFactor:this._getBlendFactor(o),operation:this._getBlendOperation(l)}}else{const i=(e,r,i,s)=>{t={srcFactor:e,dstFactor:r,operation:UP},n={srcFactor:i,dstFactor:s,operation:UP}};if(e.premultipliedAlpha)switch(r){case 1:i(SP,AP,SP,AP);break;case 2:i(SP,SP,SP,SP);break;case 3:i(TP,wP,TP,SP);break;case 4:i(RP,AP,TP,SP)}else switch(r){case 1:i(EP,AP,SP,AP);break;case 2:i(EP,SP,SP,SP);break;case 3:console.error("THREE.WebGPURenderer: SubtractiveBlending requires material.premultipliedAlpha = true");break;case 4:console.error("THREE.WebGPURenderer: MultiplyBlending requires material.premultipliedAlpha = true")}}if(void 0!==t&&void 0!==n)return{color:t,alpha:n};console.error("THREE.WebGPURenderer: Invalid blending: ",r)}_getBlendFactor(e){let t;switch(e){case y:t=TP;break;case 201:t=SP;break;case 202:t=MP;break;case 203:t=wP;break;case S:t=EP;break;case M:t=AP;break;case 208:t=RP;break;case 209:t=CP;break;case 206:t=NP;break;case 207:t=PP;break;case 210:t=LP;break;case 211:t=DP;break;case 212:t=IP;break;default:console.error("THREE.WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const n=e.stencilFunc;switch(n){case 512:t=mC;break;case 519:t=TC;break;case 513:t=gC;break;case 515:t=vC;break;case 514:t=_C;break;case 518:t=bC;break;case 516:t=yC;break;case 517:t=xC;break;default:console.error("THREE.WebGPURenderer: Invalid stencil function.",n)}return t}_getStencilOperation(e){let t;switch(e){case ot:t=GP;break;case 0:t=HP;break;case 7681:t=jP;break;case 5386:t=WP;break;case 7682:t=XP;break;case 7683:t=qP;break;case 34055:t=$P;break;case 34056:t=YP;break;default:console.error("THREE.WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case g:t=UP;break;case 101:t=OP;break;case 102:t=FP;break;case 103:t=BP;break;case 104:t=kP;break;default:console.error("THREE.WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,n){const r={},i=this.backend.utils;switch(r.topology=i.getPrimitiveTopology(e,n),null!==t.index&&!0===e.isLine&&!0!==e.isLineSegments&&(r.stripIndexFormat=t.index.array instanceof Uint16Array?NC:PC),n.side){case 0:r.frontFace=EC,r.cullMode=CC;break;case 1:r.frontFace=EC,r.cullMode=RC;break;case 2:r.frontFace=EC,r.cullMode=AC;break;default:console.error("THREE.WebGPUPipelineUtils: Unknown material.side value.",n.side)}return r}_getColorWriteMask(e){return!0===e.colorWrite?VP:zP}_getDepthCompare(e){let t;if(!1===e.depthTest)t=TC;else{const n=e.depthFunc;switch(n){case 0:t=mC;break;case 1:t=TC;break;case 2:t=gC;break;case 3:t=vC;break;case 4:t=_C;break;case 5:t=bC;break;case 6:t=yC;break;case 7:t=xC;break;default:console.error("THREE.WebGPUPipelineUtils: Invalid depth function.",n)}}return t}}class ZL extends aC{constructor(e,t,n=2048){super(n),this.device=e,this.type=t,this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxQueries,label:`queryset_global_timestamp_${t}`});const r=8*this.maxQueries;this.resolveBuffer=this.device.createBuffer({label:`buffer_timestamp_resolve_${t}`,size:r,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.resultBuffer=this.device.createBuffer({label:`buffer_timestamp_result_${t}`,size:r,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ})}allocateQueriesForContext(e){if(!this.trackTimestamp||this.isDisposed)return null;if(this.currentQueryIndex+2>this.maxQueries)return jt(`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.id,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,n=8*t;this.currentQueryIndex=0,this.queryOffsets.clear();const r=this.device.createCommandEncoder();r.resolveQuerySet(this.querySet,0,t,this.resolveBuffer,0),r.copyBufferToBuffer(this.resolveBuffer,0,this.resultBuffer,0,n);const i=r.finish();if(this.device.queue.submit([i]),"unmapped"!==this.resultBuffer.mapState)return this.lastValue;if(await this.resultBuffer.mapAsync(GPUMapMode.READ,0,n),this.isDisposed)return"mapped"===this.resultBuffer.mapState&&this.resultBuffer.unmap(),this.lastValue;const s=new BigUint64Array(this.resultBuffer.getMappedRange(0,n));let a=0;for(const[,t]of e){const e=s[t],n=s[t+1];a+=Number(n-e)/1e6}return this.resultBuffer.unmap(),this.lastValue=a,a}catch(e){return console.error("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){console.error("Error waiting for pending resolve:",e)}if(this.resultBuffer&&"mapped"===this.resultBuffer.mapState)try{this.resultBuffer.unmap()}catch(e){console.error("Error unmapping buffer:",e)}this.querySet&&(this.querySet.destroy(),this.querySet=null),this.resolveBuffer&&(this.resolveBuffer.destroy(),this.resolveBuffer=null),this.resultBuffer&&(this.resultBuffer.destroy(),this.resultBuffer=null),this.queryOffsets.clear(),this.pendingResolve=null}}}class JL extends GR{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=void 0===e.alpha||e.alpha,this.parameters.compatibilityMode=void 0!==e.compatibilityMode&&e.compatibilityMode,this.parameters.requiredLimits=void 0===e.requiredLimits?{}:e.requiredLimits,this.compatibilityMode=this.parameters.compatibilityMode,this.device=null,this.context=null,this.colorBuffer=null,this.defaultRenderPassdescriptor=null,this.utils=new WL(this),this.attributeUtils=new YL(this),this.bindingUtils=new KL(this),this.pipelineUtils=new QL(this),this.textureUtils=new EL(this),this.occludedResolveCache=new Map}async init(e){await super.init(e);const t=this.parameters;let n;if(void 0===t.device){const e={powerPreference:t.powerPreference,featureLevel:t.compatibilityMode?"compatibility":void 0},r="undefined"!=typeof navigator?await navigator.gpu.requestAdapter(e):null;if(null===r)throw new Error("WebGPUBackend: Unable to create WebGPU adapter.");const i=Object.values(_L),s=[];for(const e of i)r.features.has(e)&&s.push(e);const a={requiredFeatures:s,requiredLimits:t.requiredLimits};n=await r.requestDevice(a)}else n=t.device;n.lost.then(t=>{const n={api:"WebGPU",message:t.message||"Unknown reason",reason:t.reason||null,originalEvent:t};e.onDeviceLost(n)});const r=void 0!==t.context?t.context:e.domElement.getContext("webgpu");this.device=n,this.context=r;const i=t.alpha?"premultiplied":"opaque";this.trackTimestamp=this.trackTimestamp&&this.hasFeature(_L.TimestampQuery),this.context.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:i}),this.updateSize()}get coordinateSystem(){return xt}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){let e=this.defaultRenderPassdescriptor;if(null===e){const t=this.renderer;e={colorAttachments:[{view:null}]},!0!==this.renderer.depth&&!0!==this.renderer.stencil||(e.depthStencilAttachment={view:this.textureUtils.getDepthBuffer(t.depth,t.stencil).createView()});const n=e.colorAttachments[0];this.renderer.samples>0?n.view=this.colorBuffer.createView():n.resolveTarget=void 0,this.defaultRenderPassdescriptor=e}const t=e.colorAttachments[0];return this.renderer.samples>0?t.resolveTarget=this.context.getCurrentTexture().createView():t.view=this.context.getCurrentTexture().createView(),e}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.image.depth>1&&e.camera.isArrayCamera}_getRenderPassDescriptor(e,t={}){const n=e.renderTarget,r=this.get(n);let i=r.descriptors;if(void 0===i||r.width!==n.width||r.height!==n.height||r.dimensions!==n.dimensions||r.activeMipmapLevel!==e.activeMipmapLevel||r.activeCubeFace!==e.activeCubeFace||r.samples!==n.samples){i={},r.descriptors=i;const e=()=>{n.removeEventListener("dispose",e),this.delete(n)};!1===n.hasEventListener("dispose",e)&&n.addEventListener("dispose",e)}const s=e.getCacheKey();let a=i[s];if(void 0===a){const t=e.textures,o=[];let l;const u=this._isRenderCameraDepthArray(e);for(let r=0;r<t.length;r++){const i=this.get(t[r]),s={label:`colorAttachment_${r}`,baseMipLevel:e.activeMipmapLevel,mipLevelCount:1,baseArrayLayer:e.activeCubeFace,arrayLayerCount:1,dimension:cL};if(n.isRenderTarget3D)l=e.activeCubeFace,s.baseArrayLayer=0,s.dimension=pL,s.depthOrArrayLayers=t[r].image.depth;else if(n.isRenderTarget&&t[r].image.depth>1)if(!0===u){const t=e.camera.cameras;for(let e=0;e<t.length;e++){const t={...s,baseArrayLayer:e,arrayLayerCount:1,dimension:cL},n=i.texture.createView(t);o.push({view:n,resolveTarget:void 0,depthSlice:void 0})}}else s.dimension=hL,s.depthOrArrayLayers=t[r].image.depth;if(!0!==u){const e=i.texture.createView(s);let t,n;void 0!==i.msaaTexture?(t=i.msaaTexture.createView(),n=e):(t=e,n=void 0),o.push({view:t,resolveTarget:n,depthSlice:l})}}if(a={textureViews:o},e.depth){const t=this.get(e.depthTexture),n={};e.depthTexture.isArrayTexture&&(n.dimension=cL,n.arrayLayerCount=1,n.baseArrayLayer=e.activeCubeFace),a.depthStencilView=t.texture.createView(n)}i[s]=a,r.width=n.width,r.height=n.height,r.samples=n.samples,r.activeMipmapLevel=e.activeMipmapLevel,r.activeCubeFace=e.activeCubeFace,r.dimensions=n.dimensions}const o={colorAttachments:[]};for(let e=0;e<a.textureViews.length;e++){const n=a.textureViews[e];let r={r:0,g:0,b:0,a:1};0===e&&t.clearValue&&(r=t.clearValue),o.colorAttachments.push({view:n.view,depthSlice:n.depthSlice,resolveTarget:n.resolveTarget,loadOp:t.loadOp||MC,storeOp:t.storeOp||SC,clearValue:r})}return a.depthStencilView&&(o.depthStencilAttachment={view:a.depthStencilView}),o}beginRender(e){const t=this.get(e),n=this.device,r=e.occlusionQueryCount;let i,s;r>0&&(t.currentOcclusionQuerySet&&t.currentOcclusionQuerySet.destroy(),t.currentOcclusionQueryBuffer&&t.currentOcclusionQueryBuffer.destroy(),t.currentOcclusionQuerySet=t.occlusionQuerySet,t.currentOcclusionQueryBuffer=t.occlusionQueryBuffer,t.currentOcclusionQueryObjects=t.occlusionQueryObjects,i=n.createQuerySet({type:"occlusion",count:r,label:`occlusionQuerySet_${e.id}`}),t.occlusionQuerySet=i,t.occlusionQueryIndex=0,t.occlusionQueryObjects=new Array(r),t.lastOcclusionObject=null),s=null===e.textures?this._getDefaultRenderPassDescriptor():this._getRenderPassDescriptor(e,{loadOp:MC}),this.initTimestampQuery(e,s),s.occlusionQuerySet=i;const a=s.depthStencilAttachment;if(null!==e.textures){const t=s.colorAttachments;for(let n=0;n<t.length;n++){const r=t[n];e.clearColor?(r.clearValue=0===n?e.clearColorValue:{r:0,g:0,b:0,a:1},r.loadOp=wC):r.loadOp=MC,r.storeOp=SC}}else{const t=s.colorAttachments[0];e.clearColor?(t.clearValue=e.clearColorValue,t.loadOp=wC):t.loadOp=MC,t.storeOp=SC}e.depth&&(e.clearDepth?(a.depthClearValue=e.clearDepthValue,a.depthLoadOp=wC):a.depthLoadOp=MC,a.depthStoreOp=SC),e.stencil&&(e.clearStencil?(a.stencilClearValue=e.clearStencilValue,a.stencilLoadOp=wC):a.stencilLoadOp=MC,a.stencilStoreOp=SC);const o=n.createCommandEncoder({label:"renderContext_"+e.id});if(!0===this._isRenderCameraDepthArray(e)){const n=e.camera.cameras;t.layerDescriptors&&t.layerDescriptors.length===n.length?this._updateDepthLayerDescriptors(e,t,n):this._createDepthLayerDescriptors(e,t,s,n),t.bundleEncoders=[],t.bundleSets=[];for(let r=0;r<n.length;r++){const n=this.pipelineUtils.createBundleEncoder(e,"renderBundleArrayCamera_"+r),i={attributes:{},bindingGroups:[],pipeline:null,index:null};t.bundleEncoders.push(n),t.bundleSets.push(i)}t.currentPass=null}else{const n=o.beginRenderPass(s);if(t.currentPass=n,e.viewport&&this.updateViewport(e),e.scissor){const{x:t,y:r,width:i,height:s}=e.scissorValue;n.setScissorRect(t,r,i,s)}}t.descriptor=s,t.encoder=o,t.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.renderBundles=[]}_createDepthLayerDescriptors(e,t,n,r){const i=n.depthStencilAttachment;t.layerDescriptors=[];const s=this.get(e.depthTexture);s.viewCache||(s.viewCache=[]);for(let a=0;a<r.length;a++){const r={...n,colorAttachments:[{...n.colorAttachments[0],view:n.colorAttachments[a].view}]};if(n.depthStencilAttachment){const t=a;s.viewCache[t]||(s.viewCache[t]=s.texture.createView({dimension:cL,baseArrayLayer:a,arrayLayerCount:1})),r.depthStencilAttachment={view:s.viewCache[t],depthLoadOp:i.depthLoadOp||wC,depthStoreOp:i.depthStoreOp||SC,depthClearValue:i.depthClearValue||1},e.stencil&&(r.depthStencilAttachment.stencilLoadOp=i.stencilLoadOp,r.depthStencilAttachment.stencilStoreOp=i.stencilStoreOp,r.depthStencilAttachment.stencilClearValue=i.stencilClearValue)}else r.depthStencilAttachment={...i};t.layerDescriptors.push(r)}}_updateDepthLayerDescriptors(e,t,n){for(let r=0;r<n.length;r++){const n=t.layerDescriptors[r];if(n.depthStencilAttachment){const t=n.depthStencilAttachment;e.depth&&(e.clearDepth?(t.depthClearValue=e.clearDepthValue,t.depthLoadOp=wC):t.depthLoadOp=MC),e.stencil&&(e.clearStencil?(t.stencilClearValue=e.clearStencilValue,t.stencilLoadOp=wC):t.stencilLoadOp=MC)}}}finishRender(e){const t=this.get(e),n=e.occlusionQueryCount;t.renderBundles.length>0&&t.currentPass.executeBundles(t.renderBundles),n>t.occlusionQueryIndex&&t.currentPass.endOcclusionQuery();const r=t.encoder;if(!0===this._isRenderCameraDepthArray(e)){const n=[];for(let e=0;e<t.bundleEncoders.length;e++){const r=t.bundleEncoders[e];n.push(r.finish())}for(let i=0;i<t.layerDescriptors.length;i++)if(i<n.length){const s=t.layerDescriptors[i],a=r.beginRenderPass(s);if(e.viewport){const{x:t,y:n,width:r,height:i,minDepth:s,maxDepth:o}=e.viewportValue;a.setViewport(t,n,r,i,s,o)}if(e.scissor){const{x:t,y:n,width:r,height:i}=e.scissorValue;a.setScissorRect(t,n,r,i)}a.executeBundles([n[i]]),a.end()}}else t.currentPass&&t.currentPass.end();if(n>0){const r=8*n;let i=this.occludedResolveCache.get(r);void 0===i&&(i=this.device.createBuffer({size:r,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.occludedResolveCache.set(r,i));const s=this.device.createBuffer({size:r,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});t.encoder.resolveQuerySet(t.occlusionQuerySet,0,n,i,0),t.encoder.copyBufferToBuffer(i,0,s,0,r),t.occlusionQueryBuffer=s,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 n=t[e];!0===n.generateMipmaps&&this.textureUtils.generateMipmaps(n)}}}isOccluded(e,t){const n=this.get(e);return n.occluded&&n.occluded.has(t)}async resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueryBuffer:n,currentOcclusionQueryObjects:r}=t;if(n&&r){const e=new WeakSet;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueryBuffer=null,await n.mapAsync(GPUMapMode.READ);const i=n.getMappedRange(),s=new BigUint64Array(i);for(let t=0;t<r.length;t++)s[t]===BigInt(0)&&e.add(r[t]);n.destroy(),t.occluded=e}}updateViewport(e){const{currentPass:t}=this.get(e),{x:n,y:r,width:i,height:s,minDepth:a,maxDepth:o}=e.viewportValue;t.setViewport(n,r,i,s,a,o)}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,n,r=null){const i=this.device,s=this.renderer;let a,o,l,u,c=[];if(e){const e=this.getClearColor();o={r:e.r,g:e.g,b:e.b,a:e.a}}if(null===r){l=s.depth,u=s.stencil;const t=this._getDefaultRenderPassDescriptor();if(e){c=t.colorAttachments;const e=c[0];e.clearValue=o,e.loadOp=wC,e.storeOp=SC}(l||u)&&(a=t.depthStencilAttachment)}else{l=r.depth,u=r.stencil;const i={loadOp:e?wC:MC,clearValue:e?o:void 0};l&&(i.depthLoadOp=t?wC:MC,i.depthClearValue=t?s.getClearDepth():void 0,i.depthStoreOp=SC),u&&(i.stencilLoadOp=n?wC:MC,i.stencilClearValue=n?s.getClearStencil():void 0,i.stencilStoreOp=SC);const h=this._getRenderPassDescriptor(r,i);c=h.colorAttachments,a=h.depthStencilAttachment}l&&a&&void 0===a.depthLoadOp&&(t?(a.depthLoadOp=wC,a.depthClearValue=s.getClearDepth(),a.depthStoreOp=SC):(a.depthLoadOp=MC,a.depthStoreOp=SC)),u&&a&&void 0===a.stencilLoadOp&&(n?(a.stencilLoadOp=wC,a.stencilClearValue=s.getClearStencil(),a.stencilStoreOp=SC):(a.stencilLoadOp=MC,a.stencilStoreOp=SC));const h=i.createCommandEncoder({label:"clear"});h.beginRenderPass({colorAttachments:c,depthStencilAttachment:a}).end(),i.queue.submit([h.finish()])}beginCompute(e){const t=this.get(e),n={label:"computeGroup_"+e.id};this.initTimestampQuery(e,n),t.cmdEncoderGPU=this.device.createCommandEncoder({label:"computeGroup_"+e.id}),t.passEncoderGPU=t.cmdEncoderGPU.beginComputePass(n)}compute(e,t,n,r){const{passEncoderGPU:i}=this.get(e),s=this.get(r).pipeline;this.pipelineUtils.setPipeline(i,s);for(let e=0,t=n.length;e<t;e++){const t=n[e],r=this.get(t);i.setBindGroup(e,r.group)}const a=this.device.limits.maxComputeWorkgroupsPerDimension,o=this.get(t);void 0===o.dispatchSize&&(o.dispatchSize={x:0,y:1,z:1});const{dispatchSize:l}=o;t.dispatchCount>a?(l.x=Math.min(t.dispatchCount,a),l.y=Math.ceil(t.dispatchCount/a)):l.x=t.dispatchCount,i.dispatchWorkgroups(l.x,l.y,l.z)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),this.device.queue.submit([t.cmdEncoderGPU.finish()])}async waitForGPU(){await this.device.queue.onSubmittedWorkDone()}draw(e,t){const{object:n,material:r,context:i,pipeline:s}=e,a=e.getBindings(),o=this.get(i),l=this.get(s).pipeline,u=e.getIndex(),c=null!==u,h=e.getDrawParameters();if(null===h)return;const d=(t,n)=>{this.pipelineUtils.setPipeline(t,l),n.pipeline=l;const s=n.bindingGroups;for(let e=0,n=a.length;e<n;e++){const n=a[e],r=this.get(n);s[n.index]!==n.id&&(t.setBindGroup(n.index,r.group),s[n.index]=n.id)}if(!0===c&&n.index!==u){const e=this.get(u).buffer,r=u.array instanceof Uint16Array?NC:PC;t.setIndexBuffer(e,r),n.index=u}const h=e.getVertexBuffers();for(let e=0,r=h.length;e<r;e++){const r=h[e];if(n.attributes[e]!==r){const i=this.get(r).buffer;t.setVertexBuffer(e,i),n.attributes[e]=r}}!0===i.stencil&&!0===r.stencilWrite&&o.currentStencilRef!==r.stencilRef&&(t.setStencilReference(r.stencilRef),o.currentStencilRef=r.stencilRef)},p=(r,i)=>{if(d(r,i),!0===n.isBatchedMesh){const e=n._multiDrawStarts,i=n._multiDrawCounts,s=n._multiDrawCount,a=n._multiDrawInstances;null!==a&&jt("THREE.WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.");for(let o=0;o<s;o++){const s=a?a[o]:1,l=s>1?0:o;!0===c?r.drawIndexed(i[o],s,e[o]/u.array.BYTES_PER_ELEMENT,0,l):r.draw(i[o],s,e[o],l),t.update(n,i[o],s)}}else if(!0===c){const{vertexCount:i,instanceCount:s,firstVertex:a}=h,o=e.getIndirect();if(null!==o){const e=this.get(o).buffer;r.drawIndexedIndirect(e,0)}else r.drawIndexed(i,s,a,0,0);t.update(n,i,s)}else{const{vertexCount:i,instanceCount:s,firstVertex:a}=h,o=e.getIndirect();if(null!==o){const e=this.get(o).buffer;r.drawIndirect(e,0)}else r.draw(i,s,a,0);t.update(n,i,s)}};if(e.camera.isArrayCamera&&e.camera.cameras.length>0){const t=this.get(e.camera),r=e.camera.cameras,s=e.getBindingGroup("cameraIndex");if(void 0===t.indexesGPU||t.indexesGPU.length!==r.length){const e=this.get(s),n=[],i=new Uint32Array([0,0,0,0]);for(let t=0,s=r.length;t<s;t++){i[0]=t;const r=this.bindingUtils.createBindGroupIndex(i,e.layout);n.push(r)}t.indexesGPU=n}const a=this.renderer.getPixelRatio();for(let e=0,l=r.length;e<l;e++){const l=r[e];if(n.layers.test(l.layers)){const n=l.viewport;let r=o.currentPass,u=o.currentSets;if(o.bundleEncoders){r=o.bundleEncoders[e],u=o.bundleSets[e]}n&&r.setViewport(Math.floor(n.x*a),Math.floor(n.y*a),Math.floor(n.width*a),Math.floor(n.height*a),i.viewportValue.minDepth,i.viewportValue.maxDepth),s&&t.indexesGPU&&(r.setBindGroup(s.index,t.indexesGPU[e]),u.bindingGroups[s.index]=s.id),p(r,u)}}}else if(o.currentPass){if(void 0!==o.occlusionQuerySet){const e=o.lastOcclusionObject;e!==n&&(null!==e&&!0===e.occlusionTest&&(o.currentPass.endOcclusionQuery(),o.occlusionQueryIndex++),!0===n.occlusionTest&&(o.currentPass.beginOcclusionQuery(o.occlusionQueryIndex),o.occlusionQueryObjects[o.occlusionQueryIndex]=n),o.lastOcclusionObject=n)}p(o.currentPass,o.currentSets)}}needsRenderUpdate(e){const t=this.get(e),{object:n,material:r}=e,i=this.utils,s=i.getSampleCountRenderContext(e.context),a=i.getCurrentColorSpace(e.context),o=i.getCurrentColorFormat(e.context),l=i.getCurrentDepthStencilFormat(e.context),u=i.getPrimitiveTopology(n,r);let c=!1;return t.material===r&&t.materialVersion===r.version&&t.transparent===r.transparent&&t.blending===r.blending&&t.premultipliedAlpha===r.premultipliedAlpha&&t.blendSrc===r.blendSrc&&t.blendDst===r.blendDst&&t.blendEquation===r.blendEquation&&t.blendSrcAlpha===r.blendSrcAlpha&&t.blendDstAlpha===r.blendDstAlpha&&t.blendEquationAlpha===r.blendEquationAlpha&&t.colorWrite===r.colorWrite&&t.depthWrite===r.depthWrite&&t.depthTest===r.depthTest&&t.depthFunc===r.depthFunc&&t.stencilWrite===r.stencilWrite&&t.stencilFunc===r.stencilFunc&&t.stencilFail===r.stencilFail&&t.stencilZFail===r.stencilZFail&&t.stencilZPass===r.stencilZPass&&t.stencilFuncMask===r.stencilFuncMask&&t.stencilWriteMask===r.stencilWriteMask&&t.side===r.side&&t.alphaToCoverage===r.alphaToCoverage&&t.sampleCount===s&&t.colorSpace===a&&t.colorFormat===o&&t.depthStencilFormat===l&&t.primitiveTopology===u&&t.clippingContextCacheKey===e.clippingContextCacheKey||(t.material=r,t.materialVersion=r.version,t.transparent=r.transparent,t.blending=r.blending,t.premultipliedAlpha=r.premultipliedAlpha,t.blendSrc=r.blendSrc,t.blendDst=r.blendDst,t.blendEquation=r.blendEquation,t.blendSrcAlpha=r.blendSrcAlpha,t.blendDstAlpha=r.blendDstAlpha,t.blendEquationAlpha=r.blendEquationAlpha,t.colorWrite=r.colorWrite,t.depthWrite=r.depthWrite,t.depthTest=r.depthTest,t.depthFunc=r.depthFunc,t.stencilWrite=r.stencilWrite,t.stencilFunc=r.stencilFunc,t.stencilFail=r.stencilFail,t.stencilZFail=r.stencilZFail,t.stencilZPass=r.stencilZPass,t.stencilFuncMask=r.stencilFuncMask,t.stencilWriteMask=r.stencilWriteMask,t.side=r.side,t.alphaToCoverage=r.alphaToCoverage,t.sampleCount=s,t.colorSpace=a,t.colorFormat=o,t.depthStencilFormat=l,t.primitiveTopology=u,t.clippingContextCacheKey=e.clippingContextCacheKey,c=!0),c}getRenderCacheKey(e){const{object:t,material:n}=e,r=this.utils,i=e.context;return[n.transparent,n.blending,n.premultipliedAlpha,n.blendSrc,n.blendDst,n.blendEquation,n.blendSrcAlpha,n.blendDstAlpha,n.blendEquationAlpha,n.colorWrite,n.depthWrite,n.depthTest,n.depthFunc,n.stencilWrite,n.stencilFunc,n.stencilFail,n.stencilZFail,n.stencilZPass,n.stencilFuncMask,n.stencilWriteMask,n.side,r.getSampleCountRenderContext(i),r.getCurrentColorSpace(i),r.getCurrentColorFormat(i),r.getCurrentDepthStencilFormat(i),r.getPrimitiveTopology(t,n),e.getGeometryCacheKey(),e.clippingContextCacheKey].join()}createSampler(e){this.textureUtils.createSampler(e)}destroySampler(e){this.textureUtils.destroySampler(e)}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){this.textureUtils.destroyTexture(e)}async copyTextureToBuffer(e,t,n,r,i,s){return this.textureUtils.copyTextureToBuffer(e,t,n,r,i,s)}initTimestampQuery(e,t){if(!this.trackTimestamp)return;const n=e.isComputeNode?"compute":"render";this.timestampQueryPool[n]||(this.timestampQueryPool[n]=new ZL(this.device,n,2048));const r=this.timestampQueryPool[n],i=r.allocateQueriesForContext(e);t.timestampWrites={querySet:r.querySet,beginningOfPassWriteIndex:i,endOfPassWriteIndex:i+1}}createNodeBuilder(e,t){return new jL(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 n=this.get(e),r=n.currentPass.finish();this.get(t).bundleGPU=r,n.currentSets=n._currentSets,n.currentPass=n._currentPass}addBundle(e,t){this.get(e).renderBundles.push(this.get(t).bundleGPU)}createBindings(e,t,n,r){this.bindingUtils.createBindings(e,t,n,r)}updateBindings(e,t,n,r){this.bindingUtils.createBindings(e,t,n,r)}updateBinding(e){this.bindingUtils.updateBinding(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.colorBuffer=this.textureUtils.getColorBuffer(),this.defaultRenderPassdescriptor=null}getMaxAnisotropy(){return 16}hasFeature(e){return this.device.features.has(e)}copyTextureToTexture(e,t,n=null,r=null,i=0,s=0){let a=0,o=0,l=0,u=0,c=0,h=0,d=e.image.width,p=e.image.height,f=1;null!==n&&(!0===n.isBox3?(u=n.min.x,c=n.min.y,h=n.min.z,d=n.max.x-n.min.x,p=n.max.y-n.min.y,f=n.max.z-n.min.z):(u=n.min.x,c=n.min.y,d=n.max.x-n.min.x,p=n.max.y-n.min.y,f=1)),null!==r&&(a=r.x,o=r.y,l=r.z||0);const m=this.device.createCommandEncoder({label:"copyTextureToTexture_"+e.id+"_"+t.id}),g=this.get(e).texture,_=this.get(t).texture;m.copyTextureToTexture({texture:g,mipLevel:i,origin:{x:u,y:c,z:h}},{texture:_,mipLevel:s,origin:{x:a,y:o,z:l}},[d,p,f]),this.device.queue.submit([m.finish()]),0===s&&t.generateMipmaps&&this.textureUtils.generateMipmaps(t)}copyFramebufferToTexture(e,t,n){const r=this.get(t);let i=null;i=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 s=this.get(e).texture;if(i.format!==s.format)return void console.error("WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.",i.format,s.format);let a;if(r.currentPass?(r.currentPass.end(),a=r.encoder):a=this.device.createCommandEncoder({label:"copyFramebufferToTexture_"+e.id}),a.copyTextureToTexture({texture:i,origin:[n.x,n.y,0]},{texture:s},[n.z,n.w]),r.currentPass){const{descriptor:e}=r;for(let t=0;t<e.colorAttachments.length;t++)e.colorAttachments[t].loadOp=MC;if(t.depth&&(e.depthStencilAttachment.depthLoadOp=MC),t.stencil&&(e.depthStencilAttachment.stencilLoadOp=MC),r.currentPass=a.beginRenderPass(e),r.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.viewport&&this.updateViewport(t),t.scissor){const{x:e,y:n,width:i,height:s}=t.scissorValue;r.currentPass.setScissorRect(e,n,i,s)}}else this.device.queue.submit([a.finish()]);e.generateMipmaps&&this.textureUtils.generateMipmaps(e)}}class eD extends Ks{constructor(e,t,n,r,i,s){super(e,t,n,r,i,s),this.iesMap=null}copy(e,t){return super.copy(e,t),this.iesMap=e.iesMap,this}}class tD extends Ks{constructor(e,t,n,r,i,s){super(e,t,n,r,i,s),this.aspect=null}copy(e,t){return super.copy(e,t),this.aspect=e.aspect,this}}class nD extends ZA{constructor(){super(),this.addMaterial(wT,"MeshPhongMaterial"),this.addMaterial(dM,"MeshStandardMaterial"),this.addMaterial(fM,"MeshPhysicalMaterial"),this.addMaterial(vM,"MeshToonMaterial"),this.addMaterial(gT,"MeshBasicMaterial"),this.addMaterial(ST,"MeshLambertMaterial"),this.addMaterial(rT,"MeshNormalMaterial"),this.addMaterial(bM,"MeshMatcapMaterial"),this.addMaterial(Jb,"LineBasicMaterial"),this.addMaterial(tT,"LineDashedMaterial"),this.addMaterial(AM,"PointsMaterial"),this.addMaterial(wM,"SpriteMaterial"),this.addMaterial(NM,"ShadowMaterial"),this.addLight(zE,ta),this.addLight(MA,ia),this.addLight(RA,aa),this.addLight(CA,Ks),this.addLight(DA,sa),this.addLight(IA,js),this.addLight(UA,la),this.addLight(NA,eD),this.addLight(LA,tD),this.addToneMapping(Bw,1),this.addToneMapping(kw,2),this.addToneMapping(zw,3),this.addToneMapping(Gw,4),this.addToneMapping(Xw,6),this.addToneMapping(qw,7)}}class rD extends yR{constructor(e={}){let t;e.forceWebGL?t=uC:(t=JL,e.getFallback=()=>(console.warn("THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new uC(e)));super(new t(e),e),this.library=new nD,this.isWebGPURenderer=!0,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}}const iD={type:"change"},sD={type:"start"},aD={type:"end"},oD=1e-6,lD=-1,uD=0,cD=1,hD=2,dD=3,pD=4,fD=new Dt,mD=new Dt,gD=new Ut,_D=new Ut,vD=new Ut,yD=new It,xD=new Ut,bD=new Ut,TD=new Ut,SD=new Ut;class MD extends va{constructor(e,t=null){super(e,t),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:a,MIDDLE:o,RIGHT:l},this.target=new Ut,this.state=lD,this.keyState=lD,this._lastPosition=new Ut,this._lastZoom=1,this._touchZoomDistanceStart=0,this._touchZoomDistanceEnd=0,this._lastAngle=0,this._eye=new Ut,this._movePrev=new Dt,this._moveCurr=new Dt,this._lastAxis=new Ut,this._zoomStart=new Dt,this._zoomEnd=new Dt,this._panStart=new Dt,this._panEnd=new Dt,this._pointers=[],this._pointerPositions={},this._onPointerMove=ED.bind(this),this._onPointerDown=wD.bind(this),this._onPointerUp=AD.bind(this),this._onPointerCancel=RD.bind(this),this._onContextMenu=UD.bind(this),this._onMouseWheel=ID.bind(this),this._onKeyDown=ND.bind(this),this._onKeyUp=CD.bind(this),this._onTouchStart=OD.bind(this),this._onTouchMove=FD.bind(this),this._onTouchEnd=BD.bind(this),this._onMouseDown=PD.bind(this),this._onMouseMove=LD.bind(this),this._onMouseUp=DD.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!==t&&(this.connect(t),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.removeEventListener("pointermove",this._onPointerMove),this.domElement.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="auto"}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)>oD&&(this.dispatchEvent(iD),this._lastPosition.copy(this.object.position))):this.object.isOrthographicCamera?(this.object.lookAt(this.target),(this._lastPosition.distanceToSquared(this.object.position)>oD||this._lastZoom!==this.object.zoom)&&(this.dispatchEvent(iD),this._lastPosition.copy(this.object.position),this._lastZoom=this.object.zoom)):console.warn("THREE.TrackballControls: Unsupported camera type.")}reset(){this.state=lD,this.keyState=lD,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(iD),this._lastPosition.copy(this.object.position),this._lastZoom=this.object.zoom}_panCamera(){if(mD.copy(this._panEnd).sub(this._panStart),mD.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;mD.x*=e,mD.y*=t}mD.multiplyScalar(this._eye.length()*this.panSpeed),_D.copy(this._eye).cross(this.object.up).setLength(mD.x),_D.add(gD.copy(this.object.up).setLength(mD.y)),this.object.position.add(_D),this.target.add(_D),this.staticMoving?this._panStart.copy(this._panEnd):this._panStart.add(mD.subVectors(this._panEnd,this._panStart).multiplyScalar(this.dynamicDampingFactor))}}_rotateCamera(){SD.set(this._moveCurr.x-this._movePrev.x,this._moveCurr.y-this._movePrev.y,0);let e=SD.length();e?(this._eye.copy(this.object.position).sub(this.target),xD.copy(this._eye).normalize(),bD.copy(this.object.up).normalize(),TD.crossVectors(bD,xD).normalize(),bD.setLength(this._moveCurr.y-this._movePrev.y),TD.setLength(this._moveCurr.x-this._movePrev.x),SD.copy(bD.add(TD)),vD.crossVectors(SD,this._eye).normalize(),e*=this.rotateSpeed,yD.setFromAxisAngle(vD,e),this._eye.applyQuaternion(yD),this.object.up.applyQuaternion(yD),this._lastAxis.copy(vD),this._lastAngle=e):!this.staticMoving&&this._lastAngle&&(this._lastAngle*=Math.sqrt(1-this.dynamicDampingFactor),this._eye.copy(this.object.position).sub(this.target),yD.setFromAxisAngle(this._lastAxis,this._lastAngle),this._eye.applyQuaternion(yD),this.object.up.applyQuaternion(yD)),this._movePrev.copy(this._moveCurr)}_zoomCamera(){let e;this.state===pD?(e=this._touchZoomDistanceStart/this._touchZoomDistanceEnd,this._touchZoomDistanceStart=this._touchZoomDistanceEnd,this.object.isPerspectiveCamera?this._eye.multiplyScalar(e):this.object.isOrthographicCamera?(this.object.zoom=Lt.clamp(this.object.zoom/e,this.minZoom,this.maxZoom),this._lastZoom!==this.object.zoom&&this.object.updateProjectionMatrix()):console.warn("THREE.TrackballControls: Unsupported camera type")):(e=1+(this._zoomEnd.y-this._zoomStart.y)*this.zoomSpeed,1!==e&&e>0&&(this.object.isPerspectiveCamera?this._eye.multiplyScalar(e):this.object.isOrthographicCamera?(this.object.zoom=Lt.clamp(this.object.zoom/e,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 fD.set((e-this.screen.left)/this.screen.width,(t-this.screen.top)/this.screen.height),fD}_getMouseOnCircle(e,t){return fD.set((e-.5*this.screen.width-this.screen.left)/(.5*this.screen.width),(this.screen.height+2*(this.screen.top-t))/this.screen.width),fD}_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(e){let t=this._pointerPositions[e.pointerId];void 0===t&&(t=new Dt,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.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 wD(e){!1!==this.enabled&&(0===this._pointers.length&&(this.domElement.setPointerCapture(e.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerup",this._onPointerUp)),this._addPointer(e),"touch"===e.pointerType?this._onTouchStart(e):this._onMouseDown(e))}function ED(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchMove(e):this._onMouseMove(e))}function AD(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.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp)))}function RD(e){this._removePointer(e)}function CD(){!1!==this.enabled&&(this.keyState=lD,window.addEventListener("keydown",this._onKeyDown))}function ND(e){!1!==this.enabled&&(window.removeEventListener("keydown",this._onKeyDown),this.keyState===lD&&(e.code!==this.keys[uD]||this.noRotate?e.code!==this.keys[cD]||this.noZoom?e.code!==this.keys[hD]||this.noPan||(this.keyState=hD):this.keyState=cD:this.keyState=uD))}function PD(e){let t;switch(e.button){case 0:t=this.mouseButtons.LEFT;break;case 1:t=this.mouseButtons.MIDDLE;break;case 2:t=this.mouseButtons.RIGHT;break;default:t=-1}switch(t){case o:this.state=cD;break;case a:this.state=uD;break;case l:this.state=hD;break;default:this.state=lD}const n=this.keyState!==lD?this.keyState:this.state;n!==uD||this.noRotate?n!==cD||this.noZoom?n!==hD||this.noPan||(this._panStart.copy(this._getMouseOnScreen(e.pageX,e.pageY)),this._panEnd.copy(this._panStart)):(this._zoomStart.copy(this._getMouseOnScreen(e.pageX,e.pageY)),this._zoomEnd.copy(this._zoomStart)):(this._moveCurr.copy(this._getMouseOnCircle(e.pageX,e.pageY)),this._movePrev.copy(this._moveCurr)),this.dispatchEvent(sD)}function LD(e){const t=this.keyState!==lD?this.keyState:this.state;t!==uD||this.noRotate?t!==cD||this.noZoom?t!==hD||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 DD(){this.state=lD,this.dispatchEvent(aD)}function ID(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(sD),this.dispatchEvent(aD)}}function UD(e){!1!==this.enabled&&e.preventDefault()}function OD(e){if(this._trackPointer(e),1===this._pointers.length)this.state=dD,this._moveCurr.copy(this._getMouseOnCircle(this._pointers[0].pageX,this._pointers[0].pageY)),this._movePrev.copy(this._moveCurr);else{this.state=pD;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 n=(this._pointers[0].pageX+this._pointers[1].pageX)/2,r=(this._pointers[0].pageY+this._pointers[1].pageY)/2;this._panStart.copy(this._getMouseOnScreen(n,r)),this._panEnd.copy(this._panStart)}this.dispatchEvent(sD)}function FD(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),n=e.pageX-t.x,r=e.pageY-t.y;this._touchZoomDistanceEnd=Math.sqrt(n*n+r*r);const i=(e.pageX+t.x)/2,s=(e.pageY+t.y)/2;this._panEnd.copy(this._getMouseOnScreen(i,s))}}function BD(e){switch(this._pointers.length){case 0:this.state=lD;break;case 1:this.state=dD,this._moveCurr.copy(this._getMouseOnCircle(e.pageX,e.pageY)),this._movePrev.copy(this._moveCurr);break;case 2:this.state=pD;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(aD)}const kD={type:"change"},zD={type:"start"},VD={type:"end"},GD=new Fn,HD=new Gi,jD=Math.cos(70*Lt.DEG2RAD),WD=new Ut,XD=2*Math.PI,qD=-1,$D=0,YD=1,KD=2,QD=3,ZD=4,JD=5,eI=6,tI=1e-6;class nI extends va{constructor(e,t=null){super(e,t),this.state=qD,this.target=new Ut,this.cursor=new Ut,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:a,MIDDLE:o,RIGHT:l},this.touches={ONE:u,TWO:h},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this._lastPosition=new Ut,this._lastQuaternion=new It,this._lastTargetPosition=new Ut,this._quat=(new It).setFromUnitVectors(e.up,new Ut(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new ga,this._sphericalDelta=new ga,this._scale=1,this._panOffset=new Ut,this._rotateStart=new Dt,this._rotateEnd=new Dt,this._rotateDelta=new Dt,this._panStart=new Dt,this._panEnd=new Dt,this._panDelta=new Dt,this._dollyStart=new Dt,this._dollyEnd=new Dt,this._dollyDelta=new Dt,this._dollyDirection=new Ut,this._mouse=new Dt,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=iI.bind(this),this._onPointerDown=rI.bind(this),this._onPointerUp=sI.bind(this),this._onContextMenu=dI.bind(this),this._onMouseWheel=lI.bind(this),this._onKeyDown=uI.bind(this),this._onTouchStart=cI.bind(this),this._onTouchMove=hI.bind(this),this._onMouseDown=aI.bind(this),this._onMouseMove=oI.bind(this),this._interceptControlDown=pI.bind(this),this._interceptControlUp=fI.bind(this),null!==this.domElement&&this.connect(this.domElement),this.update()}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.removeEventListener("pointermove",this._onPointerMove),this.domElement.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="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(kD),this.update(),this.state=qD}update(e=null){const t=this.object.position;WD.copy(t).sub(this.target),WD.applyQuaternion(this._quat),this._spherical.setFromVector3(WD),this.autoRotate&&this.state===qD&&this._rotateLeft(this._getAutoRotationAngle(e)),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 n=this.minAzimuthAngle,r=this.maxAzimuthAngle;isFinite(n)&&isFinite(r)&&(n<-Math.PI?n+=XD:n>Math.PI&&(n-=XD),r<-Math.PI?r+=XD:r>Math.PI&&(r-=XD),this._spherical.theta=n<=r?Math.max(n,Math.min(r,this._spherical.theta)):this._spherical.theta>(n+r)/2?Math.max(n,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 i=!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),i=e!=this._spherical.radius}if(WD.setFromSpherical(this._spherical),WD.applyQuaternion(this._quatInverse),t.copy(this.target).add(WD),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 e=null;if(this.object.isPerspectiveCamera){const t=WD.length();e=this._clampDistance(t*this._scale);const n=t-e;this.object.position.addScaledVector(this._dollyDirection,n),this.object.updateMatrixWorld(),i=!!n}else if(this.object.isOrthographicCamera){const t=new Ut(this._mouse.x,this._mouse.y,0);t.unproject(this.object);const n=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),i=n!==this.object.zoom;const r=new Ut(this._mouse.x,this._mouse.y,0);r.unproject(this.object),this.object.position.sub(r).add(t),this.object.updateMatrixWorld(),e=WD.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;null!==e&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(e).add(this.object.position):(GD.origin.copy(this.object.position),GD.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(GD.direction))<jD?this.object.lookAt(this.target):(HD.setFromNormalAndCoplanarPoint(this.object.up,this.target),GD.intersectPlane(HD,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(),i=!0)}return this._scale=1,this._performCursorZoom=!1,!!(i||this._lastPosition.distanceToSquared(this.object.position)>tI||8*(1-this._lastQuaternion.dot(this.object.quaternion))>tI||this._lastTargetPosition.distanceToSquared(this.target)>tI)&&(this.dispatchEvent(kD),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0)}_getAutoRotationAngle(e){return null!==e?XD/60*this.autoRotateSpeed*e:XD/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){WD.setFromMatrixColumn(t,0),WD.multiplyScalar(-e),this._panOffset.add(WD)}_panUp(e,t){!0===this.screenSpacePanning?WD.setFromMatrixColumn(t,1):(WD.setFromMatrixColumn(t,0),WD.crossVectors(this.object.up,WD)),WD.multiplyScalar(e),this._panOffset.add(WD)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const r=this.object.position;WD.copy(r).sub(this.target);let i=WD.length();i*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*i/n.clientHeight,this.object.matrix),this._panUp(2*t*i/n.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/n.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/n.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 n=this.domElement.getBoundingClientRect(),r=e-n.left,i=t-n.top,s=n.width,a=n.height;this._mouse.x=r/s*2-1,this._mouse.y=-i/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(XD*this._rotateDelta.x/t.clientHeight),this._rotateUp(XD*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(XD*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(-XD*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(XD*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(-XD*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),n=.5*(e.pageX+t.x),r=.5*(e.pageY+t.y);this._rotateStart.set(n,r)}}_handleTouchStartPan(e){if(1===this._pointers.length)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),r=.5*(e.pageY+t.y);this._panStart.set(n,r)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,r=e.pageY-t.y,i=Math.sqrt(n*n+r*r);this._dollyStart.set(0,i)}_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),n=.5*(e.pageX+t.x),r=.5*(e.pageY+t.y);this._rotateEnd.set(n,r)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(XD*this._rotateDelta.x/t.clientHeight),this._rotateUp(XD*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),n=.5*(e.pageX+t.x),r=.5*(e.pageY+t.y);this._panEnd.set(n,r)}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),n=e.pageX-t.x,r=e.pageY-t.y,i=Math.sqrt(n*n+r*r);this._dollyEnd.set(0,i),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 s=.5*(e.pageX+t.x),a=.5*(e.pageY+t.y);this._updateZoomParameters(s,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(e){let t=this._pointerPositions[e.pointerId];void 0===t&&(t=new Dt,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.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,n={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:n.deltaY*=16;break;case 2:n.deltaY*=100}return e.ctrlKey&&!this._controlActive&&(n.deltaY*=10),n}}function rI(e){!1!==this.enabled&&(0===this._pointers.length&&(this.domElement.setPointerCapture(e.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerup",this._onPointerUp)),this._isTrackingPointer(e)||(this._addPointer(e),"touch"===e.pointerType?this._onTouchStart(e):this._onMouseDown(e)))}function iI(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchMove(e):this._onMouseMove(e))}function sI(e){switch(this._removePointer(e),this._pointers.length){case 0:this.domElement.releasePointerCapture(e.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(VD),this.state=qD;break;case 1:const t=this._pointers[0],n=this._pointerPositions[t];this._onTouchStart({pointerId:t,pageX:n.x,pageY:n.y})}}function aI(e){let t;switch(e.button){case 0:t=this.mouseButtons.LEFT;break;case 1:t=this.mouseButtons.MIDDLE;break;case 2:t=this.mouseButtons.RIGHT;break;default:t=-1}switch(t){case o:if(!1===this.enableZoom)return;this._handleMouseDownDolly(e),this.state=YD;break;case a:if(e.ctrlKey||e.metaKey||e.shiftKey){if(!1===this.enablePan)return;this._handleMouseDownPan(e),this.state=KD}else{if(!1===this.enableRotate)return;this._handleMouseDownRotate(e),this.state=$D}break;case l:if(e.ctrlKey||e.metaKey||e.shiftKey){if(!1===this.enableRotate)return;this._handleMouseDownRotate(e),this.state=$D}else{if(!1===this.enablePan)return;this._handleMouseDownPan(e),this.state=KD}break;default:this.state=qD}this.state!==qD&&this.dispatchEvent(zD)}function oI(e){switch(this.state){case $D:if(!1===this.enableRotate)return;this._handleMouseMoveRotate(e);break;case YD:if(!1===this.enableZoom)return;this._handleMouseMoveDolly(e);break;case KD:if(!1===this.enablePan)return;this._handleMouseMovePan(e)}}function lI(e){!1!==this.enabled&&!1!==this.enableZoom&&this.state===qD&&(e.preventDefault(),this.dispatchEvent(zD),this._handleMouseWheel(this._customWheelEvent(e)),this.dispatchEvent(VD))}function uI(e){!1!==this.enabled&&this._handleKeyDown(e)}function cI(e){switch(this._trackPointer(e),this._pointers.length){case 1:switch(this.touches.ONE){case u:if(!1===this.enableRotate)return;this._handleTouchStartRotate(e),this.state=QD;break;case c:if(!1===this.enablePan)return;this._handleTouchStartPan(e),this.state=ZD;break;default:this.state=qD}break;case 2:switch(this.touches.TWO){case h:if(!1===this.enableZoom&&!1===this.enablePan)return;this._handleTouchStartDollyPan(e),this.state=JD;break;case d:if(!1===this.enableZoom&&!1===this.enableRotate)return;this._handleTouchStartDollyRotate(e),this.state=eI;break;default:this.state=qD}break;default:this.state=qD}this.state!==qD&&this.dispatchEvent(zD)}function hI(e){switch(this._trackPointer(e),this.state){case QD:if(!1===this.enableRotate)return;this._handleTouchMoveRotate(e),this.update();break;case ZD:if(!1===this.enablePan)return;this._handleTouchMovePan(e),this.update();break;case JD:if(!1===this.enableZoom&&!1===this.enablePan)return;this._handleTouchMoveDollyPan(e),this.update();break;case eI:if(!1===this.enableZoom&&!1===this.enableRotate)return;this._handleTouchMoveDollyRotate(e),this.update();break;default:this.state=qD}}function dI(e){!1!==this.enabled&&e.preventDefault()}function pI(e){if("Control"===e.key){this._controlActive=!0;this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}}function fI(e){if("Control"===e.key){this._controlActive=!1;this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}}const mI={type:"change"},gI=1e-6,_I=new It;class vI extends va{constructor(e,t=null){super(e,t),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 Ut(0,0,0),this._rotationVector=new Ut(0,0,0),this._lastQuaternion=new It,this._lastPosition=new Ut,this._status=0,this._onKeyDown=yI.bind(this),this._onKeyUp=xI.bind(this),this._onPointerMove=TI.bind(this),this._onPointerDown=bI.bind(this),this._onPointerUp=SI.bind(this),this._onPointerCancel=MI.bind(this),this._onContextMenu=wI.bind(this),null!==t&&this.connect(t)}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)}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)}dispose(){this.disconnect()}update(e){if(!1===this.enabled)return;const t=this.object,n=e*this.movementSpeed,r=e*this.rollSpeed;t.translateX(this._moveVector.x*n),t.translateY(this._moveVector.y*n),t.translateZ(this._moveVector.z*n),_I.set(this._rotationVector.x*r,this._rotationVector.y*r,this._rotationVector.z*r,1).normalize(),t.quaternion.multiply(_I),(this._lastPosition.distanceToSquared(t.position)>gI||8*(1-this._lastQuaternion.dot(t.quaternion))>gI)&&(this.dispatchEvent(mI),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 yI(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 xI(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 bI(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 TI(e){if(!1!==this.enabled&&(!this.dragToLook||this._status>0)){const t=this._getContainerDimensions(),n=t.size[0]/2,r=t.size[1]/2;this._moveState.yawLeft=-(e.pageX-t.offset[0]-n)/n,this._moveState.pitchDown=(e.pageY-t.offset[1]-r)/r,this._updateRotationVector()}}function SI(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 MI(){!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 wI(e){!1!==this.enabled&&e.preventDefault()}const EI={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 AI{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 RI=new na(-1,1,1,-1,0,1);const CI=new class extends ei{constructor(){super(),this.setAttribute("position",new Xr([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new Xr([0,2,0,0,2,0],2))}};class NI{constructor(e){this._mesh=new di(CI,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,RI)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}class PI extends AI{constructor(e,t="tDiffuse"){super(),this.textureID=t,this.uniforms=null,this.material=null,e instanceof yi?(this.uniforms=e.uniforms,this.material=e):e&&(this.uniforms=vi.clone(e.uniforms),this.material=new yi({name:void 0!==e.name?e.name:"unspecified",defines:Object.assign({},e.defines),uniforms:this.uniforms,vertexShader:e.vertexShader,fragmentShader:e.fragmentShader})),this._fsQuad=new NI(this.material)}render(e,t,n){this.uniforms[this.textureID]&&(this.uniforms[this.textureID].value=n.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 LI extends AI{constructor(e,t){super(),this.scene=e,this.camera=t,this.clear=!0,this.needsSwap=!1,this.inverse=!1}render(e,t,n){const r=e.getContext(),i=e.state;let s,a;i.buffers.color.setMask(!1),i.buffers.depth.setMask(!1),i.buffers.color.setLocked(!0),i.buffers.depth.setLocked(!0),this.inverse?(s=0,a=1):(s=1,a=0),i.buffers.stencil.setTest(!0),i.buffers.stencil.setOp(r.REPLACE,r.REPLACE,r.REPLACE),i.buffers.stencil.setFunc(r.ALWAYS,s,4294967295),i.buffers.stencil.setClear(a),i.buffers.stencil.setLocked(!0),e.setRenderTarget(n),this.clear&&e.clear(),e.render(this.scene,this.camera),e.setRenderTarget(t),this.clear&&e.clear(),e.render(this.scene,this.camera),i.buffers.color.setLocked(!1),i.buffers.depth.setLocked(!1),i.buffers.color.setMask(!0),i.buffers.depth.setMask(!0),i.buffers.stencil.setLocked(!1),i.buffers.stencil.setFunc(r.EQUAL,1,4294967295),i.buffers.stencil.setOp(r.KEEP,r.KEEP,r.KEEP),i.buffers.stencil.setLocked(!0)}}class DI extends AI{constructor(){super(),this.needsSwap=!1}render(e){e.state.buffers.stencil.setLocked(!1),e.state.buffers.stencil.setTest(!1)}}class II{constructor(e,t){if(this.renderer=e,this._pixelRatio=e.getPixelRatio(),void 0===t){const n=e.getSize(new Dt);this._width=n.width,this._height=n.height,(t=new ln(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:ue})).texture.name="EffectComposer.rt1"}else this._width=t.width,this._height=t.height;this.renderTarget1=t,this.renderTarget2=t.clone(),this.renderTarget2.texture.name="EffectComposer.rt2",this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2,this.renderToScreen=!0,this.passes=[],this.copyPass=new PI(EI),this.copyPass.material.blending=0,this.clock=new ca}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){void 0===e&&(e=this.clock.getDelta());const t=this.renderer.getRenderTarget();let n=!1;for(let t=0,r=this.passes.length;t<r;t++){const r=this.passes[t];if(!1!==r.enabled){if(r.renderToScreen=this.renderToScreen&&this.isLastEnabledPass(t),r.render(this.renderer,this.writeBuffer,this.readBuffer,e,n),r.needsSwap){if(n){const t=this.renderer.getContext(),n=this.renderer.state.buffers.stencil;n.setFunc(t.NOTEQUAL,1,4294967295),this.copyPass.render(this.renderer,this.writeBuffer,this.readBuffer,e),n.setFunc(t.EQUAL,1,4294967295)}this.swapBuffers()}void 0!==LI&&(r instanceof LI?n=!0:r instanceof DI&&(n=!1))}}this.renderer.setRenderTarget(t)}reset(e){if(void 0===e){const t=this.renderer.getSize(new Dt);this._pixelRatio=this.renderer.getPixelRatio(),this._width=t.width,this._height=t.height,(e=this.renderTarget1.clone()).setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}this.renderTarget1.dispose(),this.renderTarget2.dispose(),this.renderTarget1=e,this.renderTarget2=e.clone(),this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2}setSize(e,t){this._width=e,this._height=t;const n=this._width*this._pixelRatio,r=this._height*this._pixelRatio;this.renderTarget1.setSize(n,r),this.renderTarget2.setSize(n,r);for(let e=0;e<this.passes.length;e++)this.passes[e].setSize(n,r)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget1.dispose(),this.renderTarget2.dispose(),this.copyPass.dispose()}}class UI extends AI{constructor(e,t,n=null,r=null,i=null){super(),this.scene=e,this.camera=t,this.overrideMaterial=n,this.clearColor=r,this.clearAlpha=i,this.clear=!0,this.clearDepth=!1,this.needsSwap=!1,this._oldClearColor=new Nr}render(e,t,n){const r=e.autoClear;let i,s;e.autoClear=!1,null!==this.overrideMaterial&&(s=this.scene.overrideMaterial,this.scene.overrideMaterial=this.overrideMaterial),null!==this.clearColor&&(e.getClearColor(this._oldClearColor),e.setClearColor(this.clearColor,e.getClearAlpha())),null!==this.clearAlpha&&(i=e.getClearAlpha(),e.setClearAlpha(this.clearAlpha)),1==this.clearDepth&&e.clearDepth(),e.setRenderTarget(this.renderToScreen?null:n),!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(i),null!==this.overrideMaterial&&(this.scene.overrideMaterial=s),e.autoClear=r}}function OI(){return OI=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},OI.apply(null,arguments)}function FI(e,t){return FI=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},FI(e,t)}function BI(e){return BI=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},BI(e)}function kI(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(kI=function(){return!!e})()}function zI(e){var t="function"==typeof Map?new Map:void 0;return zI=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,n)}function n(){return function(e,t,n){if(kI())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&FI(i,n.prototype),i}(e,arguments,BI(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),FI(n,e)},zI(e)}var VI={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 GI(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];var r,i=t[0],s=[];for(r=1;r<t.length;r+=1)s.push(t[r]);return s.forEach(function(e){i=i.replace(/%[a-z]/,e)}),i}var HI=function(e){function t(t){var n;if("production"===process.env.NODE_ENV)n=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 r=arguments.length,i=new Array(r>1?r-1:0),s=1;s<r;s++)i[s-1]=arguments[s];n=e.call(this,GI.apply(void 0,[VI[t]].concat(i)))||this}return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(n)}return function(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,FI(e,t)}(t,e),t}(zI(Error));function jI(e){return Math.round(255*e)}function WI(e,t,n){return jI(e)+","+jI(t)+","+jI(n)}function XI(e,t,n,r){if(void 0===r&&(r=WI),0===t)return r(n,n,n);var i=(e%360+360)%360/60,s=(1-Math.abs(2*n-1))*t,a=s*(1-Math.abs(i%2-1)),o=0,l=0,u=0;i>=0&&i<1?(o=s,l=a):i>=1&&i<2?(o=a,l=s):i>=2&&i<3?(l=s,u=a):i>=3&&i<4?(l=a,u=s):i>=4&&i<5?(o=a,u=s):i>=5&&i<6&&(o=s,u=a);var c=n-s/2;return r(o+c,l+c,u+c)}var qI={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 $I=/^#[a-fA-F0-9]{6}$/,YI=/^#[a-fA-F0-9]{8}$/,KI=/^#[a-fA-F0-9]{3}$/,QI=/^#[a-fA-F0-9]{4}$/,ZI=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,JI=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,eU=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,tU=/^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 nU(e){if("string"!=typeof e)throw new HI(3);var t=function(e){if("string"!=typeof e)return e;var t=e.toLowerCase();return qI[t]?"#"+qI[t]:e}(e);if(t.match($I))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(YI)){var n=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:n}}if(t.match(KI))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(QI)){var r=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:r}}var i=ZI.exec(t);if(i)return{red:parseInt(""+i[1],10),green:parseInt(""+i[2],10),blue:parseInt(""+i[3],10)};var s=JI.exec(t.substring(0,50));if(s)return{red:parseInt(""+s[1],10),green:parseInt(""+s[2],10),blue:parseInt(""+s[3],10),alpha:parseFloat(""+s[4])>1?parseFloat(""+s[4])/100:parseFloat(""+s[4])};var a=eU.exec(t);if(a){var o="rgb("+XI(parseInt(""+a[1],10),parseInt(""+a[2],10)/100,parseInt(""+a[3],10)/100)+")",l=ZI.exec(o);if(!l)throw new HI(4,t,o);return{red:parseInt(""+l[1],10),green:parseInt(""+l[2],10),blue:parseInt(""+l[3],10)}}var u=tU.exec(t.substring(0,50));if(u){var c="rgb("+XI(parseInt(""+u[1],10),parseInt(""+u[2],10)/100,parseInt(""+u[3],10)/100)+")",h=ZI.exec(c);if(!h)throw new HI(4,t,c);return{red:parseInt(""+h[1],10),green:parseInt(""+h[2],10),blue:parseInt(""+h[3],10),alpha:parseFloat(""+u[4])>1?parseFloat(""+u[4])/100:parseFloat(""+u[4])}}throw new HI(5)}function rU(e){return function(e){var t,n=e.red/255,r=e.green/255,i=e.blue/255,s=Math.max(n,r,i),a=Math.min(n,r,i),o=(s+a)/2;if(s===a)return void 0!==e.alpha?{hue:0,saturation:0,lightness:o,alpha:e.alpha}:{hue:0,saturation:0,lightness:o};var l=s-a,u=o>.5?l/(2-s-a):l/(s+a);switch(s){case n:t=(r-i)/l+(r<i?6:0);break;case r:t=(i-n)/l+2;break;default:t=(n-r)/l+4}return t*=60,void 0!==e.alpha?{hue:t,saturation:u,lightness:o,alpha:e.alpha}:{hue:t,saturation:u,lightness:o}}(nU(e))}var iU=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 sU(e){var t=e.toString(16);return 1===t.length?"0"+t:t}function aU(e){return sU(Math.round(255*e))}function oU(e,t,n){return iU("#"+aU(e)+aU(t)+aU(n))}function lU(e,t,n){return XI(e,t,n,oU)}function uU(e,t,n){if("number"==typeof e&&"number"==typeof t&&"number"==typeof n)return iU("#"+sU(e)+sU(t)+sU(n));if("object"==typeof e&&void 0===t&&void 0===n)return iU("#"+sU(e.red)+sU(e.green)+sU(e.blue));throw new HI(6)}function cU(e,t,n,r){if("object"==typeof e&&void 0===t&&void 0===n&&void 0===r)return e.alpha>=1?uU(e.red,e.green,e.blue):"rgba("+e.red+","+e.green+","+e.blue+","+e.alpha+")";throw new HI(7)}function hU(e){if("object"!=typeof e)throw new HI(8);if(function(e){return"number"==typeof e.red&&"number"==typeof e.green&&"number"==typeof e.blue&&"number"==typeof e.alpha}(e))return cU(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 uU(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,n,r){if("object"==typeof e&&void 0===t&&void 0===n&&void 0===r)return e.alpha>=1?lU(e.hue,e.saturation,e.lightness):"rgba("+XI(e.hue,e.saturation,e.lightness)+","+e.alpha+")";throw new HI(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,n){if("object"==typeof e&&void 0===t&&void 0===n)return lU(e.hue,e.saturation,e.lightness);throw new HI(1)}(e);throw new HI(8)}function dU(e,t,n){return function(){var r=n.concat(Array.prototype.slice.call(arguments));return r.length>=t?e.apply(this,r):dU(e,t,r)}}function pU(e){return dU(e,e.length,[])}function fU(e,t,n){return Math.max(e,Math.min(t,n))}pU(function(e,t){if("transparent"===t)return t;var n=rU(t);return hU(OI({},n,{hue:n.hue+parseFloat(e)}))}),pU(function(e,t){if("transparent"===t)return t;var n=rU(t);return hU(OI({},n,{lightness:fU(0,1,n.lightness-parseFloat(e))}))}),pU(function(e,t){if("transparent"===t)return t;var n=rU(t);return hU(OI({},n,{saturation:fU(0,1,n.saturation-parseFloat(e))}))}),pU(function(e,t){if("transparent"===t)return t;var n=rU(t);return hU(OI({},n,{lightness:fU(0,1,n.lightness+parseFloat(e))}))});var mU=pU(function(e,t,n){if("transparent"===t)return n;if("transparent"===n)return t;if(0===e)return n;var r=nU(t),i=OI({},r,{alpha:"number"==typeof r.alpha?r.alpha:1}),s=nU(n),a=OI({},s,{alpha:"number"==typeof s.alpha?s.alpha:1}),o=i.alpha-a.alpha,l=2*parseFloat(e)-1,u=((l*o===-1?l:l+o)/(1+l*o)+1)/2,c=1-u;return cU({red:Math.floor(i.red*u+a.red*c),green:Math.floor(i.green*u+a.green*c),blue:Math.floor(i.blue*u+a.blue*c),alpha:i.alpha*parseFloat(e)+a.alpha*(1-parseFloat(e))})}),gU=mU;var _U=pU(function(e,t){if("transparent"===t)return t;var n=nU(t);return cU(OI({},n,{alpha:fU(0,1,(100*("number"==typeof n.alpha?n.alpha:1)+100*parseFloat(e))/100)}))}),vU=_U;pU(function(e,t){if("transparent"===t)return t;var n=rU(t);return hU(OI({},n,{saturation:fU(0,1,n.saturation+parseFloat(e))}))}),pU(function(e,t){return"transparent"===t?t:hU(OI({},rU(t),{hue:parseFloat(e)}))}),pU(function(e,t){return"transparent"===t?t:hU(OI({},rU(t),{lightness:parseFloat(e)}))}),pU(function(e,t){return"transparent"===t?t:hU(OI({},rU(t),{saturation:parseFloat(e)}))}),pU(function(e,t){return"transparent"===t?t:gU(parseFloat(e),"rgb(0, 0, 0)",t)}),pU(function(e,t){return"transparent"===t?t:gU(parseFloat(e),"rgb(255, 255, 255)",t)}),pU(function(e,t){if("transparent"===t)return t;var n=nU(t);return cU(OI({},n,{alpha:fU(0,1,+(100*("number"==typeof n.alpha?n.alpha:1)-100*parseFloat(e)).toFixed(2)/100)}))});var yU=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-yU.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*yU.Bounce.In(2*e):.5*yU.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}}}}),xU=function(){return performance.now()},bU=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=[],n=0;n<arguments.length;n++)t[n]=arguments[n];for(var r=0,i=t;r<i.length;r++){var s=i[r];null===(e=s._group)||void 0===e||e.remove(s),s._group=this,this._tweens[s.getId()]=s,this._tweensAddedDuringUpdate[s.getId()]=s}},e.prototype.remove=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var n=0,r=e;n<r.length;n++){var i=r[n];i._group=void 0,delete this._tweens[i.getId()],delete this._tweensAddedDuringUpdate[i.getId()]}},e.prototype.allStopped=function(){return this.getAll().every(function(e){return!e.isPlaying()})},e.prototype.update=function(e,t){void 0===e&&(e=xU()),void 0===t&&(t=!0);var n=Object.keys(this._tweens);if(0!==n.length)for(;n.length>0;){this._tweensAddedDuringUpdate={};for(var r=0;r<n.length;r++){var i=this._tweens[n[r]],s=!t;i&&!1===i.update(e,s)&&!t&&this.remove(i)}n=Object.keys(this._tweensAddedDuringUpdate)}},e}(),TU={Linear:function(e,t){var n=e.length-1,r=n*t,i=Math.floor(r),s=TU.Utils.Linear;return t<0?s(e[0],e[1],r):t>1?s(e[n],e[n-1],n-r):s(e[i],e[i+1>n?n:i+1],r-i)},Utils:{Linear:function(e,t,n){return(t-e)*n+e}}},SU=function(){function e(){}return e.nextId=function(){return e._nextId++},e._nextId=0,e}(),MU=new bU,wU=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=yU.Linear.None,this._interpolationFunction=TU.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=SU.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=MU,MU.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=xU()),void 0===t&&(t=!1),this._isPlaying)return this;if(this._repeat=this._initialRepeat,this._reversed)for(var n in this._reversed=!1,this._valuesStartRepeat)this._swapEndStartRepeatValues(n),this._valuesStart[n]=this._valuesStartRepeat[n];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 r={};for(var i in this._valuesEnd)r[i]=this._valuesEnd[i];this._valuesEnd=r}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,n,r,i){for(var s in n){var a=e[s],o=Array.isArray(a),l=o?"array":typeof a,u=!o&&Array.isArray(n[s]);if("undefined"!==l&&"function"!==l){if(u){if(0===(g=n[s]).length)continue;for(var c=[a],h=0,d=g.length;h<d;h+=1){var p=this._handleRelativeValue(a,g[h]);if(isNaN(p)){u=!1,console.warn("Found invalid interpolation list. Skipping.");break}c.push(p)}u&&(n[s]=c)}if("object"!==l&&!o||!a||u)(void 0===t[s]||i)&&(t[s]=a),o||(t[s]*=1),r[s]=u?n[s].slice().reverse():t[s]||0;else{t[s]=o?[]:{};var f=a;for(var m in f)t[s][m]=f[m];r[s]=o?[]:{};var g=n[s];if(!this._isDynamic){var _={};for(var m in g)_[m]=g[m];n[s]=g=_}this._setupProperties(f,t[s],g,r[s],i)}}}},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=xU()),this._isPaused||!this._isPlaying||(this._isPaused=!0,this._pauseStart=e),this},e.prototype.resume=function(e){return void 0===e&&(e=xU()),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=yU.Linear.None),this._easingFunction=e,this},e.prototype.interpolation=function(e){return void 0===e&&(e=TU.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,n){var r,i,s=this;if(void 0===t&&(t=xU()),void 0===n&&(n=e.autoStartOnUpdate),this._isPaused)return!0;if(!this._goToEnd&&!this._isPlaying){if(!n)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!==(r=this._repeatDelayTime)&&void 0!==r?r:this._delayTime),l=this._duration+this._repeat*o,u=function(){if(0===s._duration)return 1;if(a>l)return 1;var e=Math.trunc(a/o),t=a-e*o,n=Math.min(t/s._duration,1);return 0===n&&a===s._duration?1:n}(),c=this._easingFunction(u);if(this._updateProperties(this._object,this._valuesStart,this._valuesEnd,c),this._onUpdateCallback&&this._onUpdateCallback(this._object,u),0===this._duration||a>=this._duration){if(this._repeat>0){var h=Math.min(Math.trunc((a-this._duration)/o)+1,this._repeat);for(i in isFinite(this._repeat)&&(this._repeat-=h),this._valuesStartRepeat)this._yoyo||"string"!=typeof this._valuesEnd[i]||(this._valuesStartRepeat[i]=this._valuesStartRepeat[i]+parseFloat(this._valuesEnd[i])),this._yoyo&&this._swapEndStartRepeatValues(i),this._valuesStart[i]=this._valuesStartRepeat[i];return this._yoyo&&(this._reversed=!this._reversed),this._startTime+=o*h,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,n,r){for(var i in n)if(void 0!==t[i]){var s=t[i]||0,a=n[i],o=Array.isArray(e[i]),l=Array.isArray(a);!o&&l?e[i]=this._interpolationFunction(a,r):"object"==typeof a&&a?this._updateProperties(e[i],s,a,r):"number"==typeof(a=this._handleRelativeValue(s,a))&&(e[i]=s+(a-s)*r)}},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],n=this._valuesEnd[e];this._valuesStartRepeat[e]="string"==typeof n?this._valuesStartRepeat[e]+parseFloat(n):this._valuesEnd[e],this._valuesEnd[e]=t},e.autoStartOnUpdate=!1,e}();SU.nextId;var EU=MU;EU.getAll.bind(EU),EU.removeAll.bind(EU),EU.add.bind(EU),EU.remove.bind(EU),EU.update.bind(EU);var AU="http://www.w3.org/1999/xhtml",RU={svg:"http://www.w3.org/2000/svg",xhtml:AU,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function CU(e){var t=e+="",n=t.indexOf(":");return n>=0&&"xmlns"!==(t=e.slice(0,n))&&(e=e.slice(n+1)),RU.hasOwnProperty(t)?{space:RU[t],local:e}:e}function NU(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===AU&&t.documentElement.namespaceURI===AU?t.createElement(e):t.createElementNS(n,e)}}function PU(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function LU(e){var t=CU(e);return(t.local?PU:NU)(t)}function DU(){}function IU(e){return null==e?DU:function(){return this.querySelector(e)}}function UU(){return[]}function OU(e){return function(){return function(e){return null==e?[]:Array.isArray(e)?e:Array.from(e)}(e.apply(this,arguments))}}function FU(e){return function(t){return t.matches(e)}}var BU=Array.prototype.find;function kU(){return this.firstElementChild}var zU=Array.prototype.filter;function VU(){return Array.from(this.children)}function GU(e){return new Array(e.length)}function HU(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}function jU(e,t,n,r,i,s){for(var a,o=0,l=t.length,u=s.length;o<u;++o)(a=t[o])?(a.__data__=s[o],r[o]=a):n[o]=new HU(e,s[o]);for(;o<l;++o)(a=t[o])&&(i[o]=a)}function WU(e,t,n,r,i,s,a){var o,l,u,c=new Map,h=t.length,d=s.length,p=new Array(h);for(o=0;o<h;++o)(l=t[o])&&(p[o]=u=a.call(l,l.__data__,o,t)+"",c.has(u)?i[o]=l:c.set(u,l));for(o=0;o<d;++o)u=a.call(e,s[o],o,s)+"",(l=c.get(u))?(r[o]=l,l.__data__=s[o],c.delete(u)):n[o]=new HU(e,s[o]);for(o=0;o<h;++o)(l=t[o])&&c.get(p[o])===l&&(i[o]=l)}function XU(e){return e.__data__}function qU(e){return"object"==typeof e&&"length"in e?e:Array.from(e)}function $U(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function YU(e){return function(){this.removeAttribute(e)}}function KU(e){return function(){this.removeAttributeNS(e.space,e.local)}}function QU(e,t){return function(){this.setAttribute(e,t)}}function ZU(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function JU(e,t){return function(){var n=t.apply(this,arguments);null==n?this.removeAttribute(e):this.setAttribute(e,n)}}function eO(e,t){return function(){var n=t.apply(this,arguments);null==n?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,n)}}function tO(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function nO(e){return function(){this.style.removeProperty(e)}}function rO(e,t,n){return function(){this.style.setProperty(e,t,n)}}function iO(e,t,n){return function(){var r=t.apply(this,arguments);null==r?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function sO(e){return function(){delete this[e]}}function aO(e,t){return function(){this[e]=t}}function oO(e,t){return function(){var n=t.apply(this,arguments);null==n?delete this[e]:this[e]=n}}function lO(e){return e.trim().split(/^|\s+/)}function uO(e){return e.classList||new cO(e)}function cO(e){this._node=e,this._names=lO(e.getAttribute("class")||"")}function hO(e,t){for(var n=uO(e),r=-1,i=t.length;++r<i;)n.add(t[r])}function dO(e,t){for(var n=uO(e),r=-1,i=t.length;++r<i;)n.remove(t[r])}function pO(e){return function(){hO(this,e)}}function fO(e){return function(){dO(this,e)}}function mO(e,t){return function(){(t.apply(this,arguments)?hO:dO)(this,e)}}function gO(){this.textContent=""}function _O(e){return function(){this.textContent=e}}function vO(e){return function(){var t=e.apply(this,arguments);this.textContent=null==t?"":t}}function yO(){this.innerHTML=""}function xO(e){return function(){this.innerHTML=e}}function bO(e){return function(){var t=e.apply(this,arguments);this.innerHTML=null==t?"":t}}function TO(){this.nextSibling&&this.parentNode.appendChild(this)}function SO(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function MO(){return null}function wO(){var e=this.parentNode;e&&e.removeChild(this)}function EO(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function AO(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function RO(e){return function(){var t=this.__on;if(t){for(var n,r=0,i=-1,s=t.length;r<s;++r)n=t[r],e.type&&n.type!==e.type||n.name!==e.name?t[++i]=n:this.removeEventListener(n.type,n.listener,n.options);++i?t.length=i:delete this.__on}}}function CO(e,t,n){return function(){var r,i=this.__on,s=function(e){return function(t){e.call(this,t,this.__data__)}}(t);if(i)for(var a=0,o=i.length;a<o;++a)if((r=i[a]).type===e.type&&r.name===e.name)return this.removeEventListener(r.type,r.listener,r.options),this.addEventListener(r.type,r.listener=s,r.options=n),void(r.value=t);this.addEventListener(e.type,s,n),r={type:e.type,name:e.name,value:t,listener:s,options:n},i?i.push(r):this.__on=[r]}}function NO(e,t,n){var r=tO(e),i=r.CustomEvent;"function"==typeof i?i=new i(t,n):(i=r.document.createEvent("Event"),n?(i.initEvent(t,n.bubbles,n.cancelable),i.detail=n.detail):i.initEvent(t,!1,!1)),e.dispatchEvent(i)}function PO(e,t){return function(){return NO(this,e,t)}}function LO(e,t){return function(){return NO(this,e,t.apply(this,arguments))}}HU.prototype={constructor:HU,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)}},cO.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 DO=[null];function IO(e,t){this._groups=e,this._parents=t}IO.prototype={constructor:IO,select:function(e){"function"!=typeof e&&(e=IU(e));for(var t=this._groups,n=t.length,r=new Array(n),i=0;i<n;++i)for(var s,a,o=t[i],l=o.length,u=r[i]=new Array(l),c=0;c<l;++c)(s=o[c])&&(a=e.call(s,s.__data__,c,o))&&("__data__"in s&&(a.__data__=s.__data__),u[c]=a);return new IO(r,this._parents)},selectAll:function(e){e="function"==typeof e?OU(e):function(e){return null==e?UU:function(){return this.querySelectorAll(e)}}(e);for(var t=this._groups,n=t.length,r=[],i=[],s=0;s<n;++s)for(var a,o=t[s],l=o.length,u=0;u<l;++u)(a=o[u])&&(r.push(e.call(a,a.__data__,u,o)),i.push(a));return new IO(r,i)},selectChild:function(e){return this.select(null==e?kU:function(e){return function(){return BU.call(this.children,e)}}("function"==typeof e?e:FU(e)))},selectChildren:function(e){return this.selectAll(null==e?VU:function(e){return function(){return zU.call(this.children,e)}}("function"==typeof e?e:FU(e)))},filter:function(e){"function"!=typeof e&&(e=function(e){return function(){return this.matches(e)}}(e));for(var t=this._groups,n=t.length,r=new Array(n),i=0;i<n;++i)for(var s,a=t[i],o=a.length,l=r[i]=[],u=0;u<o;++u)(s=a[u])&&e.call(s,s.__data__,u,a)&&l.push(s);return new IO(r,this._parents)},data:function(e,t){if(!arguments.length)return Array.from(this,XU);var n=t?WU:jU,r=this._parents,i=this._groups;"function"!=typeof e&&(e=function(e){return function(){return e}}(e));for(var s=i.length,a=new Array(s),o=new Array(s),l=new Array(s),u=0;u<s;++u){var c=r[u],h=i[u],d=h.length,p=qU(e.call(c,c&&c.__data__,u,r)),f=p.length,m=o[u]=new Array(f),g=a[u]=new Array(f);n(c,h,m,g,l[u]=new Array(d),p,t);for(var _,v,y=0,x=0;y<f;++y)if(_=m[y]){for(y>=x&&(x=y+1);!(v=g[x])&&++x<f;);_._next=v||null}}return(a=new IO(a,r))._enter=o,a._exit=l,a},enter:function(){return new IO(this._enter||this._groups.map(GU),this._parents)},exit:function(){return new IO(this._exit||this._groups.map(GU),this._parents)},join:function(e,t,n){var r=this.enter(),i=this,s=this.exit();return"function"==typeof e?(r=e(r))&&(r=r.selection()):r=r.append(e+""),null!=t&&(i=t(i))&&(i=i.selection()),null==n?s.remove():n(s),r&&i?r.merge(i).order():i},merge:function(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,i=n.length,s=r.length,a=Math.min(i,s),o=new Array(i),l=0;l<a;++l)for(var u,c=n[l],h=r[l],d=c.length,p=o[l]=new Array(d),f=0;f<d;++f)(u=c[f]||h[f])&&(p[f]=u);for(;l<i;++l)o[l]=n[l];return new IO(o,this._parents)},selection:function(){return this},order:function(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r,i=e[t],s=i.length-1,a=i[s];--s>=0;)(r=i[s])&&(a&&4^r.compareDocumentPosition(a)&&a.parentNode.insertBefore(r,a),a=r);return this},sort:function(e){function t(t,n){return t&&n?e(t.__data__,n.__data__):!t-!n}e||(e=$U);for(var n=this._groups,r=n.length,i=new Array(r),s=0;s<r;++s){for(var a,o=n[s],l=o.length,u=i[s]=new Array(l),c=0;c<l;++c)(a=o[c])&&(u[c]=a);u.sort(t)}return new IO(i,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,n=e.length;t<n;++t)for(var r=e[t],i=0,s=r.length;i<s;++i){var a=r[i];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,n=0,r=t.length;n<r;++n)for(var i,s=t[n],a=0,o=s.length;a<o;++a)(i=s[a])&&e.call(i,i.__data__,a,s);return this},attr:function(e,t){var n=CU(e);if(arguments.length<2){var r=this.node();return n.local?r.getAttributeNS(n.space,n.local):r.getAttribute(n)}return this.each((null==t?n.local?KU:YU:"function"==typeof t?n.local?eO:JU:n.local?ZU:QU)(n,t))},style:function(e,t,n){return arguments.length>1?this.each((null==t?nO:"function"==typeof t?iO:rO)(e,t,null==n?"":n)):function(e,t){return e.style.getPropertyValue(t)||tO(e).getComputedStyle(e,null).getPropertyValue(t)}(this.node(),e)},property:function(e,t){return arguments.length>1?this.each((null==t?sO:"function"==typeof t?oO:aO)(e,t)):this.node()[e]},classed:function(e,t){var n=lO(e+"");if(arguments.length<2){for(var r=uO(this.node()),i=-1,s=n.length;++i<s;)if(!r.contains(n[i]))return!1;return!0}return this.each(("function"==typeof t?mO:t?pO:fO)(n,t))},text:function(e){return arguments.length?this.each(null==e?gO:("function"==typeof e?vO:_O)(e)):this.node().textContent},html:function(e){return arguments.length?this.each(null==e?yO:("function"==typeof e?bO:xO)(e)):this.node().innerHTML},raise:function(){return this.each(TO)},lower:function(){return this.each(SO)},append:function(e){var t="function"==typeof e?e:LU(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})},insert:function(e,t){var n="function"==typeof e?e:LU(e),r=null==t?MO:"function"==typeof t?t:IU(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})},remove:function(){return this.each(wO)},clone:function(e){return this.select(e?AO:EO)},datum:function(e){return arguments.length?this.property("__data__",e):this.node().__data__},on:function(e,t,n){var r,i,s=function(e){return e.trim().split(/^|\s+/).map(function(e){var t="",n=e.indexOf(".");return n>=0&&(t=e.slice(n+1),e=e.slice(0,n)),{type:e,name:t}})}(e+""),a=s.length;if(!(arguments.length<2)){for(o=t?CO:RO,r=0;r<a;++r)this.each(o(s[r],t,n));return this}var o=this.node().__on;if(o)for(var l,u=0,c=o.length;u<c;++u)for(r=0,l=o[u];r<a;++r)if((i=s[r]).type===l.type&&i.name===l.name)return l.value},dispatch:function(e,t){return this.each(("function"==typeof t?LO:PO)(e,t))},[Symbol.iterator]:function*(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r,i=e[t],s=0,a=i.length;s<a;++s)(r=i[s])&&(yield r)}};var UO,OO,FO,BO,kO,zO,VO,GO,HO,jO,WO,XO,qO={},$O=[],YO=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,KO=Array.isArray;function QO(e,t){for(var n in t)e[n]=t[n];return e}function ZO(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function JO(e,t,n,r,i){var s={type:e,props:t,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:null==i?++FO:i,__i:-1,__u:0};return null==i&&null!=OO.vnode&&OO.vnode(s),s}function eF(e){return e.children}function tF(e,t){this.props=e,this.context=t}function nF(e,t){if(null==t)return e.__?nF(e.__,e.__i+1):null;for(var n;t<e.__k.length;t++)if(null!=(n=e.__k[t])&&null!=n.__e)return n.__e;return"function"==typeof e.type?nF(e):null}function rF(e){var t,n;if(null!=(e=e.__)&&null!=e.__c){for(e.__e=e.__c.base=null,t=0;t<e.__k.length;t++)if(null!=(n=e.__k[t])&&null!=n.__e){e.__e=e.__c.base=n.__e;break}return rF(e)}}function iF(e){(!e.__d&&(e.__d=!0)&&kO.push(e)&&!sF.__r++||zO!=OO.debounceRendering)&&((zO=OO.debounceRendering)||VO)(sF)}function sF(){for(var e,t,n,r,i,s,a,o=1;kO.length;)kO.length>o&&kO.sort(GO),e=kO.shift(),o=kO.length,e.__d&&(n=void 0,i=(r=(t=e).__v).__e,s=[],a=[],t.__P&&((n=QO({},r)).__v=r.__v+1,OO.vnode&&OO.vnode(n),pF(t.__P,n,r,t.__n,t.__P.namespaceURI,32&r.__u?[i]:null,s,null==i?nF(r):i,!!(32&r.__u),a),n.__v=r.__v,n.__.__k[n.__i]=n,fF(s,n,a),n.__e!=i&&rF(n)));sF.__r=0}function aF(e,t,n,r,i,s,a,o,l,u,c){var h,d,p,f,m,g,_=r&&r.__k||$O,v=t.length;for(l=oF(n,t,_,l,v),h=0;h<v;h++)null!=(p=n.__k[h])&&(d=-1==p.__i?qO:_[p.__i]||qO,p.__i=h,g=pF(e,p,d,i,s,a,o,l,u,c),f=p.__e,p.ref&&d.ref!=p.ref&&(d.ref&&_F(d.ref,null,p),c.push(p.ref,p.__c||f,p)),null==m&&null!=f&&(m=f),4&p.__u||d.__k===p.__k?l=lF(p,l,e):"function"==typeof p.type&&void 0!==g?l=g:f&&(l=f.nextSibling),p.__u&=-7);return n.__e=m,l}function oF(e,t,n,r,i){var s,a,o,l,u,c=n.length,h=c,d=0;for(e.__k=new Array(i),s=0;s<i;s++)null!=(a=t[s])&&"boolean"!=typeof a&&"function"!=typeof a?(l=s+d,(a=e.__k[s]="string"==typeof a||"number"==typeof a||"bigint"==typeof a||a.constructor==String?JO(null,a,null,null,null):KO(a)?JO(eF,{children:a},null,null,null):null==a.constructor&&a.__b>0?JO(a.type,a.props,a.key,a.ref?a.ref:null,a.__v):a).__=e,a.__b=e.__b+1,o=null,-1!=(u=a.__i=uF(a,n,l,h))&&(h--,(o=n[u])&&(o.__u|=2)),null==o||null==o.__v?(-1==u&&(i>c?d--:i<c&&d++),"function"!=typeof a.type&&(a.__u|=4)):u!=l&&(u==l-1?d--:u==l+1?d++:(u>l?d--:d++,a.__u|=4))):e.__k[s]=null;if(h)for(s=0;s<c;s++)null!=(o=n[s])&&!(2&o.__u)&&(o.__e==r&&(r=nF(o)),vF(o,o));return r}function lF(e,t,n){var r,i;if("function"==typeof e.type){for(r=e.__k,i=0;r&&i<r.length;i++)r[i]&&(r[i].__=e,t=lF(r[i],t,n));return t}e.__e!=t&&(t&&e.type&&!n.contains(t)&&(t=nF(e)),n.insertBefore(e.__e,t||null),t=e.__e);do{t=t&&t.nextSibling}while(null!=t&&8==t.nodeType);return t}function uF(e,t,n,r){var i,s,a=e.key,o=e.type,l=t[n];if(null===l&&null==e.key||l&&a==l.key&&o==l.type&&!(2&l.__u))return n;if(r>(null==l||2&l.__u?0:1))for(i=n-1,s=n+1;i>=0||s<t.length;){if(i>=0){if((l=t[i])&&!(2&l.__u)&&a==l.key&&o==l.type)return i;i--}if(s<t.length){if((l=t[s])&&!(2&l.__u)&&a==l.key&&o==l.type)return s;s++}}return-1}function cF(e,t,n){"-"==t[0]?e.setProperty(t,null==n?"":n):e[t]=null==n?"":"number"!=typeof n||YO.test(t)?n:n+"px"}function hF(e,t,n,r,i){var s,a;e:if("style"==t)if("string"==typeof n)e.style.cssText=n;else{if("string"==typeof r&&(e.style.cssText=r=""),r)for(t in r)n&&t in n||cF(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||cF(e.style,t,n[t])}else if("o"==t[0]&&"n"==t[1])s=t!=(t=t.replace(HO,"$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+s]=n,n?r?n.u=r.u:(n.u=jO,e.addEventListener(t,s?XO:WO,s)):e.removeEventListener(t,s?XO:WO,s);else{if("http://www.w3.org/2000/svg"==i)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==n?"":n;break e}catch(e){}"function"==typeof n||(null==n||!1===n&&"-"!=t[4]?e.removeAttribute(t):e.setAttribute(t,"popover"==t&&1==n?"":n))}}function dF(e){return function(t){if(this.l){var n=this.l[t.type+e];if(null==t.t)t.t=jO++;else if(t.t<n.u)return;return n(OO.event?OO.event(t):t)}}}function pF(e,t,n,r,i,s,a,o,l,u){var c,h,d,p,f,m,g,_,v,y,x,b,T,S,M,w,E,A=t.type;if(null!=t.constructor)return null;128&n.__u&&(l=!!(32&n.__u),s=[o=t.__e=n.__e]),(c=OO.__b)&&c(t);e:if("function"==typeof A)try{if(_=t.props,v="prototype"in A&&A.prototype.render,y=(c=A.contextType)&&r[c.__c],x=c?y?y.props.value:c.__:r,n.__c?g=(h=t.__c=n.__c).__=h.__E:(v?t.__c=h=new A(_,x):(t.__c=h=new tF(_,x),h.constructor=A,h.render=yF),y&&y.sub(h),h.props=_,h.state||(h.state={}),h.context=x,h.__n=r,d=h.__d=!0,h.__h=[],h._sb=[]),v&&null==h.__s&&(h.__s=h.state),v&&null!=A.getDerivedStateFromProps&&(h.__s==h.state&&(h.__s=QO({},h.__s)),QO(h.__s,A.getDerivedStateFromProps(_,h.__s))),p=h.props,f=h.state,h.__v=t,d)v&&null==A.getDerivedStateFromProps&&null!=h.componentWillMount&&h.componentWillMount(),v&&null!=h.componentDidMount&&h.__h.push(h.componentDidMount);else{if(v&&null==A.getDerivedStateFromProps&&_!==p&&null!=h.componentWillReceiveProps&&h.componentWillReceiveProps(_,x),!h.__e&&null!=h.shouldComponentUpdate&&!1===h.shouldComponentUpdate(_,h.__s,x)||t.__v==n.__v){for(t.__v!=n.__v&&(h.props=_,h.state=h.__s,h.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(e){e&&(e.__=t)}),b=0;b<h._sb.length;b++)h.__h.push(h._sb[b]);h._sb=[],h.__h.length&&a.push(h);break e}null!=h.componentWillUpdate&&h.componentWillUpdate(_,h.__s,x),v&&null!=h.componentDidUpdate&&h.__h.push(function(){h.componentDidUpdate(p,f,m)})}if(h.context=x,h.props=_,h.__P=e,h.__e=!1,T=OO.__r,S=0,v){for(h.state=h.__s,h.__d=!1,T&&T(t),c=h.render(h.props,h.state,h.context),M=0;M<h._sb.length;M++)h.__h.push(h._sb[M]);h._sb=[]}else do{h.__d=!1,T&&T(t),c=h.render(h.props,h.state,h.context),h.state=h.__s}while(h.__d&&++S<25);h.state=h.__s,null!=h.getChildContext&&(r=QO(QO({},r),h.getChildContext())),v&&!d&&null!=h.getSnapshotBeforeUpdate&&(m=h.getSnapshotBeforeUpdate(p,f)),w=c,null!=c&&c.type===eF&&null==c.key&&(w=mF(c.props.children)),o=aF(e,KO(w)?w:[w],t,n,r,i,s,a,o,l,u),h.base=t.__e,t.__u&=-161,h.__h.length&&a.push(h),g&&(h.__E=h.__=null)}catch(e){if(t.__v=null,l||null!=s)if(e.then){for(t.__u|=l?160:128;o&&8==o.nodeType&&o.nextSibling;)o=o.nextSibling;s[s.indexOf(o)]=null,t.__e=o}else for(E=s.length;E--;)ZO(s[E]);else t.__e=n.__e,t.__k=n.__k;OO.__e(e,t,n)}else null==s&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):o=t.__e=gF(n.__e,t,n,r,i,s,a,l,u);return(c=OO.diffed)&&c(t),128&t.__u?void 0:o}function fF(e,t,n){for(var r=0;r<n.length;r++)_F(n[r],n[++r],n[++r]);OO.__c&&OO.__c(t,e),e.some(function(t){try{e=t.__h,t.__h=[],e.some(function(e){e.call(t)})}catch(e){OO.__e(e,t.__v)}})}function mF(e){return"object"!=typeof e||null==e||e.__b&&e.__b>0?e:KO(e)?e.map(mF):QO({},e)}function gF(e,t,n,r,i,s,a,o,l){var u,c,h,d,p,f,m,g=n.props,_=t.props,v=t.type;if("svg"==v?i="http://www.w3.org/2000/svg":"math"==v?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),null!=s)for(u=0;u<s.length;u++)if((p=s[u])&&"setAttribute"in p==!!v&&(v?p.localName==v:3==p.nodeType)){e=p,s[u]=null;break}if(null==e){if(null==v)return document.createTextNode(_);e=document.createElementNS(i,v,_.is&&_),o&&(OO.__m&&OO.__m(t,s),o=!1),s=null}if(null==v)g===_||o&&e.data==_||(e.data=_);else{if(s=s&&UO.call(e.childNodes),g=n.props||qO,!o&&null!=s)for(g={},u=0;u<e.attributes.length;u++)g[(p=e.attributes[u]).name]=p.value;for(u in g)if(p=g[u],"children"==u);else if("dangerouslySetInnerHTML"==u)h=p;else if(!(u in _)){if("value"==u&&"defaultValue"in _||"checked"==u&&"defaultChecked"in _)continue;hF(e,u,null,p,i)}for(u in _)p=_[u],"children"==u?d=p:"dangerouslySetInnerHTML"==u?c=p:"value"==u?f=p:"checked"==u?m=p:o&&"function"!=typeof p||g[u]===p||hF(e,u,p,g[u],i);if(c)o||h&&(c.__html==h.__html||c.__html==e.innerHTML)||(e.innerHTML=c.__html),t.__k=[];else if(h&&(e.innerHTML=""),aF("template"==t.type?e.content:e,KO(d)?d:[d],t,n,r,"foreignObject"==v?"http://www.w3.org/1999/xhtml":i,s,a,s?s[0]:n.__k&&nF(n,0),o,l),null!=s)for(u=s.length;u--;)ZO(s[u]);o||(u="value","progress"==v&&null==f?e.removeAttribute("value"):null!=f&&(f!==e[u]||"progress"==v&&!f||"option"==v&&f!=g[u])&&hF(e,u,f,g[u],i),u="checked",null!=m&&m!=e[u]&&hF(e,u,m,g[u],i))}return e}function _F(e,t,n){try{if("function"==typeof e){var r="function"==typeof e.__u;r&&e.__u(),r&&null==t||(e.__u=e(t))}else e.current=t}catch(e){OO.__e(e,n)}}function vF(e,t,n){var r,i;if(OO.unmount&&OO.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||_F(r,null,t)),null!=(r=e.__c)){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(e){OO.__e(e,t)}r.base=r.__P=null}if(r=e.__k)for(i=0;i<r.length;i++)r[i]&&vF(r[i],t,n||"function"!=typeof e.type);n||ZO(e.__e),e.__c=e.__=e.__e=void 0}function yF(e,t,n){return this.constructor(e,n)}function xF(e,t,n){var r,i,s;t==document&&(t=document.documentElement),OO.__&&OO.__(e,t),r=!1?null:t.__k,i=[],s=[],pF(t,e=t.__k=function(e,t,n){var r,i,s,a={};for(s in t)"key"==s?r=t[s]:"ref"==s?i=t[s]:a[s]=t[s];if(arguments.length>2&&(a.children=arguments.length>3?UO.call(arguments,2):n),"function"==typeof e&&null!=e.defaultProps)for(s in e.defaultProps)void 0===a[s]&&(a[s]=e.defaultProps[s]);return JO(e,a,r,i,null)}(eF,null,[e]),r||qO,qO,t.namespaceURI,r?null:t.firstChild?UO.call(t.childNodes):null,i,r?r.__e:t.firstChild,false,s),fF(i,e,s)}function bF(e,t,n){var r,i,s,a,o=QO({},e.props);for(s in e.type&&e.type.defaultProps&&(a=e.type.defaultProps),t)"key"==s?r=t[s]:"ref"==s?i=t[s]:o[s]=void 0===t[s]&&null!=a?a[s]:t[s];return arguments.length>2&&(o.children=arguments.length>3?UO.call(arguments,2):n),JO(e.type,o,r||e.key,i||e.ref,null)}function TF(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function SF(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t);if("object"!=typeof r)return r;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:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function MF(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function wF(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,s,a,o=[],l=!0,u=!1;try{if(s=(n=n.call(e)).next,0===t);else for(;!(l=(r=s.call(n)).done)&&(o.push(r.value),o.length!==t);l=!0);}catch(e){u=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(u)throw i}}return o}}(e,t)||function(e,t){if(e){if("string"==typeof e)return TF(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?TF(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)}UO=$O.slice,OO={__e:function(e,t,n,r){for(var i,s,a;t=t.__;)if((i=t.__c)&&!i.__)try{if((s=i.constructor)&&null!=s.getDerivedStateFromError&&(i.setState(s.getDerivedStateFromError(e)),a=i.__d),null!=i.componentDidCatch&&(i.componentDidCatch(e,r||{}),a=i.__d),a)return i.__E=i}catch(t){e=t}throw e}},FO=0,BO=function(e){return null!=e&&null==e.constructor},tF.prototype.setState=function(e,t){var n;n=null!=this.__s&&this.__s!=this.state?this.__s:this.__s=QO({},this.state),"function"==typeof e&&(e=e(QO({},n),this.props)),e&&QO(n,e),null!=e&&this.__v&&(t&&this._sb.push(t),iF(this))},tF.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),iF(this))},tF.prototype.render=eF,kO=[],VO="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,GO=function(e,t){return e.__v.__b-t.__v.__b},sF.__r=0,HO=/(PointerCapture)$|Capture$/i,jO=0,WO=dF(!1),XO=dF(!0);var AF=function(e){if("object"!==EF(e))return e;var t,n=bF(e);n.props&&(n.props=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?MF(Object(n),!0).forEach(function(t){SF(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):MF(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}({},n.props),null!=n&&null!==(t=n.props)&&void 0!==t&&t.children&&(n.props.children=Array.isArray(n.props.children)?n.props.children.map(AF):AF(n.props.children)));return n};!function(e,t){void 0===t&&(t={});var n=t.insertAt;if("undefined"!=typeof document){var r=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");i.type="text/css","top"===n&&r.firstChild?r.insertBefore(i,r.firstChild):r.appendChild(i),i.styleSheet?i.styleSheet.cssText=e:i.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 RF=Wh({props:{content:{default:!1},offsetX:{triggerUpdate:!1},offsetY:{triggerUpdate:!1}},init:function(e,t){var n=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).style,r=void 0===n?{}:n,i=function(e){return"string"==typeof e?new IO([[document.querySelector(e)]],[document.documentElement]):new IO([[e]],DO)}(!!e&&"object"===EF(e)&&!!e.node&&"function"==typeof e.node?e.node():e);"static"===i.style("position")&&i.style("position","relative"),t.tooltipEl=i.append("div").attr("class","float-tooltip-kap"),Object.entries(r).forEach(function(e){var n=wF(e,2),r=n[0],i=n[1];return t.tooltipEl.style(r,i)}),t.tooltipEl.style("left","-10000px").style("display","none");var s="tooltip-".concat(Math.round(1e12*Math.random()));t.mouseInside=!1,i.on("mousemove.".concat(s),function(e){t.mouseInside=!0;var n=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 n=t.ownerSVGElement||t;if(n.createSVGPoint){var r=n.createSVGPoint();return r.x=e.clientX,r.y=e.clientY,[(r=r.matrixTransform(t.getScreenCTM().inverse())).x,r.y]}if(t.getBoundingClientRect){var i=t.getBoundingClientRect();return[e.clientX-i.left-t.clientLeft,e.clientY-i.top-t.clientTop]}}return[e.pageX,e.pageY]}(e),r=i.node(),s=r.offsetWidth,a=r.offsetHeight,o=[null===t.offsetX||void 0===t.offsetX?"-".concat(n[0]/s*100,"%"):"number"==typeof t.offsetX?"calc(-50% + ".concat(t.offsetX,"px)"):t.offsetX,null===t.offsetY||void 0===t.offsetY?a>130&&a-n[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",n[0]+"px").style("top",n[1]+"px").style("transform","translate(".concat(o.join(","),")")),t.content&&t.tooltipEl.style("display","inline")}),i.on("mouseover.".concat(s),function(){t.mouseInside=!0,t.content&&t.tooltipEl.style("display","inline")}),i.on("mouseout.".concat(s),function(){t.mouseInside=!1,t.tooltipEl.style("display","none")})},update:function(e){var t,n;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 BO(bF(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(n=e.tooltipEl.node()).__k,xF(AF(t),n)):e.tooltipEl.text("")}});function CF(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function NF(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t);if("object"!=typeof r)return r;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:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function PF(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,s,a,o=[],l=!0,u=!1;try{if(s=(n=n.call(e)).next,0===t);else for(;!(l=(r=s.call(n)).done)&&(o.push(r.value),o.length!==t);l=!0);}catch(e){u=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(u)throw i}}return o}}(e,t)||DF(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 LF(e){return function(e){if(Array.isArray(e))return CF(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||DF(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 DF(e,t){if(e){if("string"==typeof e)return CF(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?CF(e,t):void 0}}!function(e,t){void 0===t&&(t={});var n=t.insertAt;if("undefined"!=typeof document){var r=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");i.type="text/css","top"===n&&r.firstChild?r.insertBefore(i,r.firstChild):r.appendChild(i),i.styleSheet?i.styleSheet.cssText=e:i.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}");var IF=window.THREE?window.THREE:{WebGLRenderer:class{constructor(e={}){const{canvas:t=Gt(),context:n=null,depth:r=!0,stencil:i=!1,alpha:a=!1,antialias:o=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:u=!1,powerPreference:c="default",failIfMajorPerformanceCaveat:h=!1,reverseDepthBuffer:d=!1}=e;let p;if(this.isWebGLRenderer=!0,null!==n){if("undefined"!=typeof WebGLRenderingContext&&n instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");p=n.getContextAttributes().alpha}else p=a;const f=new Uint32Array(4),m=new Int32Array(4);let g=null,_=null;const v=[],y=[];this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=0,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const x=this;let b=!1;this._outputColorSpace=rt;let T=0,S=0,M=null,w=-1,E=null;const A=new an,R=new an;let C=null;const N=new Nr(0);let P=0,L=t.width,D=t.height,I=1,U=null,O=null;const F=new an(0,0,L,D),B=new an(0,0,L,D);let k=!1;const z=new Xi;let V=!1,G=!1;const H=new Bn,j=new Bn,W=new Ut,X=new an,q={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let $=!1;function Y(){return null===M?I:1}let K,Q,Z,J,ee,re,ie,ae,le,pe,fe,me,ge,_e,ve,ye,be,Me,we,Ee,Ae,Re,Ce,Ne,Pe=n;function Le(e,n){return t.getContext(e,n)}try{const e={alpha:!0,depth:r,stencil:i,antialias:o,premultipliedAlpha:l,preserveDrawingBuffer:u,powerPreference:c,failIfMajorPerformanceCaveat:h};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${s}`),t.addEventListener("webglcontextlost",Ue,!1),t.addEventListener("webglcontextrestored",Oe,!1),t.addEventListener("webglcontextcreationerror",Fe,!1),null===Pe){const t="webgl2";if(Pe=Le(t,e),null===Pe)throw Le(t)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(e){throw console.error("THREE.WebGLRenderer: "+e.message),e}function De(){K=new Ja(Pe),K.init(),Re=new Kl(Pe,K),Q=new Pa(Pe,K,e,Re),Z=new $l(Pe,K),Q.reverseDepthBuffer&&d&&Z.buffers.depth.setReversed(!0),J=new no(Pe),ee=new Ul,re=new Yl(Pe,K,Z,ee,Q,Re,J),ie=new Da(x),ae=new Za(x),le=new ba(Pe),Ce=new Ca(Pe,le),pe=new eo(Pe,le,J,Ce),fe=new io(Pe,pe,le,J),we=new ro(Pe,Q,re),ye=new La(ee),me=new Il(x,ie,ae,K,Q,Ce,ye),ge=new tu(x,ee),_e=new kl,ve=new Wl(K),Me=new Ra(x,ie,ae,Z,fe,p,l),be=new Xl(x,fe,Q),Ne=new nu(Pe,J,Q,Z),Ee=new Na(Pe,K,J),Ae=new to(Pe,K,J),J.programs=me.programs,x.capabilities=Q,x.extensions=K,x.properties=ee,x.renderLists=_e,x.shadowMap=be,x.state=Z,x.info=J}De();const Ie=new Zl(x,Pe);function Ue(e){e.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),b=!0}function Oe(){console.log("THREE.WebGLRenderer: Context Restored."),b=!1;const e=J.autoReset,t=be.enabled,n=be.autoUpdate,r=be.needsUpdate,i=be.type;De(),J.autoReset=e,be.enabled=t,be.autoUpdate=n,be.needsUpdate=r,be.type=i}function Fe(e){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",e.statusMessage)}function Be(e){const t=e.target;t.removeEventListener("dispose",Be),function(e){(function(e){const t=ee.get(e).programs;void 0!==t&&(t.forEach(function(e){me.releaseProgram(e)}),e.isShaderMaterial&&me.releaseShaderCache(e))})(e),ee.remove(e)}(t)}function ke(e,t,n){!0===e.transparent&&2===e.side&&!1===e.forceSinglePass?(e.side=1,e.needsUpdate=!0,Ye(e,t,n),e.side=0,e.needsUpdate=!0,Ye(e,t,n),e.side=2):Ye(e,t,n)}this.xr=Ie,this.getContext=function(){return Pe},this.getContextAttributes=function(){return Pe.getContextAttributes()},this.forceContextLoss=function(){const e=K.get("WEBGL_lose_context");e&&e.loseContext()},this.forceContextRestore=function(){const e=K.get("WEBGL_lose_context");e&&e.restoreContext()},this.getPixelRatio=function(){return I},this.setPixelRatio=function(e){void 0!==e&&(I=e,this.setSize(L,D,!1))},this.getSize=function(e){return e.set(L,D)},this.setSize=function(e,n,r=!0){Ie.isPresenting?console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting."):(L=e,D=n,t.width=Math.floor(e*I),t.height=Math.floor(n*I),!0===r&&(t.style.width=e+"px",t.style.height=n+"px"),this.setViewport(0,0,e,n))},this.getDrawingBufferSize=function(e){return e.set(L*I,D*I).floor()},this.setDrawingBufferSize=function(e,n,r){L=e,D=n,I=r,t.width=Math.floor(e*r),t.height=Math.floor(n*r),this.setViewport(0,0,e,n)},this.getCurrentViewport=function(e){return e.copy(A)},this.getViewport=function(e){return e.copy(F)},this.setViewport=function(e,t,n,r){e.isVector4?F.set(e.x,e.y,e.z,e.w):F.set(e,t,n,r),Z.viewport(A.copy(F).multiplyScalar(I).round())},this.getScissor=function(e){return e.copy(B)},this.setScissor=function(e,t,n,r){e.isVector4?B.set(e.x,e.y,e.z,e.w):B.set(e,t,n,r),Z.scissor(R.copy(B).multiplyScalar(I).round())},this.getScissorTest=function(){return k},this.setScissorTest=function(e){Z.setScissorTest(k=e)},this.setOpaqueSort=function(e){U=e},this.setTransparentSort=function(e){O=e},this.getClearColor=function(e){return e.copy(Me.getClearColor())},this.setClearColor=function(){Me.setClearColor(...arguments)},this.getClearAlpha=function(){return Me.getClearAlpha()},this.setClearAlpha=function(){Me.setClearAlpha(...arguments)},this.clear=function(e=!0,t=!0,n=!0){let r=0;if(e){let e=!1;if(null!==M){const t=M.texture.format;e=t===Se||t===Te||t===xe}if(e){const e=M.texture.type,t=e===ne||e===oe||e===se||e===de||e===ce||e===he,n=Me.getClearColor(),r=Me.getClearAlpha(),i=n.r,s=n.g,a=n.b;t?(f[0]=i,f[1]=s,f[2]=a,f[3]=r,Pe.clearBufferuiv(Pe.COLOR,0,f)):(m[0]=i,m[1]=s,m[2]=a,m[3]=r,Pe.clearBufferiv(Pe.COLOR,0,m))}else r|=Pe.COLOR_BUFFER_BIT}t&&(r|=Pe.DEPTH_BUFFER_BIT),n&&(r|=Pe.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),Pe.clear(r)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){t.removeEventListener("webglcontextlost",Ue,!1),t.removeEventListener("webglcontextrestored",Oe,!1),t.removeEventListener("webglcontextcreationerror",Fe,!1),Me.dispose(),_e.dispose(),ve.dispose(),ee.dispose(),ie.dispose(),ae.dispose(),fe.dispose(),Ce.dispose(),Ne.dispose(),me.dispose(),Ie.dispose(),Ie.removeEventListener("sessionstart",Ve),Ie.removeEventListener("sessionend",Ge),He.stop()},this.renderBufferDirect=function(e,t,n,r,i,s){null===t&&(t=q);const a=i.isMesh&&i.matrixWorld.determinant()<0,o=function(e,t,n,r,i){!0!==t.isScene&&(t=q);re.resetTextureUnits();const s=t.fog,a=r.isMeshStandardMaterial?t.environment:null,o=null===M?x.outputColorSpace:!0===M.isXRRenderTarget?M.texture.colorSpace:it,l=(r.isMeshStandardMaterial?ae:ie).get(r.envMap||a),u=!0===r.vertexColors&&!!n.attributes.color&&4===n.attributes.color.itemSize,c=!!n.attributes.tangent&&(!!r.normalMap||r.anisotropy>0),h=!!n.morphAttributes.position,d=!!n.morphAttributes.normal,p=!!n.morphAttributes.color;let f=0;r.toneMapped&&(null!==M&&!0!==M.isXRRenderTarget||(f=x.toneMapping));const m=n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color,g=void 0!==m?m.length:0,v=ee.get(r),y=_.state.lights;if(!0===V&&(!0===G||e!==E)){const t=e===E&&r.id===w;ye.setState(r,e,t)}let b=!1;r.version===v.__version?v.needsLights&&v.lightsStateVersion!==y.state.version||v.outputColorSpace!==o||i.isBatchedMesh&&!1===v.batching?b=!0:i.isBatchedMesh||!0!==v.batching?i.isBatchedMesh&&!0===v.batchingColor&&null===i.colorTexture||i.isBatchedMesh&&!1===v.batchingColor&&null!==i.colorTexture||i.isInstancedMesh&&!1===v.instancing?b=!0:i.isInstancedMesh||!0!==v.instancing?i.isSkinnedMesh&&!1===v.skinning?b=!0:i.isSkinnedMesh||!0!==v.skinning?i.isInstancedMesh&&!0===v.instancingColor&&null===i.instanceColor||i.isInstancedMesh&&!1===v.instancingColor&&null!==i.instanceColor||i.isInstancedMesh&&!0===v.instancingMorph&&null===i.morphTexture||i.isInstancedMesh&&!1===v.instancingMorph&&null!==i.morphTexture||v.envMap!==l||!0===r.fog&&v.fog!==s?b=!0:void 0===v.numClippingPlanes||v.numClippingPlanes===ye.numPlanes&&v.numIntersection===ye.numIntersection?(v.vertexAlphas!==u||v.vertexTangents!==c||v.morphTargets!==h||v.morphNormals!==d||v.morphColors!==p||v.toneMapping!==f||v.morphTargetsCount!==g)&&(b=!0):b=!0:b=!0:b=!0:b=!0:(b=!0,v.__version=r.version);let T=v.currentProgram;!0===b&&(T=Ye(r,t,i));let S=!1,A=!1,R=!1;const C=T.getUniforms(),N=v.uniforms;Z.useProgram(T.program)&&(S=!0,A=!0,R=!0);r.id!==w&&(w=r.id,A=!0);if(S||E!==e){Z.buffers.depth.getReversed()?(H.copy(e.projectionMatrix),function(e){const t=e.elements;t[2]=.5*t[2]+.5*t[3],t[6]=.5*t[6]+.5*t[7],t[10]=.5*t[10]+.5*t[11],t[14]=.5*t[14]+.5*t[15]}(H),function(e){const t=e.elements;-1===t[11]?(t[10]=-t[10]-1,t[14]=-t[14]):(t[10]=-t[10],t[14]=1-t[14])}(H),C.setValue(Pe,"projectionMatrix",H)):C.setValue(Pe,"projectionMatrix",e.projectionMatrix),C.setValue(Pe,"viewMatrix",e.matrixWorldInverse);const t=C.map.cameraPosition;void 0!==t&&t.setValue(Pe,W.setFromMatrixPosition(e.matrixWorld)),Q.logarithmicDepthBuffer&&C.setValue(Pe,"logDepthBufFC",2/(Math.log(e.far+1)/Math.LN2)),(r.isMeshPhongMaterial||r.isMeshToonMaterial||r.isMeshLambertMaterial||r.isMeshBasicMaterial||r.isMeshStandardMaterial||r.isShaderMaterial)&&C.setValue(Pe,"isOrthographic",!0===e.isOrthographicCamera),E!==e&&(E=e,A=!0,R=!0)}if(i.isSkinnedMesh){C.setOptional(Pe,i,"bindMatrix"),C.setOptional(Pe,i,"bindMatrixInverse");const e=i.skeleton;e&&(null===e.boneTexture&&e.computeBoneTexture(),C.setValue(Pe,"boneTexture",e.boneTexture,re))}i.isBatchedMesh&&(C.setOptional(Pe,i,"batchingTexture"),C.setValue(Pe,"batchingTexture",i._matricesTexture,re),C.setOptional(Pe,i,"batchingIdTexture"),C.setValue(Pe,"batchingIdTexture",i._indirectTexture,re),C.setOptional(Pe,i,"batchingColorTexture"),null!==i._colorsTexture&&C.setValue(Pe,"batchingColorTexture",i._colorsTexture,re));const P=n.morphAttributes;void 0===P.position&&void 0===P.normal&&void 0===P.color||we.update(i,n,T);(A||v.receiveShadow!==i.receiveShadow)&&(v.receiveShadow=i.receiveShadow,C.setValue(Pe,"receiveShadow",i.receiveShadow));r.isMeshGouraudMaterial&&null!==r.envMap&&(N.envMap.value=l,N.flipEnvMap.value=l.isCubeTexture&&!1===l.isRenderTargetTexture?-1:1);r.isMeshStandardMaterial&&null===r.envMap&&null!==t.environment&&(N.envMapIntensity.value=t.environmentIntensity);A&&(C.setValue(Pe,"toneMappingExposure",x.toneMappingExposure),v.needsLights&&(U=R,(L=N).ambientLightColor.needsUpdate=U,L.lightProbe.needsUpdate=U,L.directionalLights.needsUpdate=U,L.directionalLightShadows.needsUpdate=U,L.pointLights.needsUpdate=U,L.pointLightShadows.needsUpdate=U,L.spotLights.needsUpdate=U,L.spotLightShadows.needsUpdate=U,L.rectAreaLights.needsUpdate=U,L.hemisphereLights.needsUpdate=U),s&&!0===r.fog&&ge.refreshFogUniforms(N,s),ge.refreshMaterialUniforms(N,r,I,D,_.state.transmissionRenderTarget[e.id]),cl.upload(Pe,Ke(v),N,re));var L,U;r.isShaderMaterial&&!0===r.uniformsNeedUpdate&&(cl.upload(Pe,Ke(v),N,re),r.uniformsNeedUpdate=!1);r.isSpriteMaterial&&C.setValue(Pe,"center",i.center);if(C.setValue(Pe,"modelViewMatrix",i.modelViewMatrix),C.setValue(Pe,"normalMatrix",i.normalMatrix),C.setValue(Pe,"modelMatrix",i.matrixWorld),r.isShaderMaterial||r.isRawShaderMaterial){const e=r.uniformsGroups;for(let t=0,n=e.length;t<n;t++){const n=e[t];Ne.update(n,T),Ne.bind(n,T)}}return T}(e,t,n,r,i);Z.setMaterial(r,a);let l=n.index,u=1;if(!0===r.wireframe){if(l=pe.getWireframeAttribute(n),void 0===l)return;u=2}const c=n.drawRange,h=n.attributes.position;let d=c.start*u,p=(c.start+c.count)*u;null!==s&&(d=Math.max(d,s.start*u),p=Math.min(p,(s.start+s.count)*u)),null!==l?(d=Math.max(d,0),p=Math.min(p,l.count)):null!=h&&(d=Math.max(d,0),p=Math.min(p,h.count));const f=p-d;if(f<0||f===1/0)return;let m;Ce.setup(i,r,o,n,l);let g=Ee;if(null!==l&&(m=le.get(l),g=Ae,g.setIndex(m)),i.isMesh)!0===r.wireframe?(Z.setLineWidth(r.wireframeLinewidth*Y()),g.setMode(Pe.LINES)):g.setMode(Pe.TRIANGLES);else if(i.isLine){let e=r.linewidth;void 0===e&&(e=1),Z.setLineWidth(e*Y()),i.isLineSegments?g.setMode(Pe.LINES):i.isLineLoop?g.setMode(Pe.LINE_LOOP):g.setMode(Pe.LINE_STRIP)}else i.isPoints?g.setMode(Pe.POINTS):i.isSprite&&g.setMode(Pe.TRIANGLES);if(i.isBatchedMesh)if(null!==i._multiDrawInstances)jt("THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),g.renderMultiDrawInstances(i._multiDrawStarts,i._multiDrawCounts,i._multiDrawCount,i._multiDrawInstances);else if(K.get("WEBGL_multi_draw"))g.renderMultiDraw(i._multiDrawStarts,i._multiDrawCounts,i._multiDrawCount);else{const e=i._multiDrawStarts,t=i._multiDrawCounts,n=i._multiDrawCount,s=l?le.get(l).bytesPerElement:1,a=ee.get(r).currentProgram.getUniforms();for(let r=0;r<n;r++)a.setValue(Pe,"_gl_DrawID",r),g.render(e[r]/s,t[r])}else if(i.isInstancedMesh)g.renderInstances(d,f,i.count);else if(n.isInstancedBufferGeometry){const e=void 0!==n._maxInstanceCount?n._maxInstanceCount:1/0,t=Math.min(n.instanceCount,e);g.renderInstances(d,f,t)}else g.render(d,f)},this.compile=function(e,t,n=null){null===n&&(n=e),_=ve.get(n),_.init(t),y.push(_),n.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(_.pushLight(e),e.castShadow&&_.pushShadow(e))}),e!==n&&e.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(_.pushLight(e),e.castShadow&&_.pushShadow(e))}),_.setupLights();const r=new Set;return e.traverse(function(e){if(!(e.isMesh||e.isPoints||e.isLine||e.isSprite))return;const t=e.material;if(t)if(Array.isArray(t))for(let i=0;i<t.length;i++){const s=t[i];ke(s,n,e),r.add(s)}else ke(t,n,e),r.add(t)}),_=y.pop(),r},this.compileAsync=function(e,t,n=null){const r=this.compile(e,t,n);return new Promise(t=>{function n(){r.forEach(function(e){ee.get(e).currentProgram.isReady()&&r.delete(e)}),0!==r.size?setTimeout(n,10):t(e)}null!==K.get("KHR_parallel_shader_compile")?n():setTimeout(n,10)})};let ze=null;function Ve(){He.stop()}function Ge(){He.start()}const He=new xa;function je(e,t,n,r){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)n=e.renderOrder;else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)_.pushLight(e),e.castShadow&&_.pushShadow(e);else if(e.isSprite){if(!e.frustumCulled||z.intersectsSprite(e)){r&&X.setFromMatrixPosition(e.matrixWorld).applyMatrix4(j);const t=fe.update(e),i=e.material;i.visible&&g.push(e,t,i,n,X.z,null)}}else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||z.intersectsObject(e))){const t=fe.update(e),i=e.material;if(r&&(void 0!==e.boundingSphere?(null===e.boundingSphere&&e.computeBoundingSphere(),X.copy(e.boundingSphere.center)):(null===t.boundingSphere&&t.computeBoundingSphere(),X.copy(t.boundingSphere.center)),X.applyMatrix4(e.matrixWorld).applyMatrix4(j)),Array.isArray(i)){const r=t.groups;for(let s=0,a=r.length;s<a;s++){const a=r[s],o=i[a.materialIndex];o&&o.visible&&g.push(e,t,o,n,X.z,a)}}else i.visible&&g.push(e,t,i,n,X.z,null)}const i=e.children;for(let e=0,s=i.length;e<s;e++)je(i[e],t,n,r)}function We(e,t,n,r){const i=e.opaque,s=e.transmissive,a=e.transparent;_.setupLightsView(n),!0===V&&ye.setGlobalState(x.clippingPlanes,n),r&&Z.viewport(A.copy(r)),i.length>0&&qe(i,t,n),s.length>0&&qe(s,t,n),a.length>0&&qe(a,t,n),Z.buffers.depth.setTest(!0),Z.buffers.depth.setMask(!0),Z.buffers.color.setMask(!0),Z.setPolygonOffset(!1)}function Xe(e,t,n,r){if(null!==(!0===n.isScene?n.overrideMaterial:null))return;void 0===_.state.transmissionRenderTarget[r.id]&&(_.state.transmissionRenderTarget[r.id]=new ln(1,1,{generateMipmaps:!0,type:K.has("EXT_color_buffer_half_float")||K.has("EXT_color_buffer_float")?ue:ne,minFilter:te,samples:4,stencilBuffer:i,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:$t.workingColorSpace}));const s=_.state.transmissionRenderTarget[r.id],a=r.viewport||A;s.setSize(a.z*x.transmissionResolutionScale,a.w*x.transmissionResolutionScale);const o=x.getRenderTarget(),l=x.getActiveCubeFace(),u=x.getActiveMipmapLevel();x.setRenderTarget(s),x.getClearColor(N),P=x.getClearAlpha(),P<1&&x.setClearColor(16777215,.5),x.clear(),$&&Me.render(n);const c=x.toneMapping;x.toneMapping=0;const h=r.viewport;if(void 0!==r.viewport&&(r.viewport=void 0),_.setupLightsView(r),!0===V&&ye.setGlobalState(x.clippingPlanes,r),qe(e,n,r),re.updateMultisampleRenderTarget(s),re.updateRenderTargetMipmap(s),!1===K.has("WEBGL_multisampled_render_to_texture")){let e=!1;for(let i=0,s=t.length;i<s;i++){const s=t[i],a=s.object,o=s.geometry,l=s.material,u=s.group;if(2===l.side&&a.layers.test(r.layers)){const t=l.side;l.side=1,l.needsUpdate=!0,$e(a,n,r,o,l,u),l.side=t,l.needsUpdate=!0,e=!0}}!0===e&&(re.updateMultisampleRenderTarget(s),re.updateRenderTargetMipmap(s))}x.setRenderTarget(o,l,u),x.setClearColor(N,P),void 0!==h&&(r.viewport=h),x.toneMapping=c}function qe(e,t,n){const r=!0===t.isScene?t.overrideMaterial:null;for(let i=0,s=e.length;i<s;i++){const s=e[i],a=s.object,o=s.geometry,l=s.group;let u=s.material;!0===u.allowOverride&&null!==r&&(u=r),a.layers.test(n.layers)&&$e(a,t,n,o,u,l)}}function $e(e,t,n,r,i,s){e.onBeforeRender(x,t,n,r,i,s),e.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix),i.onBeforeRender(x,t,n,r,e,s),!0===i.transparent&&2===i.side&&!1===i.forceSinglePass?(i.side=1,i.needsUpdate=!0,x.renderBufferDirect(n,t,r,i,e,s),i.side=0,i.needsUpdate=!0,x.renderBufferDirect(n,t,r,i,e,s),i.side=2):x.renderBufferDirect(n,t,r,i,e,s),e.onAfterRender(x,t,n,r,i,s)}function Ye(e,t,n){!0!==t.isScene&&(t=q);const r=ee.get(e),i=_.state.lights,s=_.state.shadowsArray,a=i.state.version,o=me.getParameters(e,i.state,s,t,n),l=me.getProgramCacheKey(o);let u=r.programs;r.environment=e.isMeshStandardMaterial?t.environment:null,r.fog=t.fog,r.envMap=(e.isMeshStandardMaterial?ae:ie).get(e.envMap||r.environment),r.envMapRotation=null!==r.environment&&null===e.envMap?t.environmentRotation:e.envMapRotation,void 0===u&&(e.addEventListener("dispose",Be),u=new Map,r.programs=u);let c=u.get(l);if(void 0!==c){if(r.currentProgram===c&&r.lightsStateVersion===a)return Qe(e,o),c}else o.uniforms=me.getUniforms(e),e.onBeforeCompile(o,x),c=me.acquireProgram(o,l),u.set(l,c),r.uniforms=o.uniforms;const h=r.uniforms;return(e.isShaderMaterial||e.isRawShaderMaterial)&&!0!==e.clipping||(h.clippingPlanes=ye.uniform),Qe(e,o),r.needsLights=function(e){return e.isMeshLambertMaterial||e.isMeshToonMaterial||e.isMeshPhongMaterial||e.isMeshStandardMaterial||e.isShadowMaterial||e.isShaderMaterial&&!0===e.lights}(e),r.lightsStateVersion=a,r.needsLights&&(h.ambientLightColor.value=i.state.ambient,h.lightProbe.value=i.state.probe,h.directionalLights.value=i.state.directional,h.directionalLightShadows.value=i.state.directionalShadow,h.spotLights.value=i.state.spot,h.spotLightShadows.value=i.state.spotShadow,h.rectAreaLights.value=i.state.rectArea,h.ltc_1.value=i.state.rectAreaLTC1,h.ltc_2.value=i.state.rectAreaLTC2,h.pointLights.value=i.state.point,h.pointLightShadows.value=i.state.pointShadow,h.hemisphereLights.value=i.state.hemi,h.directionalShadowMap.value=i.state.directionalShadowMap,h.directionalShadowMatrix.value=i.state.directionalShadowMatrix,h.spotShadowMap.value=i.state.spotShadowMap,h.spotLightMatrix.value=i.state.spotLightMatrix,h.spotLightMap.value=i.state.spotLightMap,h.pointShadowMap.value=i.state.pointShadowMap,h.pointShadowMatrix.value=i.state.pointShadowMatrix),r.currentProgram=c,r.uniformsList=null,c}function Ke(e){if(null===e.uniformsList){const t=e.currentProgram.getUniforms();e.uniformsList=cl.seqWithValue(t.seq,e.uniforms)}return e.uniformsList}function Qe(e,t){const n=ee.get(e);n.outputColorSpace=t.outputColorSpace,n.batching=t.batching,n.batchingColor=t.batchingColor,n.instancing=t.instancing,n.instancingColor=t.instancingColor,n.instancingMorph=t.instancingMorph,n.skinning=t.skinning,n.morphTargets=t.morphTargets,n.morphNormals=t.morphNormals,n.morphColors=t.morphColors,n.morphTargetsCount=t.morphTargetsCount,n.numClippingPlanes=t.numClippingPlanes,n.numIntersection=t.numClipIntersection,n.vertexAlphas=t.vertexAlphas,n.vertexTangents=t.vertexTangents,n.toneMapping=t.toneMapping}He.setAnimationLoop(function(e){ze&&ze(e)}),"undefined"!=typeof self&&He.setContext(self),this.setAnimationLoop=function(e){ze=e,Ie.setAnimationLoop(e),null===e?He.stop():He.start()},Ie.addEventListener("sessionstart",Ve),Ie.addEventListener("sessionend",Ge),this.render=function(e,t){if(void 0!==t&&!0!==t.isCamera)return void console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");if(!0===b)return;if(!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&!0===t.matrixWorldAutoUpdate&&t.updateMatrixWorld(),!0===Ie.enabled&&!0===Ie.isPresenting&&(!0===Ie.cameraAutoUpdate&&Ie.updateCamera(t),t=Ie.getCamera()),!0===e.isScene&&e.onBeforeRender(x,e,t,M),_=ve.get(e,y.length),_.init(t),y.push(_),j.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),z.setFromProjectionMatrix(j),G=this.localClippingEnabled,V=ye.init(this.clippingPlanes,G),g=_e.get(e,v.length),g.init(),v.push(g),!0===Ie.enabled&&!0===Ie.isPresenting){const e=x.xr.getDepthSensingMesh();null!==e&&je(e,t,-1/0,x.sortObjects)}je(e,t,0,x.sortObjects),g.finish(),!0===x.sortObjects&&g.sort(U,O),$=!1===Ie.enabled||!1===Ie.isPresenting||!1===Ie.hasDepthSensing(),$&&Me.addToRenderList(g,e),this.info.render.frame++,!0===V&&ye.beginShadows();const n=_.state.shadowsArray;be.render(n,e,t),!0===V&&ye.endShadows(),!0===this.info.autoReset&&this.info.reset();const r=g.opaque,i=g.transmissive;if(_.setupLights(),t.isArrayCamera){const n=t.cameras;if(i.length>0)for(let t=0,s=n.length;t<s;t++){Xe(r,i,e,n[t])}$&&Me.render(e);for(let t=0,r=n.length;t<r;t++){const r=n[t];We(g,e,r,r.viewport)}}else i.length>0&&Xe(r,i,e,t),$&&Me.render(e),We(g,e,t);null!==M&&0===S&&(re.updateMultisampleRenderTarget(M),re.updateRenderTargetMipmap(M)),!0===e.isScene&&e.onAfterRender(x,e,t),Ce.resetDefaultState(),w=-1,E=null,y.pop(),y.length>0?(_=y[y.length-1],!0===V&&ye.setGlobalState(x.clippingPlanes,_.state.camera)):_=null,v.pop(),g=v.length>0?v[v.length-1]:null},this.getActiveCubeFace=function(){return T},this.getActiveMipmapLevel=function(){return S},this.getRenderTarget=function(){return M},this.setRenderTargetTextures=function(e,t,n){const r=ee.get(e);r.__autoAllocateDepthBuffer=!1===e.resolveDepthBuffer,!1===r.__autoAllocateDepthBuffer&&(r.__useRenderToTexture=!1),ee.get(e.texture).__webglTexture=t,ee.get(e.depthTexture).__webglTexture=r.__autoAllocateDepthBuffer?void 0:n,r.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(e,t){const n=ee.get(e);n.__webglFramebuffer=t,n.__useDefaultFramebuffer=void 0===t};const Ze=Pe.createFramebuffer();this.setRenderTarget=function(e,t=0,n=0){M=e,T=t,S=n;let r=!0,i=null,s=!1,a=!1;if(e){const o=ee.get(e);if(void 0!==o.__useDefaultFramebuffer)Z.bindFramebuffer(Pe.FRAMEBUFFER,null),r=!1;else if(void 0===o.__webglFramebuffer)re.setupRenderTarget(e);else if(o.__hasExternalTextures)re.rebindTextures(e,ee.get(e.texture).__webglTexture,ee.get(e.depthTexture).__webglTexture);else if(e.depthBuffer){const t=e.depthTexture;if(o.__boundDepthTexture!==t){if(null!==t&&ee.has(t)&&(e.width!==t.image.width||e.height!==t.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");re.setupDepthRenderbuffer(e)}}const l=e.texture;(l.isData3DTexture||l.isDataArrayTexture||l.isCompressedArrayTexture)&&(a=!0);const u=ee.get(e).__webglFramebuffer;e.isWebGLCubeRenderTarget?(i=Array.isArray(u[t])?u[t][n]:u[t],s=!0):i=e.samples>0&&!1===re.useMultisampledRTT(e)?ee.get(e).__webglMultisampledFramebuffer:Array.isArray(u)?u[n]:u,A.copy(e.viewport),R.copy(e.scissor),C=e.scissorTest}else A.copy(F).multiplyScalar(I).floor(),R.copy(B).multiplyScalar(I).floor(),C=k;0!==n&&(i=Ze);if(Z.bindFramebuffer(Pe.FRAMEBUFFER,i)&&r&&Z.drawBuffers(e,i),Z.viewport(A),Z.scissor(R),Z.setScissorTest(C),s){const r=ee.get(e.texture);Pe.framebufferTexture2D(Pe.FRAMEBUFFER,Pe.COLOR_ATTACHMENT0,Pe.TEXTURE_CUBE_MAP_POSITIVE_X+t,r.__webglTexture,n)}else if(a){const r=ee.get(e.texture),i=t;Pe.framebufferTextureLayer(Pe.FRAMEBUFFER,Pe.COLOR_ATTACHMENT0,r.__webglTexture,n,i)}else if(null!==e&&0!==n){const t=ee.get(e.texture);Pe.framebufferTexture2D(Pe.FRAMEBUFFER,Pe.COLOR_ATTACHMENT0,Pe.TEXTURE_2D,t.__webglTexture,n)}w=-1},this.readRenderTargetPixels=function(e,t,n,r,i,s,a,o=0){if(!e||!e.isWebGLRenderTarget)return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let l=ee.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&void 0!==a&&(l=l[a]),l){Z.bindFramebuffer(Pe.FRAMEBUFFER,l);try{const a=e.textures[o],l=a.format,u=a.type;if(!Q.textureFormatReadable(l))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");if(!Q.textureTypeReadable(u))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i&&(e.textures.length>1&&Pe.readBuffer(Pe.COLOR_ATTACHMENT0+o),Pe.readPixels(t,n,r,i,Re.convert(l),Re.convert(u),s))}finally{const e=null!==M?ee.get(M).__webglFramebuffer:null;Z.bindFramebuffer(Pe.FRAMEBUFFER,e)}}},this.readRenderTargetPixelsAsync=async function(e,t,n,r,i,s,a,o=0){if(!e||!e.isWebGLRenderTarget)throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let l=ee.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&void 0!==a&&(l=l[a]),l){if(t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i){Z.bindFramebuffer(Pe.FRAMEBUFFER,l);const a=e.textures[o],u=a.format,c=a.type;if(!Q.textureFormatReadable(u))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!Q.textureTypeReadable(c))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const h=Pe.createBuffer();Pe.bindBuffer(Pe.PIXEL_PACK_BUFFER,h),Pe.bufferData(Pe.PIXEL_PACK_BUFFER,s.byteLength,Pe.STREAM_READ),e.textures.length>1&&Pe.readBuffer(Pe.COLOR_ATTACHMENT0+o),Pe.readPixels(t,n,r,i,Re.convert(u),Re.convert(c),0);const d=null!==M?ee.get(M).__webglFramebuffer:null;Z.bindFramebuffer(Pe.FRAMEBUFFER,d);const p=Pe.fenceSync(Pe.SYNC_GPU_COMMANDS_COMPLETE,0);return Pe.flush(),await function(e,t,n){return new Promise(function(r,i){setTimeout(function s(){switch(e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0)){case e.WAIT_FAILED:i();break;case e.TIMEOUT_EXPIRED:setTimeout(s,n);break;default:r()}},n)})}(Pe,p,4),Pe.bindBuffer(Pe.PIXEL_PACK_BUFFER,h),Pe.getBufferSubData(Pe.PIXEL_PACK_BUFFER,0,s),Pe.deleteBuffer(h),Pe.deleteSync(p),s}throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")}},this.copyFramebufferToTexture=function(e,t=null,n=0){const r=Math.pow(2,-n),i=Math.floor(e.image.width*r),s=Math.floor(e.image.height*r),a=null!==t?t.x:0,o=null!==t?t.y:0;re.setTexture2D(e,0),Pe.copyTexSubImage2D(Pe.TEXTURE_2D,n,0,0,a,o,i,s),Z.unbindTexture()};const Je=Pe.createFramebuffer(),et=Pe.createFramebuffer();this.copyTextureToTexture=function(e,t,n=null,r=null,i=0,s=null){let a,o,l,u,c,h,d,p,f;null===s&&(0!==i?(jt("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),s=i,i=0):s=0);const m=e.isCompressedTexture?e.mipmaps[s]:e.image;if(null!==n)a=n.max.x-n.min.x,o=n.max.y-n.min.y,l=n.isBox3?n.max.z-n.min.z:1,u=n.min.x,c=n.min.y,h=n.isBox3?n.min.z:0;else{const t=Math.pow(2,-i);a=Math.floor(m.width*t),o=Math.floor(m.height*t),l=e.isDataArrayTexture?m.depth:e.isData3DTexture?Math.floor(m.depth*t):1,u=0,c=0,h=0}null!==r?(d=r.x,p=r.y,f=r.z):(d=0,p=0,f=0);const g=Re.convert(t.format),_=Re.convert(t.type);let v;t.isData3DTexture?(re.setTexture3D(t,0),v=Pe.TEXTURE_3D):t.isDataArrayTexture||t.isCompressedArrayTexture?(re.setTexture2DArray(t,0),v=Pe.TEXTURE_2D_ARRAY):(re.setTexture2D(t,0),v=Pe.TEXTURE_2D),Pe.pixelStorei(Pe.UNPACK_FLIP_Y_WEBGL,t.flipY),Pe.pixelStorei(Pe.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),Pe.pixelStorei(Pe.UNPACK_ALIGNMENT,t.unpackAlignment);const y=Pe.getParameter(Pe.UNPACK_ROW_LENGTH),x=Pe.getParameter(Pe.UNPACK_IMAGE_HEIGHT),b=Pe.getParameter(Pe.UNPACK_SKIP_PIXELS),T=Pe.getParameter(Pe.UNPACK_SKIP_ROWS),S=Pe.getParameter(Pe.UNPACK_SKIP_IMAGES);Pe.pixelStorei(Pe.UNPACK_ROW_LENGTH,m.width),Pe.pixelStorei(Pe.UNPACK_IMAGE_HEIGHT,m.height),Pe.pixelStorei(Pe.UNPACK_SKIP_PIXELS,u),Pe.pixelStorei(Pe.UNPACK_SKIP_ROWS,c),Pe.pixelStorei(Pe.UNPACK_SKIP_IMAGES,h);const M=e.isDataArrayTexture||e.isData3DTexture,w=t.isDataArrayTexture||t.isData3DTexture;if(e.isDepthTexture){const n=ee.get(e),r=ee.get(t),m=ee.get(n.__renderTarget),g=ee.get(r.__renderTarget);Z.bindFramebuffer(Pe.READ_FRAMEBUFFER,m.__webglFramebuffer),Z.bindFramebuffer(Pe.DRAW_FRAMEBUFFER,g.__webglFramebuffer);for(let n=0;n<l;n++)M&&(Pe.framebufferTextureLayer(Pe.READ_FRAMEBUFFER,Pe.COLOR_ATTACHMENT0,ee.get(e).__webglTexture,i,h+n),Pe.framebufferTextureLayer(Pe.DRAW_FRAMEBUFFER,Pe.COLOR_ATTACHMENT0,ee.get(t).__webglTexture,s,f+n)),Pe.blitFramebuffer(u,c,a,o,d,p,a,o,Pe.DEPTH_BUFFER_BIT,Pe.NEAREST);Z.bindFramebuffer(Pe.READ_FRAMEBUFFER,null),Z.bindFramebuffer(Pe.DRAW_FRAMEBUFFER,null)}else if(0!==i||e.isRenderTargetTexture||ee.has(e)){const n=ee.get(e),r=ee.get(t);Z.bindFramebuffer(Pe.READ_FRAMEBUFFER,Je),Z.bindFramebuffer(Pe.DRAW_FRAMEBUFFER,et);for(let e=0;e<l;e++)M?Pe.framebufferTextureLayer(Pe.READ_FRAMEBUFFER,Pe.COLOR_ATTACHMENT0,n.__webglTexture,i,h+e):Pe.framebufferTexture2D(Pe.READ_FRAMEBUFFER,Pe.COLOR_ATTACHMENT0,Pe.TEXTURE_2D,n.__webglTexture,i),w?Pe.framebufferTextureLayer(Pe.DRAW_FRAMEBUFFER,Pe.COLOR_ATTACHMENT0,r.__webglTexture,s,f+e):Pe.framebufferTexture2D(Pe.DRAW_FRAMEBUFFER,Pe.COLOR_ATTACHMENT0,Pe.TEXTURE_2D,r.__webglTexture,s),0!==i?Pe.blitFramebuffer(u,c,a,o,d,p,a,o,Pe.COLOR_BUFFER_BIT,Pe.NEAREST):w?Pe.copyTexSubImage3D(v,s,d,p,f+e,u,c,a,o):Pe.copyTexSubImage2D(v,s,d,p,u,c,a,o);Z.bindFramebuffer(Pe.READ_FRAMEBUFFER,null),Z.bindFramebuffer(Pe.DRAW_FRAMEBUFFER,null)}else w?e.isDataTexture||e.isData3DTexture?Pe.texSubImage3D(v,s,d,p,f,a,o,l,g,_,m.data):t.isCompressedArrayTexture?Pe.compressedTexSubImage3D(v,s,d,p,f,a,o,l,g,m.data):Pe.texSubImage3D(v,s,d,p,f,a,o,l,g,_,m):e.isDataTexture?Pe.texSubImage2D(Pe.TEXTURE_2D,s,d,p,a,o,g,_,m.data):e.isCompressedTexture?Pe.compressedTexSubImage2D(Pe.TEXTURE_2D,s,d,p,m.width,m.height,g,m.data):Pe.texSubImage2D(Pe.TEXTURE_2D,s,d,p,a,o,g,_,m);Pe.pixelStorei(Pe.UNPACK_ROW_LENGTH,y),Pe.pixelStorei(Pe.UNPACK_IMAGE_HEIGHT,x),Pe.pixelStorei(Pe.UNPACK_SKIP_PIXELS,b),Pe.pixelStorei(Pe.UNPACK_SKIP_ROWS,T),Pe.pixelStorei(Pe.UNPACK_SKIP_IMAGES,S),0===s&&t.generateMipmaps&&Pe.generateMipmap(v),Z.unbindTexture()},this.copyTextureToTexture3D=function(e,t,n=null,r=null,i=0){return jt('WebGLRenderer: copyTextureToTexture3D function has been deprecated. Use "copyTextureToTexture" instead.'),this.copyTextureToTexture(e,t,n,r,i)},this.initRenderTarget=function(e){void 0===ee.get(e).__webglFramebuffer&&re.setupRenderTarget(e)},this.initTexture=function(e){e.isCubeTexture?re.setTextureCube(e,0):e.isData3DTexture?re.setTexture3D(e,0):e.isDataArrayTexture||e.isCompressedArrayTexture?re.setTexture2DArray(e,0):re.setTexture2D(e,0),Z.unbindTexture()},this.resetState=function(){T=0,S=0,M=null,Z.reset(),Ce.reset()},"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return yt}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const t=this.getContext();t.drawingBufferColorSpace=$t._getDrawingBufferColorSpace(e),t.unpackColorSpace=$t._getUnpackColorSpace()}},Scene:Li,PerspectiveCamera:Mi,Raycaster:pa,SRGBColorSpace:rt,TextureLoader:class extends zs{constructor(e){super(e)}load(e,t,n,r){const i=new sn,s=new Gs(this.manager);return s.setCrossOrigin(this.crossOrigin),s.setPath(this.path),s.load(e,function(e){i.image=e,i.needsUpdate=!0,void 0!==t&&t(i)},n,r),i}},Vector2:Dt,Vector3:Ut,Box3:hn,Color:Nr,Mesh:di,SphereGeometry:Ms,MeshBasicMaterial:Ir,BackSide:1,Clock:ca},UF=Wh({props:{width:{default:window.innerWidth,onChange:function(e,t,n){isNaN(e)&&(t.width=n)}},height:{default:window.innerHeight,onChange:function(e,t,n){isNaN(e)&&(t.height=n)}},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.clock.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 n=null;if(e.hoverDuringDrag||!e.isPointerDragging){var r=this.intersectingObjects(e.pointerPos.x,e.pointerPos.y);e.hoverOrderComparator&&r.sort(function(t,n){return e.hoverOrderComparator(t.object,n.object)});var i=r.find(function(t){return e.hoverFilter(t.object)})||null;n=i?i.object:null,e.intersection=i||null}n!==e.hoverObj&&(e.onHover(n,e.hoverObj,e.intersection),e.tooltip.content(n&&Xh(e.tooltipContent)(n,e.intersection)||null),e.hoverObj=n)}e.tweenGroup.update()}return this},getPointerPos:function(e){var t=e.pointerPos;return{x:t.x,y:t.y}},cameraPosition:function(e,t,n,r){var i=e.camera;if(t&&e.initialised){var s=t,a=n||{x:0,y:0,z:0};if(r){var o=Object.assign({},i.position),l=h();e.tweenGroup.add(new wU(o).to(s,r).easing(yU.Quadratic.Out).onUpdate(u).start()),e.tweenGroup.add(new wU(l).to(a,r/3).easing(yU.Quadratic.Out).onUpdate(c).start())}else u(s),c(a);return this}return Object.assign({},i.position,{lookAt:h()});function u(e){var t=e.x,n=e.y,r=e.z;void 0!==t&&(i.position.x=t),void 0!==n&&(i.position.y=n),void 0!==r&&(i.position.z=r)}function c(t){var n=new IF.Vector3(t.x,t.y,t.z);e.controls.target?e.controls.target=n:i.lookAt(n)}function h(){return Object.assign(new IF.Vector3(0,0,-1e3).applyQuaternion(i.quaternion).add(i.position))}},zoomToFit:function(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:10,r=arguments.length,i=new Array(r>3?r-3:0),s=3;s<r;s++)i[s-3]=arguments[s];return this.fitToBbox(this.getBbox.apply(this,i),t,n)},fitToBbox:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:10,i=e.camera;if(t){var s=new IF.Vector3(0,0,0),a=2*Math.max.apply(Math,LF(Object.entries(t).map(function(e){var t=PF(e,2),n=t[0],r=t[1];return Math.max.apply(Math,LF(r.map(function(e){return Math.abs(s[n]-e)})))}))),o=(1-2*r/e.height)*i.fov,l=a/Math.atan(o*Math.PI/180),u=l/i.aspect,c=Math.max(l,u);if(c>0){var h=s.clone().sub(i.position).normalize().multiplyScalar(-c);this.cameraPosition(h,s,n)}}return this},getBbox:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(){return!0},n=new IF.Box3(new IF.Vector3(0,0,0),new IF.Vector3(0,0,0)),r=e.objects.filter(t);return r.length?(r.forEach(function(e){return n.expandByObject(e)}),Object.assign.apply(Object,LF(["x","y","z"].map(function(e){return NF({},e,[n.min[e],n.max[e]])})))):null},getScreenCoords:function(e,t,n,r){var i=new IF.Vector3(t,n,r);return i.project(this.camera()),{x:(i.x+1)*e.width/2,y:-(i.y-1)*e.height/2}},getSceneCoords:function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,i=new IF.Vector2(t/e.width*2-1,-n/e.height*2+1),s=new IF.Raycaster;return s.setFromCamera(i,e.camera),Object.assign({},s.ray.at(r,new IF.Vector3))},intersectingObjects:function(e,t,n){var r=new IF.Vector2(t/e.width*2-1,-n/e.height*2+1),i=new IF.Raycaster;return i.params.Line.threshold=e.lineHoverPrecision,i.params.Points.threshold=e.pointsHoverPrecision,i.setFromCamera(r,e.camera),i.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}},stateInit:function(){return{scene:new IF.Scene,camera:new IF.PerspectiveCamera,clock:new IF.Clock,tweenGroup:new bU,lastRaycasterCheck:0}},init:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=n.controlType,i=void 0===r?"trackball":r,s=n.useWebGPU,a=void 0!==s&&s,o=n.rendererConfig,l=void 0===o?{}:o,u=n.extraRenderers,c=void 0===u?[]:u,h=n.waitForLoadComplete,d=void 0===h||h;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"}[i]||"",t.navInfo.style.display=t.showNavInfo?null:"none",t.tooltip=new RF(t.container),t.pointerPos=new IF.Vector2,t.pointerPos.x=-2,t.pointerPos.y=-2,["pointermove","pointerdown"].forEach(function(e){return t.container.addEventListener(e,function(n){if("pointerdown"===e&&(t.isPointerPressed=!0),!t.isPointerDragging&&"pointermove"===n.type&&(n.pressure>0||t.isPointerPressed)&&("touch"!==n.pointerType||void 0===n.movementX||[n.movementX,n.movementY].some(function(e){return Math.abs(e)>1}))&&(t.isPointerDragging=!0),t.enablePointerInteraction){var r=(i=t.container,s=i.getBoundingClientRect(),a=window.pageXOffset||document.documentElement.scrollLeft,o=window.pageYOffset||document.documentElement.scrollTop,{top:s.top+o,left:s.left+a});t.pointerPos.x=n.pageX-r.left,t.pointerPos.y=n.pageY-r.top}var i,s,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(a?rD:IF.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 II(t.renderer),t.postProcessingComposer.addPass(new UI(t.scene,t.camera)),t.controls=new{trackball:MD,orbit:nI,fly:vI}[i](t.camera,t.renderer.domElement),"fly"===i&&(t.controls.movementSpeed=300,t.controls.rollSpeed=Math.PI/6,t.controls.dragToLook=!0),"trackball"!==i&&"orbit"!==i||(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(LF(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 IF.Mesh),t.skysphere.visible=!1,t.loadComplete=t.scene.visible=!d,window.scene=t.scene},update:function(e,t){if(e.width&&e.height&&(t.hasOwnProperty("width")||t.hasOwnProperty("height"))){var n,r=e.width,i=e.height;e.container.style.width="".concat(r,"px"),e.container.style.height="".concat(i,"px"),[e.renderer,e.postProcessingComposer].concat(LF(e.extraRenderers)).forEach(function(e){return e.setSize(r,i)}),e.camera.aspect=r/i;var s=e.viewOffset.slice(0,2);s.some(function(e){return e})&&(n=e.camera).setViewOffset.apply(n,[r,i].concat(LF(s),[r,i])),e.camera.updateProjectionMatrix()}if(t.hasOwnProperty("viewOffset")){var a,o=e.width,l=e.height,u=e.viewOffset.slice(0,2);u.some(function(e){return e})?(a=e.camera).setViewOffset.apply(a,[o,l].concat(LF(u),[o,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 IF.SphereGeometry(e.skyRadius)),t.hasOwnProperty("backgroundColor")){var c=nU(e.backgroundColor).alpha;void 0===c&&(c=1),e.renderer.setClearColor(new IF.Color(vU(1,e.backgroundColor)),c)}function h(){e.loadComplete=e.scene.visible=!0}t.hasOwnProperty("backgroundImageUrl")&&(e.backgroundImageUrl?(new IF.TextureLoader).load(e.backgroundImageUrl,function(t){t.colorSpace=IF.SRGBColorSpace,e.skysphere.material=new IF.MeshBasicMaterial({map:t,side:IF.BackSide}),e.skysphere.visible=!0,e.onBackgroundImageLoaded&&setTimeout(e.onBackgroundImageLoaded),!e.loadComplete&&h()}):(e.skysphere.visible=!1,e.skysphere.material.map=null,!e.loadComplete&&h())),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)}))}});function OF(e,t){var n=new t;return n._destructor&&n._destructor(),{linkProp:function(t){return{default:n[t](),onChange:function(n,r){r[e][t](n)},triggerUpdate:!1}},linkMethod:function(t){return function(n){for(var r=n[e],i=arguments.length,s=new Array(i>1?i-1:0),a=1;a<i;a++)s[a-1]=arguments[a];var o=r[t].apply(r,s);return o===r?this:o}}}}var FF=window.THREE?window.THREE:{AmbientLight:sa,DirectionalLight:ia,REVISION:s},BF=OF("forceGraph",Op),kF=Object.assign.apply(Object,i(["jsonUrl","graphData","numDimensions","dagMode","dagLevelDistance","dagNodeFilter","onDagError","nodeRelSize","nodeId","nodeVal","nodeResolution","nodeColor","nodeAutoColorBy","nodeOpacity","nodeVisibility","nodeThreeObject","nodeThreeObjectExtend","nodePositionUpdate","linkSource","linkTarget","linkVisibility","linkColor","linkAutoColorBy","linkOpacity","linkWidth","linkResolution","linkCurvature","linkCurveRotation","linkMaterial","linkThreeObject","linkThreeObjectExtend","linkPositionUpdate","linkDirectionalArrowLength","linkDirectionalArrowColor","linkDirectionalArrowRelPos","linkDirectionalArrowResolution","linkDirectionalParticles","linkDirectionalParticleSpeed","linkDirectionalParticleOffset","linkDirectionalParticleWidth","linkDirectionalParticleColor","linkDirectionalParticleResolution","linkDirectionalParticleThreeObject","forceEngine","d3AlphaDecay","d3VelocityDecay","d3AlphaMin","ngraphPhysics","warmupTicks","cooldownTicks","cooldownTime","onEngineTick","onEngineStop"].map(function(e){return t({},e,BF.linkProp(e))}))),zF=Object.assign.apply(Object,i(["refresh","getGraphBbox","d3Force","d3ReheatSimulation","emitParticle"].map(function(e){return t({},e,BF.linkMethod(e))}))),VF=OF("renderObjs",UF),GF=Object.assign.apply(Object,i(["width","height","backgroundColor","showNavInfo","enablePointerInteraction"].map(function(e){return t({},e,VF.linkProp(e))}))),HF=Object.assign.apply(Object,i(["lights","cameraPosition","postProcessingComposer"].map(function(e){return t({},e,VF.linkMethod(e))})).concat([{graph2ScreenCoords:VF.linkMethod("getScreenCoords"),screen2GraphCoords:VF.linkMethod("getSceneCoords")}])),jF=Wh({props:r(r({nodeLabel:{default:"name",triggerUpdate:!1},linkLabel:{default:"name",triggerUpdate:!1},linkHoverPrecision:{default:1,onChange:function(e,t){return t.renderObjs.lineHoverPrecision(e)},triggerUpdate:!1},enableNavigationControls:{default:!0,onChange:function(e,t){var n=t.renderObjs.controls();n&&(n.enabled=e,e&&n.domElement&&n.domElement.dispatchEvent(new PointerEvent("pointerup")))},triggerUpdate:!1},enableNodeDrag:{default:!0,triggerUpdate:!1},onNodeDrag:{default:function(){},triggerUpdate:!1},onNodeDragEnd:{default:function(){},triggerUpdate:!1},onNodeClick:{triggerUpdate:!1},onNodeRightClick:{triggerUpdate:!1},onNodeHover:{triggerUpdate:!1},onLinkClick:{triggerUpdate:!1},onLinkRightClick:{triggerUpdate:!1},onLinkHover:{triggerUpdate:!1},onBackgroundClick:{triggerUpdate:!1},onBackgroundRightClick:{triggerUpdate:!1}},kF),GF),methods:r(r({zoomToFit:function(e,t,n){for(var r,i=arguments.length,s=new Array(i>3?i-3:0),a=3;a<i;a++)s[a-3]=arguments[a];return e.renderObjs.fitToBbox((r=e.forceGraph).getGraphBbox.apply(r,s),t,n),this},pauseAnimation:function(e){return null!==e.animationFrameRequestId&&(cancelAnimationFrame(e.animationFrameRequestId),e.animationFrameRequestId=null),this},resumeAnimation:function(e){return null===e.animationFrameRequestId&&this._animationCycle(),this},_animationCycle:function(e){e.enablePointerInteraction&&(this.renderer().domElement.style.cursor=null),e.forceGraph.tickFrame(),e.renderObjs.tick(),e.animationFrameRequestId=requestAnimationFrame(this._animationCycle)},scene:function(e){return e.renderObjs.scene()},camera:function(e){return e.renderObjs.camera()},renderer:function(e){return e.renderObjs.renderer()},controls:function(e){return e.renderObjs.controls()},tbControls:function(e){return e.renderObjs.tbControls()},_destructor:function(){this.pauseAnimation(),this.graphData({nodes:[],links:[]})}},zF),HF),stateInit:function(e){var t=e.controlType,n=e.rendererConfig,r=e.extraRenderers,i=new Op;return{forceGraph:i,renderObjs:UF({controlType:t,rendererConfig:n,extraRenderers:r}).objects([i]).lights([new FF.AmbientLight(13421772,Math.PI),new FF.DirectionalLight(16777215,.6*Math.PI)])}},init:function(e,t){e.innerHTML="",e.appendChild(t.container=document.createElement("div")),t.container.style.position="relative";var n=document.createElement("div");t.container.appendChild(n),t.renderObjs(n);var r,i=t.renderObjs.camera(),s=t.renderObjs.renderer(),a=t.renderObjs.controls();a.enabled=!!t.enableNavigationControls,t.lastSetCameraZ=i.position.z,t.container.appendChild(r=document.createElement("div")),r.className="graph-info-msg",r.textContent="",t.forceGraph.onLoading(function(){r.textContent="Loading..."}).onFinishLoading(function(){r.textContent=""}).onUpdate(function(){t.graphData=t.forceGraph.graphData(),0===i.position.x&&0===i.position.y&&i.position.z===t.lastSetCameraZ&&t.graphData.nodes.length&&(i.lookAt(t.forceGraph.position),t.lastSetCameraZ=i.position.z=170*Math.cbrt(t.graphData.nodes.length))}).onFinishUpdate(function(){if(t._dragControls){var e=t.graphData.nodes.find(function(e){return e.__initialFixedPos&&!e.__disposeControlsAfterDrag});e?e.__disposeControlsAfterDrag=!0:t._dragControls.dispose(),t._dragControls=void 0}if(t.enableNodeDrag&&t.enablePointerInteraction&&"d3"===t.forceEngine){var n=t._dragControls=new yu(t.graphData.nodes.map(function(e){return e.__threeObj}).filter(function(e){return e}),i,s.domElement);n.addEventListener("dragstart",function(e){var t=WF(e.object);if(t){a.enabled=!1,e.object.__initialPos=e.object.position.clone(),e.object.__prevPos=e.object.position.clone();var n=t.__data;!n.__initialFixedPos&&(n.__initialFixedPos={fx:n.fx,fy:n.fy,fz:n.fz}),!n.__initialPos&&(n.__initialPos={x:n.x,y:n.y,z:n.z}),["x","y","z"].forEach(function(e){return n["f".concat(e)]=n[e]}),s.domElement.classList.add("grabbable")}}),n.addEventListener("drag",function(e){var n=WF(e.object);if(n){if(!e.object.hasOwnProperty("__graphObjType")){var r=e.object.__initialPos,i=e.object.__prevPos,s=e.object.position;n.position.add(s.clone().sub(i)),i.copy(s),s.copy(r)}var a=n.__data,o=n.position,l={x:o.x-a.x,y:o.y-a.y,z:o.z-a.z};["x","y","z"].forEach(function(e){return a["f".concat(e)]=a[e]=o[e]}),t.forceGraph.d3AlphaTarget(.3).resetCountdown(),a.__dragged=!0,t.onNodeDrag(a,l)}}),n.addEventListener("dragend",function(e){var r=WF(e.object);if(r){delete e.object.__initialPos,delete e.object.__prevPos;var i=r.__data;i.__disposeControlsAfterDrag&&(n.dispose(),delete i.__disposeControlsAfterDrag);var o=i.__initialFixedPos,l=i.__initialPos,u={x:l.x-i.x,y:l.y-i.y,z:l.z-i.z};o&&(["x","y","z"].forEach(function(e){var t="f".concat(e);void 0===o[t]&&delete i[t]}),delete i.__initialFixedPos,delete i.__initialPos,i.__dragged&&(delete i.__dragged,t.onNodeDragEnd(i,u))),t.forceGraph.d3AlphaTarget(0).resetCountdown(),t.enableNavigationControls&&(a.enabled=!0,a.domElement&&a.domElement.ownerDocument&&a.domElement.ownerDocument.dispatchEvent(new PointerEvent("pointerup",{pointerType:"touch"}))),s.domElement.classList.remove("grabbable")}})}}),FF.REVISION<155&&(t.renderObjs.renderer().useLegacyLights=!1),t.renderObjs.hoverOrderComparator(function(e,t){var n=WF(e);if(!n)return 1;var r=WF(t);if(!r)return-1;var i=function(e){return"node"===e.__graphObjType};return i(r)-i(n)}).tooltipContent(function(e){var n=WF(e);return n&&Xh(t["".concat(n.__graphObjType,"Label")])(n.__data)||""}).hoverDuringDrag(!1).onHover(function(e){var n=WF(e);if(n!==t.hoverObj){var r=t.hoverObj?t.hoverObj.__graphObjType:null,i=t.hoverObj?t.hoverObj.__data:null,a=n?n.__graphObjType:null,o=n?n.__data:null;if(r&&r!==a){var l=t["on".concat("node"===r?"Node":"Link","Hover")];l&&l(null,i)}if(a){var u=t["on".concat("node"===a?"Node":"Link","Hover")];u&&u(o,r===a?i:null)}s.domElement.classList[n&&t["on".concat("node"===a?"Node":"Link","Click")]||!n&&t.onBackgroundClick?"add":"remove"]("clickable"),t.hoverObj=n}}).clickAfterDrag(!1).onClick(function(e,n){var r=WF(e);if(r){var i=t["on".concat("node"===r.__graphObjType?"Node":"Link","Click")];i&&i(r.__data,n)}else t.onBackgroundClick&&t.onBackgroundClick(n)}).onRightClick(function(e,n){var r=WF(e);if(r){var i=t["on".concat("node"===r.__graphObjType?"Node":"Link","RightClick")];i&&i(r.__data,n)}else t.onBackgroundRightClick&&t.onBackgroundRightClick(n)}),this._animationCycle()}});function WF(e){for(var t=e;t&&!t.hasOwnProperty("__graphObjType");)t=t.parent;return t}return jF});
|
|
5
|
+
bd.readability=function(e,t){var n=bd(e),r=bd(t);return(Math.max(n.getLuminance(),r.getLuminance())+.05)/(Math.min(n.getLuminance(),r.getLuminance())+.05)},bd.isReadable=function(e,t,n){var r,i,s=bd.readability(e,t);switch(i=!1,(r=function(e){var t,n;t=((e=e||{level:"AA",size:"small"}).level||"AA").toUpperCase(),n=(e.size||"small").toLowerCase(),"AA"!==t&&"AAA"!==t&&(t="AA");"small"!==n&&"large"!==n&&(n="small");return{level:t,size:n}}(n)).level+r.size){case"AAsmall":case"AAAlarge":i=s>=4.5;break;case"AAlarge":i=s>=3;break;case"AAAsmall":i=s>=7}return i},bd.mostReadable=function(e,t,n){var r,i,s,a,o=null,l=0;i=(n=n||{}).includeFallbackColors,s=n.level,a=n.size;for(var u=0;u<t.length;u++)(r=bd.readability(e,t[u]))>l&&(l=r,o=bd(t[u]));return bd.isReadable(e,o,{level:s,size:a})||!i?o:(n.includeFallbackColors=!1,bd.mostReadable(e,["#fff","#000"],n))};var Bd=bd.names={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"0ff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"00f",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",burntsienna:"ea7e5d",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"0ff",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:"f0f",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:"663399",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"},kd=bd.hexNames=function(e){var t={};for(var n in e)e.hasOwnProperty(n)&&(t[e[n]]=n);return t}(Bd);function zd(e){return e=parseFloat(e),(isNaN(e)||e<0||e>1)&&(e=1),e}function Vd(e,t){(function(e){return"string"==typeof e&&-1!=e.indexOf(".")&&1===parseFloat(e)})(e)&&(e="100%");var n=function(e){return"string"==typeof e&&-1!=e.indexOf("%")}(e);return e=Math.min(t,Math.max(0,parseFloat(e))),n&&(e=parseInt(e*t,10)/100),Math.abs(e-t)<1e-6?1:e%t/parseFloat(t)}function Gd(e){return Math.min(1,Math.max(0,e))}function Hd(e){return parseInt(e,16)}function jd(e){return 1==e.length?"0"+e:""+e}function Wd(e){return e<=1&&(e=100*e+"%"),e}function Xd(e){return Math.round(255*parseFloat(e)).toString(16)}function qd(e){return Hd(e)/255}var $d,Yd,Kd,Qd=(Yd="[\\s|\\(]+("+($d="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)")+")[,|\\s]+("+$d+")[,|\\s]+("+$d+")\\s*\\)?",Kd="[\\s|\\(]+("+$d+")[,|\\s]+("+$d+")[,|\\s]+("+$d+")[,|\\s]+("+$d+")\\s*\\)?",{CSS_UNIT:new RegExp($d),rgb:new RegExp("rgb"+Yd),rgba:new RegExp("rgba"+Kd),hsl:new RegExp("hsl"+Yd),hsla:new RegExp("hsla"+Kd),hsv:new RegExp("hsv"+Yd),hsva:new RegExp("hsva"+Kd),hex3:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex6:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,hex4:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex8:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/});function Zd(e){return!!Qd.CSS_UNIT.exec(e)}function Jd(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function ep(e,t,n){if("function"==typeof e?e===t:e.has(t))return arguments.length<3?t:n;throw new TypeError("Private element is not present on this object")}function tp(e,t,n){return t=cp(t),function(e,t){if(t&&("object"==typeof t||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(e,dp()?Reflect.construct(t,n||[],cp(e).constructor):t.apply(e,n))}function np(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function rp(e,t){return e.get(ep(e,t))}function ip(e,t,n){(function(e,t){if(t.has(e))throw new TypeError("Cannot initialize the same private elements twice on an object")})(e,t),t.set(e,n)}function sp(e,t,n){return e.set(ep(e,t),n),n}function ap(e,t,n){if(dp())return Reflect.construct.apply(null,arguments);var r=[null];return r.push.apply(r,t),new(e.bind.apply(e,r))}function op(e,t,n){return t&&function(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,vp(r.key),r)}}(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function lp(e,t,n){return(t=vp(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function up(){return up="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(e,t,n){var r=function(e,t){for(;!{}.hasOwnProperty.call(e,t)&&null!==(e=cp(e)););return e}(e,t);if(r){var i=Object.getOwnPropertyDescriptor(r,t);return i.get?i.get.call(arguments.length<3?e:n):i.value}},up.apply(null,arguments)}function cp(e){return cp=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},cp(e)}function hp(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&fp(e,t)}function dp(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(dp=function(){return!!e})()}function pp(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function fp(e,t){return fp=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},fp(e,t)}function mp(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,s,a,o=[],l=!0,u=!1;try{if(s=(n=n.call(e)).next,0===t);else for(;!(l=(r=s.call(n)).done)&&(o.push(r.value),o.length!==t);l=!0);}catch(e){u=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(u)throw i}}return o}}(e,t)||xp(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 gp(e,t,n,r){var i=up(cp(e.prototype),t,n);return"function"==typeof i?function(e){return i.apply(n,e)}:i}function _p(e){return function(e){if(Array.isArray(e))return Jd(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||xp(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 vp(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t);if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}function yp(e){return yp="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},yp(e)}function xp(e,t){if(e){if("string"==typeof e)return Jd(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Jd(e,t):void 0}}var bp=function(e){e instanceof Array?e.forEach(bp):(e.map&&e.map.dispose(),e.dispose())},Tp=function(e){e.geometry&&e.geometry.dispose(),e.material&&bp(e.material),e.texture&&e.texture.dispose(),e.children&&e.children.forEach(Tp)},Sp=function(e){for(;e.children.length;){var t=e.children[0];e.remove(t),Tp(t)}},Mp=new WeakMap,wp=new WeakMap,Ep=function(e){function t(e){var n,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=r.dataBindAttr,s=void 0===i?"__data":i,a=r.objBindAttr,o=void 0===a?"__threeObj":a;return np(this,t),lp(n=tp(this,t),"scene",void 0),ip(n,Mp,void 0),ip(n,wp,void 0),n.scene=e,sp(Mp,n,s),sp(wp,n,o),n.onRemoveObj(function(){}),n}return hp(t,e),op(t,[{key:"onCreateObj",value:function(e){var n=this;return gp(t,"onCreateObj",this)([function(t){var r=e(t);return t[rp(wp,n)]=r,r[rp(Mp,n)]=t,n.scene.add(r),r}]),this}},{key:"onRemoveObj",value:function(e){var n=this;return gp(t,"onRemoveObj",this)([function(r,i){var s=gp(t,"getData",n)([r]);e(r,i),n.scene.remove(r),Sp(r),delete s[rp(wp,n)]}]),this}}])}(fd),Ap=function(e){return isNaN(e)?parseInt(bd(e).toHex(),16):e},Rp=function(e){return isNaN(e)?bd(e).getAlpha():1},Cp=function e(){var t=new qh,n=[],r=[],i=gd;function s(e){let s=t.get(e);if(void 0===s){if(i!==gd)return i;t.set(e,s=n.push(e)-1)}return r[s%r.length]}return s.domain=function(e){if(!arguments.length)return n.slice();n=[],t=new qh;for(const r of e)t.has(r)||t.set(r,n.push(r)-1);return s},s.range=function(e){return arguments.length?(r=Array.from(e),s):r.slice()},s.unknown=function(e){return arguments.length?(i=e,s):i},s.copy=function(){return e(n,r).unknown(i)},md.apply(s,arguments),s}(_d);function Np(e,t,n){t&&"string"==typeof n&&e.filter(function(e){return!e[n]}).forEach(function(e){e[n]=Cp(t(e))})}var Pp=window.THREE?window.THREE:{Group:Ci,Mesh:di,MeshLambertMaterial:Ls,Color:Nr,BufferGeometry:ei,BufferAttribute:Gr,Matrix4:Bn,Vector3:Ut,SphereGeometry:Ms,CylinderGeometry:ls,TubeGeometry:ws,ConeGeometry:us,Line:class extends hr{constructor(e=new ei,t=new Ki){super(),this.isLine=!0,this.type="Line",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}computeLineDistances(){const e=this.geometry;if(null===e.index){const t=e.attributes.position,n=[0];for(let e=1,r=t.count;e<r;e++)Qi.fromBufferAttribute(t,e-1),Zi.fromBufferAttribute(t,e),n[e]=n[e-1],n[e]+=Qi.distanceTo(Zi);e.setAttribute("lineDistance",new Xr(n,1))}else console.warn("THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast(e,t){const n=this.geometry,r=this.matrixWorld,i=e.params.Line.threshold,s=n.drawRange;if(null===n.boundingSphere&&n.computeBoundingSphere(),ts.copy(n.boundingSphere),ts.applyMatrix4(r),ts.radius+=i,!1===e.ray.intersectsSphere(ts))return;Ji.copy(r).invert(),es.copy(e.ray).applyMatrix4(Ji);const a=i/((this.scale.x+this.scale.y+this.scale.z)/3),o=a*a,l=this.isLineSegments?2:1,u=n.index,c=n.attributes.position;if(null!==u){const n=Math.max(0,s.start),r=Math.min(u.count,s.start+s.count);for(let i=n,s=r-1;i<s;i+=l){const n=u.getX(i),r=u.getX(i+1),s=is(this,e,es,o,n,r,i);s&&t.push(s)}if(this.isLineLoop){const i=u.getX(r-1),s=u.getX(n),a=is(this,e,es,o,i,s,r-1);a&&t.push(a)}}else{const n=Math.max(0,s.start),r=Math.min(c.count,s.start+s.count);for(let i=n,s=r-1;i<s;i+=l){const n=is(this,e,es,o,i,i+1,i);n&&t.push(n)}if(this.isLineLoop){const i=is(this,e,es,o,r-1,n,r-1);i&&t.push(i)}}}updateMorphTargets(){const e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){const n=e[t[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e<t;e++){const t=n[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}},LineBasicMaterial:Ki,QuadraticBezierCurve3:bs,CubicBezierCurve3:xs,Box3:hn},Lp={graph:jc,forcelayout:gh},Dp=(new Pp.BufferGeometry).setAttribute?"setAttribute":"addAttribute",Ip=(new Pp.BufferGeometry).applyMatrix4?"applyMatrix4":"applyMatrix",Up=Wh({props:{jsonUrl:{onChange:function(e,t){var n=this;e&&!t.fetchingJson&&(t.fetchingJson=!0,t.onLoading(),fetch(e).then(function(e){return e.json()}).then(function(e){t.fetchingJson=!1,t.onFinishLoading(e),n.graphData(e)}))},triggerUpdate:!1},graphData:{default:{nodes:[],links:[]},onChange:function(e,t){t.engineRunning=!1}},numDimensions:{default:3,onChange:function(e,t){var n=t.d3ForceLayout.force("charge");function r(e,t){e.forEach(function(e){delete e[t],delete e["v".concat(t)]})}n&&n.strength(e>2?-60:-30),e<3&&r(t.graphData.nodes,"z"),e<2&&r(t.graphData.nodes,"y")}},dagMode:{onChange:function(e,t){!e&&"d3"===t.forceEngine&&(t.graphData.nodes||[]).forEach(function(e){return e.fx=e.fy=e.fz=void 0})}},dagLevelDistance:{},dagNodeFilter:{default:function(e){return!0}},onDagError:{triggerUpdate:!1},nodeRelSize:{default:4},nodeId:{default:"id"},nodeVal:{default:"val"},nodeResolution:{default:8},nodeColor:{default:"color"},nodeAutoColorBy:{},nodeOpacity:{default:.75},nodeVisibility:{default:!0},nodeThreeObject:{},nodeThreeObjectExtend:{default:!1},nodePositionUpdate:{triggerUpdate:!1},linkSource:{default:"source"},linkTarget:{default:"target"},linkVisibility:{default:!0},linkColor:{default:"color"},linkAutoColorBy:{},linkOpacity:{default:.2},linkWidth:{},linkResolution:{default:6},linkCurvature:{default:0,triggerUpdate:!1},linkCurveRotation:{default:0,triggerUpdate:!1},linkMaterial:{},linkThreeObject:{},linkThreeObjectExtend:{default:!1},linkPositionUpdate:{triggerUpdate:!1},linkDirectionalArrowLength:{default:0},linkDirectionalArrowColor:{},linkDirectionalArrowRelPos:{default:.5,triggerUpdate:!1},linkDirectionalArrowResolution:{default:8},linkDirectionalParticles:{default:0},linkDirectionalParticleSpeed:{default:.01,triggerUpdate:!1},linkDirectionalParticleOffset:{default:0,triggerUpdate:!1},linkDirectionalParticleWidth:{default:.5},linkDirectionalParticleColor:{},linkDirectionalParticleResolution:{default:4},linkDirectionalParticleThreeObject:{},forceEngine:{default:"d3"},d3AlphaMin:{default:0},d3AlphaDecay:{default:.0228,triggerUpdate:!1,onChange:function(e,t){t.d3ForceLayout.alphaDecay(e)}},d3AlphaTarget:{default:0,triggerUpdate:!1,onChange:function(e,t){t.d3ForceLayout.alphaTarget(e)}},d3VelocityDecay:{default:.4,triggerUpdate:!1,onChange:function(e,t){t.d3ForceLayout.velocityDecay(e)}},ngraphPhysics:{default:{timeStep:20,gravity:-1.2,theta:.8,springLength:30,springCoefficient:8e-4,dragCoefficient:.02}},warmupTicks:{default:0,triggerUpdate:!1},cooldownTicks:{default:1/0,triggerUpdate:!1},cooldownTime:{default:15e3,triggerUpdate:!1},onLoading:{default:function(){},triggerUpdate:!1},onFinishLoading:{default:function(){},triggerUpdate:!1},onUpdate:{default:function(){},triggerUpdate:!1},onFinishUpdate:{default:function(){},triggerUpdate:!1},onEngineTick:{default:function(){},triggerUpdate:!1},onEngineStop:{default:function(){},triggerUpdate:!1}},methods:{refresh:function(e){return e._flushObjects=!0,e._rerender(),this},d3Force:function(e,t,n){return void 0===n?e.d3ForceLayout.force(t):(e.d3ForceLayout.force(t,n),this)},d3ReheatSimulation:function(e){return e.d3ForceLayout.alpha(1),this.resetCountdown(),this},resetCountdown:function(e){return e.cntTicks=0,e.startTickTime=new Date,e.engineRunning=!0,this},tickFrame:function(e){var t,n,r,i,s,a="ngraph"!==e.forceEngine;return e.engineRunning&&function(){++e.cntTicks>e.cooldownTicks||new Date-e.startTickTime>e.cooldownTime||a&&e.d3AlphaMin>0&&e.d3ForceLayout.alpha()<e.d3AlphaMin?(e.engineRunning=!1,e.onEngineStop()):(e.layout[a?"tick":"step"](),e.onEngineTick());var t=Xh(e.nodeThreeObjectExtend);e.nodeDataMapper.entries().forEach(function(n){var r=mp(n,2),i=r[0],s=r[1];if(s){var o=a?i:e.layout.getNodePosition(i[e.nodeId]),l=t(i);e.nodePositionUpdate&&e.nodePositionUpdate(l?s.children[0]:s,{x:o.x,y:o.y,z:o.z},i)&&!l||(s.position.x=o.x,s.position.y=o.y||0,s.position.z=o.z||0)}});var n=Xh(e.linkWidth),r=Xh(e.linkCurvature),i=Xh(e.linkCurveRotation),s=Xh(e.linkThreeObjectExtend);function o(t){var n=a?t:e.layout.getLinkPosition(e.layout.graph.getLink(t.source,t.target).id),s=n[a?"source":"from"],o=n[a?"target":"to"];if(s&&o&&s.hasOwnProperty("x")&&o.hasOwnProperty("x")){var l=r(t);if(l){var u,c=new Pp.Vector3(s.x,s.y||0,s.z||0),h=new Pp.Vector3(o.x,o.y||0,o.z||0),d=c.distanceTo(h),p=i(t);if(d>0){var f=o.x-s.x,m=o.y-s.y||0,g=(new Pp.Vector3).subVectors(h,c),_=g.clone().multiplyScalar(l).cross(0!==f||0!==m?new Pp.Vector3(0,0,1):new Pp.Vector3(0,1,0)).applyAxisAngle(g.normalize(),p).add((new Pp.Vector3).addVectors(c,h).divideScalar(2));u=new Pp.QuadraticBezierCurve3(c,_,h)}else{var v=70*l,y=-p,x=y+Math.PI/2;u=new Pp.CubicBezierCurve3(c,new Pp.Vector3(v*Math.cos(x),v*Math.sin(x),0).add(c),new Pp.Vector3(v*Math.cos(y),v*Math.sin(y),0).add(c),h)}t.__curve=u}else t.__curve=null}}e.linkDataMapper.entries().forEach(function(t){var r=mp(t,2),i=r[0],l=r[1];if(l){var u=a?i:e.layout.getLinkPosition(e.layout.graph.getLink(i.source,i.target).id),c=u[a?"source":"from"],h=u[a?"target":"to"];if(c&&h&&c.hasOwnProperty("x")&&h.hasOwnProperty("x")){o(i);var d=s(i);if(!e.linkPositionUpdate||!e.linkPositionUpdate(d?l.children[1]:l,{start:{x:c.x,y:c.y,z:c.z},end:{x:h.x,y:h.y,z:h.z}},i)||d){var p=30,f=i.__curve,m=l.children.length?l.children[0]:l;if("Line"===m.type){if(f){var g=f.getPoints(p);m.geometry.getAttribute("position").array.length!==3*g.length&&m.geometry[Dp]("position",new Pp.BufferAttribute(new Float32Array(3*g.length),3)),m.geometry.setFromPoints(g)}else{var _=m.geometry.getAttribute("position");_&&_.array&&6===_.array.length||m.geometry[Dp]("position",_=new Pp.BufferAttribute(new Float32Array(6),3)),_.array[0]=c.x,_.array[1]=c.y||0,_.array[2]=c.z||0,_.array[3]=h.x,_.array[4]=h.y||0,_.array[5]=h.z||0,_.needsUpdate=!0}m.geometry.computeBoundingSphere()}else if("Mesh"===m.type)if(f){m.geometry.type.match(/^Tube(Buffer)?Geometry$/)||(m.position.set(0,0,0),m.rotation.set(0,0,0),m.scale.set(1,1,1));var v=Math.ceil(10*n(i))/10/2,y=new Pp.TubeGeometry(f,p,v,e.linkResolution,!1);m.geometry.dispose(),m.geometry=y}else{if(!m.geometry.type.match(/^Cylinder(Buffer)?Geometry$/)){var x=Math.ceil(10*n(i))/10/2,b=new Pp.CylinderGeometry(x,x,1,e.linkResolution,1,!1);b[Ip]((new Pp.Matrix4).makeTranslation(0,.5,0)),b[Ip]((new Pp.Matrix4).makeRotationX(Math.PI/2)),m.geometry.dispose(),m.geometry=b}var T=new Pp.Vector3(c.x,c.y||0,c.z||0),S=new Pp.Vector3(h.x,h.y||0,h.z||0),M=T.distanceTo(S);m.position.x=T.x,m.position.y=T.y,m.position.z=T.z,m.scale.z=M,m.parent.localToWorld(S),m.lookAt(S)}}}}})}(),t=Xh(e.linkDirectionalArrowRelPos),n=Xh(e.linkDirectionalArrowLength),r=Xh(e.nodeVal),e.arrowDataMapper.entries().forEach(function(i){var s=mp(i,2),o=s[0],l=s[1];if(l){var u=a?o:e.layout.getLinkPosition(e.layout.graph.getLink(o.source,o.target).id),c=u[a?"source":"from"],h=u[a?"target":"to"];if(c&&h&&c.hasOwnProperty("x")&&h.hasOwnProperty("x")){var d=Math.cbrt(Math.max(0,r(c)||1))*e.nodeRelSize,p=Math.cbrt(Math.max(0,r(h)||1))*e.nodeRelSize,f=n(o),m=t(o),g=o.__curve?function(e){return o.__curve.getPoint(e)}:function(e){var t=function(e,t,n,r){return t[e]+(n[e]-t[e])*r||0};return{x:t("x",c,h,e),y:t("y",c,h,e),z:t("z",c,h,e)}},_=o.__curve?o.__curve.getLength():Math.sqrt(["x","y","z"].map(function(e){return Math.pow((h[e]||0)-(c[e]||0),2)}).reduce(function(e,t){return e+t},0)),v=d+f+(_-d-p-f)*m,y=g(v/_),x=g((v-f)/_);["x","y","z"].forEach(function(e){return l.position[e]=x[e]});var b=ap(Pp.Vector3,_p(["x","y","z"].map(function(e){return y[e]})));l.parent.localToWorld(b),l.lookAt(b)}}}),i=Xh(e.linkDirectionalParticleSpeed),s=Xh(e.linkDirectionalParticleOffset),e.graphData.links.forEach(function(t){var n=e.particlesDataMapper.getObj(t),r=n&&n.children,o=t.__singleHopPhotonsObj&&t.__singleHopPhotonsObj.children;if(o&&o.length||r&&r.length){var l=a?t:e.layout.getLinkPosition(e.layout.graph.getLink(t.source,t.target).id),u=l[a?"source":"from"],c=l[a?"target":"to"];if(u&&c&&u.hasOwnProperty("x")&&c.hasOwnProperty("x")){var h=i(t),d=Math.abs(s(t)),p=t.__curve?function(e){return t.__curve.getPoint(e)}:function(e){var t=function(e,t,n,r){return t[e]+(n[e]-t[e])*r||0};return{x:t("x",u,c,e),y:t("y",u,c,e),z:t("z",u,c,e)}};[].concat(_p(r||[]),_p(o||[])).forEach(function(e,t){var n="singleHopPhotons"===e.parent.__linkThreeObjType;if(e.hasOwnProperty("__progressRatio")||(e.__progressRatio=n?0:(t+d)/r.length),e.__progressRatio+=h,e.__progressRatio>=1){if(n)return e.parent.remove(e),void Sp(e);e.__progressRatio=e.__progressRatio%1}var i=e.__progressRatio,s=p(i);"SphereGeometry"!==e.geometry.type&&e.lookAt(s.x,s.y,s.z),["x","y","z"].forEach(function(t){return e.position[t]=s[t]})})}}}),this},emitParticle:function(e,t){if(t&&e.graphData.links.includes(t)){if(!t.__singleHopPhotonsObj){var n=new Pp.Group;n.__linkThreeObjType="singleHopPhotons",t.__singleHopPhotonsObj=n,e.graphScene.add(n)}var r=Xh(e.linkDirectionalParticleThreeObject)(t);if(r&&e.linkDirectionalParticleThreeObject===r&&(r=r.clone()),!r){var i=Xh(e.linkDirectionalParticleWidth),s=Math.ceil(10*i(t))/10/2,a=e.linkDirectionalParticleResolution,o=new Pp.SphereGeometry(s,a,a),l=Xh(e.linkColor),u=Xh(e.linkDirectionalParticleColor)(t)||l(t)||"#f0f0f0",c=new Pp.Color(Ap(u)),h=3*e.linkOpacity,d=new Pp.MeshLambertMaterial({color:c,transparent:!0,opacity:h});r=new Pp.Mesh(o,d)}t.__singleHopPhotonsObj.add(r)}return this},getGraphBbox:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(){return!0};if(!e.initialised)return null;var n=function e(n){var r=[];if(n.geometry){n.geometry.computeBoundingBox();var i=new Pp.Box3;i.copy(n.geometry.boundingBox).applyMatrix4(n.matrixWorld),r.push(i)}return r.concat.apply(r,_p((n.children||[]).filter(function(e){return!e.hasOwnProperty("__graphObjType")||"node"===e.__graphObjType&&t(e.__data)}).map(e)))}(e.graphScene);return n.length?Object.assign.apply(Object,_p(["x","y","z"].map(function(e){return lp({},e,[Qh(n,function(t){return t.min[e]}),Kh(n,function(t){return t.max[e]})])}))):null}},stateInit:function(){return{d3ForceLayout:Ic().force("link",tc()).force("charge",Uc()).force("center",wu()).force("dagRadial",null).stop(),engineRunning:!1}},init:function(e,t){t.graphScene=e,t.nodeDataMapper=new Ep(e,{objBindAttr:"__threeObj"}),t.linkDataMapper=new Ep(e,{objBindAttr:"__lineObj"}),t.arrowDataMapper=new Ep(e,{objBindAttr:"__arrowObj"}),t.particlesDataMapper=new Ep(e,{objBindAttr:"__photonsObj"})},update:function(e,t){var n=function(e){return e.some(function(e){return t.hasOwnProperty(e)})};if(e.engineRunning=!1,"function"==typeof e.onUpdate&&e.onUpdate(),null!==e.nodeAutoColorBy&&n(["nodeAutoColorBy","graphData","nodeColor"])&&Np(e.graphData.nodes,Xh(e.nodeAutoColorBy),e.nodeColor),null!==e.linkAutoColorBy&&n(["linkAutoColorBy","graphData","linkColor"])&&Np(e.graphData.links,Xh(e.linkAutoColorBy),e.linkColor),e._flushObjects||n(["graphData","nodeThreeObject","nodeThreeObjectExtend","nodeVal","nodeColor","nodeVisibility","nodeRelSize","nodeResolution","nodeOpacity"])){var r=Xh(e.nodeThreeObject),i=Xh(e.nodeThreeObjectExtend),s=Xh(e.nodeVal),a=Xh(e.nodeColor),o=Xh(e.nodeVisibility),l={},u={};(e._flushObjects||n(["nodeThreeObject","nodeThreeObjectExtend"]))&&e.nodeDataMapper.clear(),e.nodeDataMapper.onCreateObj(function(t){var n,s=r(t),a=i(t);return s&&e.nodeThreeObject===s&&(s=s.clone()),s&&!a?n=s:((n=new Pp.Mesh).__graphDefaultObj=!0,s&&a&&n.add(s)),n.__graphObjType="node",n}).onUpdateObj(function(t,n){if(t.__graphDefaultObj){var r=s(n)||1,i=Math.cbrt(r)*e.nodeRelSize,o=e.nodeResolution;t.geometry.type.match(/^Sphere(Buffer)?Geometry$/)&&t.geometry.parameters.radius===i&&t.geometry.parameters.widthSegments===o||(l.hasOwnProperty(r)||(l[r]=new Pp.SphereGeometry(i,o,o)),t.geometry.dispose(),t.geometry=l[r]);var c=a(n),h=new Pp.Color(Ap(c||"#ffffaa")),d=e.nodeOpacity*Rp(c);"MeshLambertMaterial"===t.material.type&&t.material.color.equals(h)&&t.material.opacity===d||(u.hasOwnProperty(c)||(u[c]=new Pp.MeshLambertMaterial({color:h,transparent:!0,opacity:d})),t.material.dispose(),t.material=u[c])}}).digest(e.graphData.nodes.filter(o))}if(e._flushObjects||n(["graphData","linkThreeObject","linkThreeObjectExtend","linkMaterial","linkColor","linkWidth","linkVisibility","linkResolution","linkOpacity","linkDirectionalArrowLength","linkDirectionalArrowColor","linkDirectionalArrowResolution","linkDirectionalParticles","linkDirectionalParticleWidth","linkDirectionalParticleColor","linkDirectionalParticleResolution","linkDirectionalParticleThreeObject"])){var c=Xh(e.linkThreeObject),h=Xh(e.linkThreeObjectExtend),d=Xh(e.linkMaterial),p=Xh(e.linkVisibility),f=Xh(e.linkColor),m=Xh(e.linkWidth),g={},_={},v={},y=e.graphData.links.filter(p);if((e._flushObjects||n(["linkThreeObject","linkThreeObjectExtend","linkWidth"]))&&e.linkDataMapper.clear(),e.linkDataMapper.onRemoveObj(function(e){var t=e.__data&&e.__data.__singleHopPhotonsObj;t&&(t.parent.remove(t),Sp(t),delete e.__data.__singleHopPhotonsObj)}).onCreateObj(function(t){var n,r,i=c(t),s=h(t);if(i&&e.linkThreeObject===i&&(i=i.clone()),!i||s)if(!!m(t))n=new Pp.Mesh;else{var a=new Pp.BufferGeometry;a[Dp]("position",new Pp.BufferAttribute(new Float32Array(6),3)),n=new Pp.Line(a)}return i?s?((r=new Pp.Group).__graphDefaultObj=!0,r.add(n),r.add(i)):r=i:(r=n).__graphDefaultObj=!0,r.renderOrder=10,r.__graphObjType="link",r}).onUpdateObj(function(t,n){if(t.__graphDefaultObj){var r=t.children.length?t.children[0]:t,i=Math.ceil(10*m(n))/10,s=!!i;if(s){var a=i/2,o=e.linkResolution;if(!r.geometry.type.match(/^Cylinder(Buffer)?Geometry$/)||r.geometry.parameters.radiusTop!==a||r.geometry.parameters.radialSegments!==o){if(!g.hasOwnProperty(i)){var l=new Pp.CylinderGeometry(a,a,1,o,1,!1);l[Ip]((new Pp.Matrix4).makeTranslation(0,.5,0)),l[Ip]((new Pp.Matrix4).makeRotationX(Math.PI/2)),g[i]=l}r.geometry.dispose(),r.geometry=g[i]}}var u=d(n);if(u)r.material=u;else{var c=f(n),h=new Pp.Color(Ap(c||"#f0f0f0")),p=e.linkOpacity*Rp(c),y=s?"MeshLambertMaterial":"LineBasicMaterial";if(r.material.type!==y||!r.material.color.equals(h)||r.material.opacity!==p){var x=s?_:v;x.hasOwnProperty(c)||(x[c]=new Pp[y]({color:h,transparent:p<1,opacity:p,depthWrite:p>=1})),r.material.dispose(),r.material=x[c]}}}}).digest(y),e.linkDirectionalArrowLength||t.hasOwnProperty("linkDirectionalArrowLength")){var x=Xh(e.linkDirectionalArrowLength),b=Xh(e.linkDirectionalArrowColor);e.arrowDataMapper.onCreateObj(function(){var e=new Pp.Mesh(void 0,new Pp.MeshLambertMaterial({transparent:!0}));return e.__linkThreeObjType="arrow",e}).onUpdateObj(function(t,n){var r=x(n),i=e.linkDirectionalArrowResolution;if(!t.geometry.type.match(/^Cone(Buffer)?Geometry$/)||t.geometry.parameters.height!==r||t.geometry.parameters.radialSegments!==i){var s=new Pp.ConeGeometry(.25*r,r,i);s.translate(0,r/2,0),s.rotateX(Math.PI/2),t.geometry.dispose(),t.geometry=s}var a=b(n)||f(n)||"#f0f0f0";t.material.color=new Pp.Color(Ap(a)),t.material.opacity=3*e.linkOpacity*Rp(a)}).digest(y.filter(x))}if(e.linkDirectionalParticles||t.hasOwnProperty("linkDirectionalParticles")){var T=Xh(e.linkDirectionalParticles),S=Xh(e.linkDirectionalParticleWidth),M=Xh(e.linkDirectionalParticleColor),w=Xh(e.linkDirectionalParticleThreeObject),E={},A={};e.particlesDataMapper.onCreateObj(function(){var e=new Pp.Group;return e.__linkThreeObjType="photons",e.__photonDataMapper=new Ep(e),e}).onUpdateObj(function(t,n){var r,i,s=!!t.children.length&&t.children[0],a=w(n);if(a)r=a.geometry,i=a.material;else{var o=Math.ceil(10*S(n))/10/2,l=e.linkDirectionalParticleResolution;s&&s.geometry.parameters.radius===o&&s.geometry.parameters.widthSegments===l?r=s.geometry:(A.hasOwnProperty(o)||(A[o]=new Pp.SphereGeometry(o,l,l)),r=A[o]);var u=M(n)||f(n)||"#f0f0f0",c=new Pp.Color(Ap(u)),h=3*e.linkOpacity;s&&s.material.color.equals(c)&&s.material.opacity===h?i=s.material:(E.hasOwnProperty(u)||(E[u]=new Pp.MeshLambertMaterial({color:c,transparent:!0,opacity:h})),i=E[u])}s&&(s.geometry!==r&&s.geometry.dispose(),s.material!==i&&s.material.dispose());var d=Math.round(Math.abs(T(n)));t.__photonDataMapper.id(function(e){return e.idx}).onCreateObj(function(){return new Pp.Mesh(r,i)}).onUpdateObj(function(e){e.geometry=r,e.material=i}).digest(_p(new Array(d)).map(function(e,t){return{idx:t}}))}).digest(y.filter(T))}}if(e._flushObjects=!1,n(["graphData","nodeId","linkSource","linkTarget","numDimensions","forceEngine","dagMode","dagNodeFilter","dagLevelDistance"])){e.engineRunning=!1,e.graphData.links.forEach(function(t){t.source=t[e.linkSource],t.target=t[e.linkTarget]});var R,C="ngraph"!==e.forceEngine;if(C){(R=e.d3ForceLayout).stop().alpha(1).numDimensions(e.numDimensions).nodes(e.graphData.nodes);var N=e.d3ForceLayout.force("link");N&&N.id(function(t){return t[e.nodeId]}).links(e.graphData.links);var P=e.dagMode&&function(e,t){var n=e.nodes,r=e.links,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},s=i.nodeFilter,a=void 0===s?function(){return!0}:s,o=i.onLoopError,l=void 0===o?function(e){throw"Invalid DAG structure! Found cycle in node path: ".concat(e.join(" -> "),".")}:o,u={};n.forEach(function(e){return u[t(e)]={data:e,out:[],depth:-1,skip:!a(e)}}),r.forEach(function(e){var n=e.source,r=e.target,i=l(n),s=l(r);if(!u.hasOwnProperty(i))throw"Missing source node with id: ".concat(i);if(!u.hasOwnProperty(s))throw"Missing target node with id: ".concat(s);var a=u[i],o=u[s];function l(e){return"object"===yp(e)?t(e):e}a.out.push(o)});var c=[];return function e(n){for(var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=function(){var s=n[a];if(-1!==r.indexOf(s)){var o=[].concat(_p(r.slice(r.indexOf(s))),[s]).map(function(e){return t(e.data)});return c.some(function(e){return e.length===o.length&&e.every(function(e,t){return e===o[t]})})||(c.push(o),l(o)),1}i>s.depth&&(s.depth=i,e(s.out,[].concat(_p(r),[s]),i+(s.skip?0:1)))},a=0,o=n.length;a<o;a++)s()}(Object.values(u)),Object.assign.apply(Object,[{}].concat(_p(Object.entries(u).filter(function(e){return!mp(e,2)[1].skip}).map(function(e){var t=mp(e,2);return lp({},t[0],t[1].depth)}))))}(e.graphData,function(t){return t[e.nodeId]},{nodeFilter:e.dagNodeFilter,onLoopError:e.onDagError||void 0}),L=Math.max.apply(Math,_p(Object.values(P||[]))),D=e.dagLevelDistance||e.graphData.nodes.length/(L||1)*2*(-1!==["radialin","radialout"].indexOf(e.dagMode)?.7:1);if(["lr","rl","td","bu","zin","zout"].includes(t.dagMode)){var I=["lr","rl"].includes(t.dagMode)?"fx":["td","bu"].includes(t.dagMode)?"fy":"fz";e.graphData.nodes.filter(e.dagNodeFilter).forEach(function(e){return delete e[I]})}if(["lr","rl","td","bu","zin","zout"].includes(e.dagMode)){var U=["rl","td","zout"].includes(e.dagMode),O=["lr","rl"].includes(e.dagMode)?"fx":["td","bu"].includes(e.dagMode)?"fy":"fz";e.graphData.nodes.filter(e.dagNodeFilter).forEach(function(t){return t[O]=function(t){return(P[t[e.nodeId]]-L/2)*D*(U?-1:1)}(t)})}e.d3ForceLayout.force("dagRadial",-1!==["radialin","radialout"].indexOf(e.dagMode)?function(e,t,n,r){var i,s,a,o,l=Qu(.1);function u(e){for(var l=0,u=i.length;l<u;++l){var c=i[l],h=c.x-t||1e-6,d=(c.y||0)-n||1e-6,p=(c.z||0)-r||1e-6,f=Math.sqrt(h*h+d*d+p*p),m=(o[l]-f)*a[l]*e/f;c.vx+=h*m,s>1&&(c.vy+=d*m),s>2&&(c.vz+=p*m)}}function c(){if(i){var t,n=i.length;for(a=new Array(n),o=new Array(n),t=0;t<n;++t)o[t]=+e(i[t],t,i),a[t]=isNaN(o[t])?0:+l(i[t],t,i)}}return"function"!=typeof e&&(e=Qu(+e)),null==t&&(t=0),null==n&&(n=0),null==r&&(r=0),u.initialize=function(e,...t){i=e,s=t.find(e=>[1,2,3].includes(e))||2,c()},u.strength=function(e){return arguments.length?(l="function"==typeof e?e:Qu(+e),c(),u):l},u.radius=function(t){return arguments.length?(e="function"==typeof t?t:Qu(+t),c(),u):e},u.x=function(e){return arguments.length?(t=+e,u):t},u.y=function(e){return arguments.length?(n=+e,u):n},u.z=function(e){return arguments.length?(r=+e,u):r},u}(function(t){var n=P[t[e.nodeId]]||-1;return("radialin"===e.dagMode?L-n:n)*D}).strength(function(t){return e.dagNodeFilter(t)?1:0}):null)}else{var F=Lp.graph();e.graphData.nodes.forEach(function(t){F.addNode(t[e.nodeId])}),e.graphData.links.forEach(function(e){F.addLink(e.source,e.target)}),R=Lp.forcelayout(F,function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?pp(Object(n),!0).forEach(function(t){lp(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):pp(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}({dimensions:e.numDimensions},e.ngraphPhysics)),R.graph=F}for(var B=0;B<e.warmupTicks&&!(C&&e.d3AlphaMin>0&&e.d3ForceLayout.alpha()<e.d3AlphaMin);B++)R[C?"tick":"step"]();e.layout=R,this.resetCountdown()}e.engineRunning=!0,e.onFinishUpdate()}});var Op=function(e){var t=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=function(n){function r(){var n;np(this,r);for(var i=arguments.length,s=new Array(i),a=0;a<i;a++)s[a]=arguments[a];return(n=tp(this,r,[].concat(s))).__kapsuleInstance=ap(e,[].concat(_p(t?[n]:[]),s)),n}return hp(r,n),op(r)}(arguments.length>1&&void 0!==arguments[1]?arguments[1]:Object);return Object.keys(e()).forEach(function(e){return n.prototype[e]=function(){var t,n=(t=this.__kapsuleInstance)[e].apply(t,arguments);return n===this.__kapsuleInstance?this:n}}),n}(Up,(window.THREE?window.THREE:{Group:Ci}).Group,!0);const Fp=["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"];class Bp{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=!0===e.object.isSkinnedMesh,this.refreshUniforms=Fp,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:n,material:r,object:i}=e;if(t={material:this.getMaterialData(r),geometry:{id:n.id,attributes:this.getAttributesData(n.attributes),indexVersion:n.index?n.index.version:null,drawRange:{start:n.drawRange.start,count:n.drawRange.count}},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),t.material.transmission>0){const{width:n,height:r}=e.context;t.bufferWidth=n,t.bufferHeight=r}this.renderObjects.set(e,t)}return t}getAttributesData(e){const t={};for(const n in e){const r=e[n];t[n]={version:r.version}}return t}containsNode(e){const t=e.material;for(const e in t)if(t[e]&&t[e].isNode)return!0;return null!==e.renderer.overrideNodes.modelViewMatrix||null!==e.renderer.overrideNodes.modelNormalViewMatrix}getMaterialData(e){const t={};for(const n of this.refreshUniforms){const r=e[n];null!=r&&("object"==typeof r&&void 0!==r.clone?!0===r.isTexture?t[n]={id:r.id,version:r.version}:t[n]=r.clone():t[n]=r)}return t}equals(e){const{object:t,material:n,geometry:r}=e,i=this.getRenderObjectData(e);if(!0!==i.worldMatrix.equals(t.matrixWorld))return i.worldMatrix.copy(t.matrixWorld),!1;const s=i.material;for(const e in s){const t=s[e],r=n[e];if(void 0!==t.equals){if(!1===t.equals(r))return t.copy(r),!1}else if(!0===r.isTexture){if(t.id!==r.id||t.version!==r.version)return t.id=r.id,t.version=r.version,!1}else if(t!==r)return s[e]=r,!1}if(s.transmission>0){const{width:t,height:n}=e.context;if(i.bufferWidth!==t||i.bufferHeight!==n)return i.bufferWidth=t,i.bufferHeight=n,!1}const a=i.geometry,o=r.attributes,l=a.attributes,u=Object.keys(l),c=Object.keys(o);if(a.id!==r.id)return a.id=r.id,!1;if(u.length!==c.length)return i.geometry.attributes=this.getAttributesData(o),!1;for(const e of u){const t=l[e],n=o[e];if(void 0===n)return delete l[e],!1;if(t.version!==n.version)return t.version=n.version,!1}const h=r.index,d=a.indexVersion,p=h?h.version:null;if(d!==p)return a.indexVersion=p,!1;if(a.drawRange.start!==r.drawRange.start||a.drawRange.count!==r.drawRange.count)return a.drawRange.start=r.drawRange.start,a.drawRange.count=r.drawRange.count,!1;if(i.morphTargetInfluences){let e=!1;for(let n=0;n<i.morphTargetInfluences.length;n++)i.morphTargetInfluences[n]!==t.morphTargetInfluences[n]&&(e=!0);if(e)return!0}return i.center&&!1===i.center.equals(t.center)?(i.center.copy(t.center),!0):(null!==e.bundle&&(i.version=e.bundle.version),!0)}needsRefresh(e,t){if(this.hasNode||this.hasAnimation||this.firstInitialization(e)||this.needsVelocity(t.renderer))return!0;const{renderId:n}=t;if(this.renderId!==n)return this.renderId=n,!0;const r=!0===e.object.static,i=null!==e.bundle&&!0===e.bundle.static&&this.getRenderObjectData(e).version===e.bundle.version;if(r||i)return!1;return!0!==this.equals(e)}}function kp(e,t=0){let n=3735928559^t,r=1103547991^t;if(e instanceof Array)for(let t,i=0;i<e.length;i++)t=e[i],n=Math.imul(n^t,2654435761),r=Math.imul(r^t,1597334677);else for(let t,i=0;i<e.length;i++)t=e.charCodeAt(i),n=Math.imul(n^t,2654435761),r=Math.imul(r^t,1597334677);return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}const zp=e=>kp(e),Vp=(...e)=>kp(e);function Gp(e,t=!1){const n=[];!0===e.isNode&&(n.push(e.id),e=e.getSelf());for(const{property:r,childNode:i}of Hp(e))n.push(kp(r.slice(0,-4)),i.getCacheKey(t));return kp(n)}function*Hp(e,t=!1){for(const n in e){if(!0===n.startsWith("_"))continue;const r=e[n];if(!0===Array.isArray(r))for(let e=0;e<r.length;e++){const i=r[e];i&&(!0===i.isNode||t&&"function"==typeof i.toJSON)&&(yield{property:n,index:e,childNode:i})}else if(r&&!0===r.isNode)yield{property:n,childNode:r};else if("object"==typeof r)for(const e in r){const i=r[e];i&&(!0===i.isNode||t&&"function"==typeof i.toJSON)&&(yield{property:n,index:e,childNode:i})}}}const jp=new Map([[1,"float"],[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),Wp=new WeakMap;function Xp(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 qp(e,...t){const n=e?e.slice(-4):void 0;return 1===t.length&&("vec2"===n?t=[t[0],t[0]]:"vec3"===n?t=[t[0],t[0],t[0]]:"vec4"===n&&(t=[t[0],t[0],t[0],t[0]])),"color"===e?new Nr(...t):"vec2"===n?new Dt(...t):"vec3"===n?new Ut(...t):"vec4"===n?new an(...t):"mat2"===n?new _a(...t):"mat3"===n?new Bt(...t):"mat4"===n?new Bn(...t):"bool"===e?t[0]||!1:"float"===e||"int"===e||"uint"===e?t[0]||0:"string"===e?t[0]||"":"ArrayBuffer"===e?(r=t[0],Uint8Array.from(atob(r),e=>e.charCodeAt(0)).buffer):null;var r}function $p(e){let t=Wp.get(e);return void 0===t&&(t={},Wp.set(e,t)),t}const Yp="vertex",Kp="none",Qp="frame",Zp="render",Jp="object",ef="readOnly",tf="writeOnly",nf="readWrite",rf=["setup","analyze","generate"],sf=["fragment","vertex","compute"],af=["x","y","z","w"],of={analyze:"setup",generate:"analyze"};let lf=0;class uf extends bt{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=Kp,this.updateBeforeType=Kp,this.updateAfterType=Kp,this.uuid=Lt.generateUUID(),this.version=0,this.global=!1,this.parents=!1,this.isNode=!0,this._cacheKey=null,this._cacheKeyVersion=0,Object.defineProperty(this,"id",{value:lf++})}set needsUpdate(e){!0===e&&this.version++}get type(){return this.constructor.type}onUpdate(e,t){return this.updateType=t,this.update=e.bind(this.getSelf()),this}onFrameUpdate(e){return this.onUpdate(e,Qp)}onRenderUpdate(e){return this.onUpdate(e,Zp)}onObjectUpdate(e){return this.onUpdate(e,Jp)}onReference(e){return this.updateReference=e.bind(this.getSelf()),this}getSelf(){return this.self||this}updateReference(){return this}isGlobal(){return this.global}*getChildren(){for(const{childNode:e}of Hp(this))yield e}dispose(){this.dispatchEvent({type:"dispose"})}traverse(e){e(this);for(const t of this.getChildren())t.traverse(e)}getCacheKey(e=!1){return!0!==(e=e||this.version!==this._cacheKeyVersion)&&null!==this._cacheKey||(this._cacheKey=Vp(Gp(this,e),this.customCacheKey()),this._cacheKeyVersion=this.version),this._cacheKey}customCacheKey(){return 0}getScope(){return this}getHash(){return this.uuid}getUpdateType(){return this.updateType}getUpdateBeforeType(){return this.updateBeforeType}getUpdateAfterType(){return this.updateAfterType}getElementType(e){const t=this.getNodeType(e);return e.getElementType(t)}getMemberType(){return"void"}getNodeType(e){const t=e.getNodeProperties(this);return t.outputNode?t.outputNode.getNodeType(e):this.nodeType}getShared(e){const t=this.getHash(e);return e.getNodeFromHash(t)||this}setup(e){const t=e.getNodeProperties(this);let n=0;for(const e of this.getChildren())t["node"+n++]=e;return t.outputNode||null}analyze(e,t=null){const n=e.increaseUsage(this);if(!0===this.parents){const n=e.getDataFromNode(this,"any");n.stages=n.stages||{},n.stages[e.shaderStage]=n.stages[e.shaderStage]||[],n.stages[e.shaderStage].push(t)}if(1===n){const t=e.getNodeProperties(this);for(const n of Object.values(t))n&&!0===n.isNode&&n.build(e,this)}}generate(e,t){const{outputNode:n}=e.getNodeProperties(this);if(n&&!0===n.isNode)return n.build(e,t)}updateBefore(){console.warn("Abstract function.")}updateAfter(){console.warn("Abstract function.")}update(){console.warn("Abstract function.")}build(e,t=null){const n=this.getShared(e);if(this!==n)return n.build(e,t);const r=e.getDataFromNode(this);r.buildStages=r.buildStages||{},r.buildStages[e.buildStage]=!0;const i=of[e.buildStage];if(i&&!0!==r.buildStages[i]){const t=e.getBuildStage();e.setBuildStage(i),this.build(e),e.setBuildStage(t)}e.addNode(this),e.addChain(this);let s=null;const a=e.getBuildStage();if("setup"===a){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 n of Object.values(t))if(n&&!0===n.isNode){if(!0===n.parents){const t=e.getNodeProperties(n);t.parents=t.parents||[],t.parents.push(this)}n.build(e)}}s=t.outputNode}else if("analyze"===a)this.analyze(e,t);else if("generate"===a){if(1===this.generate.length){const n=this.getNodeType(e),r=e.getDataFromNode(this);s=r.snippet,void 0===s?void 0===r.generated?(r.generated=!0,s=this.generate(e)||"",r.snippet=s):(console.warn("THREE.Node: Recursion detected.",this),s="/* Recursion detected. */"):void 0!==r.flowCodes&&void 0!==e.context.nodeBlock&&e.addFlowCodeHierarchy(this,e.context.nodeBlock),s=e.format(s,n,t)}else s=this.generate(e,t)||""}return e.removeChain(this),e.addSequentialNode(this),s}getSerializeChildren(){return Hp(this)}serialize(e){const t=this.getSerializeChildren(),n={};for(const{property:r,index:i,childNode:s}of t)void 0!==i?(void 0===n[r]&&(n[r]=Number.isInteger(i)?[]:{}),n[r][i]=s.toJSON(e.meta).uuid):n[r]=s.toJSON(e.meta).uuid;Object.keys(n).length>0&&(e.inputNodes=n)}deserialize(e){if(void 0!==e.inputNodes){const t=e.meta.nodes;for(const n in e.inputNodes)if(Array.isArray(e.inputNodes[n])){const r=[];for(const i of e.inputNodes[n])r.push(t[i]);this[n]=r}else if("object"==typeof e.inputNodes[n]){const r={};for(const i in e.inputNodes[n]){const s=e.inputNodes[n][i];r[i]=t[s]}this[n]=r}else{const r=e.inputNodes[n];this[n]=t[r]}}}toJSON(e){const{uuid:t,type:n}=this,r=void 0===e||"string"==typeof e;r&&(e={textures:{},images:{},nodes:{}});let i=e.nodes[t];function s(e){const t=[];for(const n in e){const r=e[n];delete r.metadata,t.push(r)}return t}if(void 0===i&&(i={uuid:t,type:n,meta:e,metadata:{version:4.7,type:"Node",generator:"Node.toJSON"}},!0!==r&&(e.nodes[i.uuid]=i),this.serialize(i),delete i.meta),r){const t=s(e.textures),n=s(e.images),r=s(e.nodes);t.length>0&&(i.textures=t),n.length>0&&(i.images=n),r.length>0&&(i.nodes=r)}return i}}class cf extends uf{static get type(){return"ArrayElementNode"}constructor(e,t){super(),this.node=e,this.indexNode=t,this.isArrayElementNode=!0}getNodeType(e){return this.node.getElementType(e)}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 hf extends uf{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}getNodeType(e){const t=this.node.getNodeType(e);let n=null;for(const r of this.convertTo.split("|"))null!==n&&e.getTypeLength(t)!==e.getTypeLength(r)||(n=r);return n}serialize(e){super.serialize(e),e.convertTo=this.convertTo}deserialize(e){super.deserialize(e),this.convertTo=e.convertTo}generate(e,t){const n=this.node,r=this.getNodeType(e),i=n.build(e,r);return e.format(i,r,t)}}class df extends uf{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 n=e.getVectorType(this.getNodeType(e,t)),r=e.getDataFromNode(this);if(void 0!==r.propertyName)return e.format(r.propertyName,n,t);if("void"!==n&&"void"!==t&&this.hasDependencies(e)){const i=super.build(e,n),s=e.getVarFromNode(this,null,n),a=e.getPropertyName(s);return e.addLineFlowCode(`${a} = ${i}`,this),r.snippet=i,r.propertyName=a,e.format(r.propertyName,n,t)}}return super.build(e,t)}}class pf extends df{static get type(){return"JoinNode"}constructor(e=[],t=null){super(t),this.nodes=e}getNodeType(e){return null!==this.nodeType?e.getVectorType(this.nodeType):e.getTypeFromLength(this.nodes.reduce((t,n)=>t+e.getTypeLength(n.getNodeType(e)),0))}generate(e,t){const n=this.getNodeType(e),r=e.getTypeLength(n),i=this.nodes,s=e.getComponentType(n),a=[];let o=0;for(const t of i){if(o>=r){console.error(`THREE.TSL: Length of parameters exceeds maximum length of function '${n}()' type.`);break}let i,l=t.getNodeType(e),u=e.getTypeLength(l);o+u>r&&(console.error(`THREE.TSL: Length of '${n}()' data exceeds maximum length of output type.`),u=r-o,l=e.getTypeFromLength(u)),o+=u,i=t.build(e,l);const c=e.getComponentType(l);c!==s&&(i=e.format(i,c,s)),a.push(i)}const l=`${e.getType(n)}( ${a.join(", ")} )`;return e.format(l,n,t)}}const ff=af.join("");class mf extends uf{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(af.indexOf(t)+1,e);return e}getComponentType(e){return e.getComponentType(this.node.getNodeType(e))}getNodeType(e){return e.getTypeFromLength(this.components.length,this.getComponentType(e))}generate(e,t){const n=this.node,r=e.getTypeLength(n.getNodeType(e));let i=null;if(r>1){let s=null;this.getVectorLength()>=r&&(s=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));const a=n.build(e,s);i=this.components.length===r&&this.components===ff.slice(0,this.components.length)?e.format(a,s,t):e.format(`${a}.${this.components}`,this.getNodeType(e),t)}else i=n.build(e,t);return i}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}}class gf extends df{static get type(){return"SetNode"}constructor(e,t,n){super(),this.sourceNode=e,this.components=t,this.targetNode=n}getNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{sourceNode:t,components:n,targetNode:r}=this,i=this.getNodeType(e),s=e.getComponentType(r.getNodeType(e)),a=e.getTypeFromLength(n.length,s),o=r.build(e,a),l=t.build(e,i),u=e.getTypeLength(i),c=[];for(let e=0;e<u;e++){const t=af[e];t===n[0]?(c.push(o),e+=n.length-1):c.push(l+"."+t)}return`${e.getType(i)}( ${c.join(", ")} )`}}class _f extends df{static get type(){return"FlipNode"}constructor(e,t){super(),this.sourceNode=e,this.components=t}getNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{components:t,sourceNode:n}=this,r=this.getNodeType(e),i=n.build(e),s=e.getVarFromNode(this),a=e.getPropertyName(s);e.addLineFlowCode(a+" = "+i,this);const o=e.getTypeLength(r),l=[];let u=0;for(let e=0;e<o;e++){const n=af[e];n===t[u]?(l.push("1.0 - "+a+"."+n),u++):l.push(a+"."+n)}return`${e.getType(r)}( ${l.join(", ")} )`}}class vf extends uf{static get type(){return"InputNode"}constructor(e,t=null){super(t),this.isInputNode=!0,this.value=e,this.precision=null}getNodeType(){return null===this.nodeType?Xp(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=Xp(this.value),e.nodeType=this.nodeType,"ArrayBuffer"===e.valueType&&(e.value=function(e){let t="";const n=new Uint8Array(e);for(let e=0;e<n.length;e++)t+=String.fromCharCode(n[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)?qp(e.valueType,...e.value):e.value,this.precision=e.precision||null,this.value&&this.value.fromArray&&(this.value=this.value.fromArray(e.value))}generate(){console.warn("Abstract function.")}}const yf=/float|u?int/;class xf extends vf{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 n=this.getNodeType(e);return yf.test(n)&&yf.test(t)?e.generateConst(t,this.value):e.format(this.generateConst(e),n,t)}}class bf extends uf{static get type(){return"MemberNode"}constructor(e,t){super(),this.node=e,this.property=t,this.isMemberNode=!0}getNodeType(e){return this.node.getMemberType(e,this.property)}generate(e){return this.node.build(e)+"."+this.property}}let Tf=null;const Sf=new Map;function Mf(e,t){if(Sf.has(e))console.warn(`THREE.TSL: Redefinition of method chaining '${e}'.`);else{if("function"!=typeof t)throw new Error(`THREE.TSL: Node element ${e} is not a function`);Sf.set(e,t)}}const wf=e=>e.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"),Ef=e=>wf(e).split("").sort().join(""),Af={setup(e,t){const n=t.shift();return e(Qf(n),...t)},get(e,t,n){if("string"==typeof t&&void 0===e[t]){if(!0!==e.isStackNode&&"assign"===t)return(...e)=>(Tf.assign(n,...e),n);if(Sf.has(t)){const r=Sf.get(t);return e.isStackNode?(...e)=>n.add(r(...e)):(...e)=>r(n,...e)}if("self"===t)return e;if(t.endsWith("Assign")&&Sf.has(t.slice(0,t.length-6))){const r=Sf.get(t.slice(0,t.length-6));return e.isStackNode?(...e)=>n.assign(e[0],r(...e)):(...e)=>n.assign(r(n,...e))}if(!0===/^[xyzwrgbastpq]{1,4}$/.test(t))return t=wf(t),Kf(new mf(n,t));if(!0===/^set[XYZWRGBASTPQ]{1,4}$/.test(t))return t=Ef(t.slice(3).toLowerCase()),n=>Kf(new gf(e,t,Kf(n)));if(!0===/^flip[XYZWRGBASTPQ]{1,4}$/.test(t))return t=Ef(t.slice(4).toLowerCase()),()=>Kf(new _f(Kf(e),t));if("width"===t||"height"===t||"depth"===t)return"width"===t?t="x":"height"===t?t="y":"depth"===t&&(t="z"),Kf(new mf(e,t));if(!0===/^\d+$/.test(t))return Kf(new cf(n,new xf(Number(t),"uint")));if(!0===/^get$/.test(t))return e=>Kf(new bf(n,e))}return Reflect.get(e,t,n)},set:(e,t,n,r)=>"string"!=typeof t||void 0!==e[t]||!0!==/^[xyzwrgbastpq]{1,4}$/.test(t)&&"width"!==t&&"height"!==t&&"depth"!==t&&!0!==/^\d+$/.test(t)?Reflect.set(e,t,n,r):(r[t].assign(n),!0)},Rf=new WeakMap,Cf=new WeakMap,Nf=function(e,t=null){for(const n in e)e[n]=Kf(e[n],t);return e},Pf=function(e,t=null){const n=e.length;for(let r=0;r<n;r++)e[r]=Kf(e[r],t);return e},Lf=function(e,t=null,n=null,r=null){const i=e=>Kf(null!==r?Object.assign(e,r):e);let s,a,o,l=t;function u(t){let n;return n=l?/[a-z]/i.test(l)?l+"()":l:e.type,void 0!==a&&t.length<a?(console.error(`THREE.TSL: "${n}" parameter length is less than minimum required.`),t.concat(new Array(a-t.length).fill(0))):void 0!==o&&t.length>o?(console.error(`THREE.TSL: "${n}" parameter length exceeds limit.`),t.slice(0,o)):t}return null===t?s=(...t)=>i(new e(...Zf(u(t)))):null!==n?(n=Kf(n),s=(...r)=>i(new e(t,...Zf(u(r)),n))):s=(...n)=>i(new e(t,...Zf(u(n)))),s.setParameterLength=(...e)=>(1===e.length?a=o=e[0]:2===e.length&&([a,o]=e),s),s.setName=e=>(l=e,s),s},Df=function(e,...t){return Kf(new e(...Zf(t)))};class If extends uf{constructor(e,t){super(),this.shaderNode=e,this.inputNodes=t,this.isShaderCallNodeInternal=!0}getNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}getMemberType(e,t){return this.getOutputNode(e).getMemberType(e,t)}call(e){const{shaderNode:t,inputNodes:n}=this,r=e.getNodeProperties(t),i=e.getClosestSubBuild(t.subBuilds)||"",s=i||"default";if(r[s])return r[s];const a=e.subBuildFn;e.subBuildFn=i;let o=null;if(t.layout){let r=Cf.get(e.constructor);void 0===r&&(r=new WeakMap,Cf.set(e.constructor,r));let i=r.get(t);void 0===i&&(i=Kf(e.buildFunctionNode(t)),r.set(t,i)),e.addInclude(i),o=Kf(i.call(n))}else{const r=t.jsFunc,i=null!==n||r.length>1?r(n||[],e):r(e);o=Kf(i)}return e.subBuildFn=a,t.once&&(r[s]=o),o}setupOutput(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}getOutputNode(e){const t=e.getNodeProperties(this),n=e.getSubBuildOutput(this);return t[n]=t[n]||this.setupOutput(e),t[n].subBuild=e.getClosestSubBuild(this),t[n]}build(e,t=null){let n=null;const r=e.getBuildStage(),i=e.getNodeProperties(this),s=e.getSubBuildOutput(this),a=this.getOutputNode(e);if("setup"===r){const t=e.getSubBuildProperty("initialized",this);if(!0!==i[t]&&(i[t]=!0,i[s]=this.getOutputNode(e),i[s].build(e),this.shaderNode.subBuilds))for(const t of e.chaining){const n=e.getDataFromNode(t,"any");n.subBuilds=n.subBuilds||new Set;for(const e of this.shaderNode.subBuilds)n.subBuilds.add(e)}n=i[s]}else"analyze"===r?a.build(e,t):"generate"===r&&(n=a.build(e,t)||"");return n}}class Uf extends uf{constructor(e,t){super(t),this.jsFunc=e,this.layout=null,this.global=!0,this.once=!1}setLayout(e){return this.layout=e,this}call(e=null){return Qf(e),Kf(new If(this,e))}setup(){return this.call()}}const Of=[!1,!0],Ff=[0,1,2,3],Bf=[-1,-2],kf=[.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],zf=new Map;for(const e of Of)zf.set(e,new xf(e));const Vf=new Map;for(const e of Ff)Vf.set(e,new xf(e,"uint"));const Gf=new Map([...Vf].map(e=>new xf(e.value,"int")));for(const e of Bf)Gf.set(e,new xf(e,"int"));const Hf=new Map([...Gf].map(e=>new xf(e.value)));for(const e of kf)Hf.set(e,new xf(e));for(const e of kf)Hf.set(-e,new xf(-e));const jf={bool:zf,uint:Vf,ints:Gf,float:Hf},Wf=new Map([...zf,...Hf]),Xf=(e,t)=>Wf.has(e)?Wf.get(e):!0===e.isNode?e:new xf(e,t),qf=function(e,t=null){return(...n)=>{if((0===n.length||!["bool","float","int","uint"].includes(e)&&n.every(e=>"object"!=typeof e))&&(n=[qp(e,...n)]),1===n.length&&null!==t&&t.has(n[0]))return Kf(t.get(n[0]));if(1===n.length){const t=Xf(n[0],e);return t.nodeType===e?Kf(t):Kf(new hf(t,e))}const r=n.map(e=>Xf(e));return Kf(new pf(r,e))}},$f=e=>"object"==typeof e&&null!==e?e.value:e;function Yf(e,t){return new Proxy(new Uf(e,t),Af)}const Kf=(e,t=null)=>function(e,t=null){const n=Xp(e);if("node"===n){let t=Rf.get(e);return void 0===t&&(t=new Proxy(e,Af),Rf.set(e,t),Rf.set(t,t)),t}return null===t&&("float"===n||"boolean"===n)||n&&"shader"!==n&&"string"!==n?Kf(Xf(e,t)):"shader"===n?e.isFn?e:nm(e):e}(e,t),Qf=(e,t=null)=>new Nf(e,t),Zf=(e,t=null)=>new Pf(e,t),Jf=(...e)=>new Lf(...e),em=(...e)=>new Df(...e);let tm=0;const nm=(e,t=null)=>{let n=null;null!==t&&("object"==typeof t?n=t.return:("string"==typeof t?n=t:console.error("THREE.TSL: Invalid layout type."),t=null));const r=new Yf(e,n),i=(...e)=>{let t;Qf(e);t=e[0]&&(e[0].isNode||Object.getPrototypeOf(e[0])!==Object.prototype)?[...e]:e[0];const i=r.call(t);return"void"===n&&i.toStack(),i};if(i.shaderNode=r,i.id=r.id,i.isFn=!0,i.getNodeType=(...e)=>r.getNodeType(...e),i.getCacheKey=(...e)=>r.getCacheKey(...e),i.setLayout=e=>(r.setLayout(e),i),i.once=(e=null)=>(r.once=!0,r.subBuilds=e,i),null!==t){if("object"!=typeof t.inputs){const e={name:"fn"+tm++,type:n,inputs:[]};for(const n in t)"return"!==n&&e.inputs.push({name:n,type:t[n]});t=e}i.setLayout(t)}return i},rm=e=>{Tf=e},im=()=>Tf,sm=(...e)=>Tf.If(...e);function am(e){return Tf&&Tf.add(e),e}Mf("toStack",am);const om=new qf("color"),lm=new qf("float",jf.float),um=new qf("int",jf.ints),cm=new qf("uint",jf.uint),hm=new qf("bool",jf.bool),dm=new qf("vec2"),pm=new qf("ivec2"),fm=new qf("uvec2"),mm=new qf("bvec2"),gm=new qf("vec3"),_m=new qf("ivec3"),vm=new qf("uvec3"),ym=new qf("bvec3"),xm=new qf("vec4"),bm=new qf("ivec4"),Tm=new qf("uvec4"),Sm=new qf("bvec4"),Mm=new qf("mat2"),wm=new qf("mat3"),Em=new qf("mat4");Mf("toColor",om),Mf("toFloat",lm),Mf("toInt",um),Mf("toUint",cm),Mf("toBool",hm),Mf("toVec2",dm),Mf("toIVec2",pm),Mf("toUVec2",fm),Mf("toBVec2",mm),Mf("toVec3",gm),Mf("toIVec3",_m),Mf("toUVec3",vm),Mf("toBVec3",ym),Mf("toVec4",xm),Mf("toIVec4",bm),Mf("toUVec4",Tm),Mf("toBVec4",Sm),Mf("toMat2",Mm),Mf("toMat3",wm),Mf("toMat4",Em);Mf("element",Jf(cf).setParameterLength(2)),Mf("convert",(e,t)=>Kf(new hf(Kf(e),t))),Mf("append",e=>(console.warn("THREE.TSL: .append() has been renamed to .toStack()."),am(e)));class Am extends uf{static get type(){return"PropertyNode"}constructor(e,t=null,n=!1){super(e),this.name=t,this.varying=n,this.isPropertyNode=!0,this.global=!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 Rm=(e,t)=>Kf(new Am(e,t)),Cm=(e,t)=>Kf(new Am(e,t,!0)),Nm=em(Am,"vec4","DiffuseColor"),Pm=em(Am,"vec3","EmissiveColor"),Lm=em(Am,"float","Roughness"),Dm=em(Am,"float","Metalness"),Im=em(Am,"float","Clearcoat"),Um=em(Am,"float","ClearcoatRoughness"),Om=em(Am,"vec3","Sheen"),Fm=em(Am,"float","SheenRoughness"),Bm=em(Am,"float","Iridescence"),km=em(Am,"float","IridescenceIOR"),zm=em(Am,"float","IridescenceThickness"),Vm=em(Am,"float","AlphaT"),Gm=em(Am,"float","Anisotropy"),Hm=em(Am,"vec3","AnisotropyT"),jm=em(Am,"vec3","AnisotropyB"),Wm=em(Am,"color","SpecularColor"),Xm=em(Am,"float","SpecularF90"),qm=em(Am,"float","Shininess"),$m=em(Am,"vec4","Output"),Ym=em(Am,"float","dashSize"),Km=em(Am,"float","gapSize"),Qm=em(Am,"float","IOR"),Zm=em(Am,"float","Transmission"),Jm=em(Am,"float","Thickness"),eg=em(Am,"float","AttenuationDistance"),tg=em(Am,"color","AttenuationColor"),ng=em(Am,"float","Dispersion");class rg extends uf{static get type(){return"UniformGroupNode"}constructor(e,t=!1,n=1){super("string"),this.name=e,this.shared=t,this.order=n,this.isUniformGroup=!0}serialize(e){super.serialize(e),e.name=this.name,e.version=this.version,e.shared=this.shared}deserialize(e){super.deserialize(e),this.name=e.name,this.version=e.version,this.shared=e.shared}}const ig=e=>new rg(e),sg=(e,t=0)=>new rg(e,!0,t),ag=sg("frame"),og=sg("render"),lg=ig("object");class ug extends vf{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=lg}label(e){return this.name=e,this}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}onUpdate(e,t){const n=this.getSelf();return e=e.bind(n),super.onUpdate(t=>{const r=e(t,n);void 0!==r&&(this.value=r)},t)}generate(e,t){const n=this.getNodeType(e),r=this.getUniformHash(e);let i=e.getNodeFromHash(r);void 0===i&&(e.setHashNode(this,r),i=this);const s=i.getInputType(e),a=e.getUniformFromNode(i,s,e.shaderStage,this.name||e.context.label),o=e.getPropertyName(a);return void 0!==e.context.label&&delete e.context.label,e.format(o,n,t)}}const cg=(e,t)=>{const n=(e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null)(t||e),r=e&&!0===e.isNode?e.node&&e.node.value||e.value:e;return Kf(new ug(r,n))};class hg extends df{static get type(){return"ArrayNode"}constructor(e,t,n=null){super(e),this.count=t,this.values=n,this.isArrayNode=!0}getNodeType(e){return null===this.nodeType&&(this.nodeType=this.values[0].getNodeType(e)),this.nodeType}getElementType(e){return this.getNodeType(e)}generate(e){const t=this.getNodeType(e);return e.generateArray(t,this.count,this.values)}}Mf("toArray",(e,t)=>((...e)=>{let t;if(1===e.length){const n=e[0];t=new hg(null,n.length,n)}else{const n=e[0],r=e[1];t=new hg(n,r)}return Kf(t)})(Array(t).fill(e)));class dg extends df{static get type(){return"AssignNode"}constructor(e,t){super(),this.targetNode=e,this.sourceNode=t,this.isAssignNode=!0}hasDependencies(){return!1}getNodeType(e,t){return"void"!==t?this.targetNode.getNodeType(e):"void"}needsSplitAssign(e){const{targetNode:t}=this;if(!1===e.isAvailable("swizzleAssign")&&t.isSplitNode&&t.components.length>1){const n=e.getTypeLength(t.node.getNodeType(e));return af.join("").slice(0,n)!==t.components}return!1}setup(e){const{targetNode:t,sourceNode:n}=this,r=e.getNodeProperties(this);r.sourceNode=n,r.targetNode=t.context({assign:!0})}generate(e,t){const{targetNode:n,sourceNode:r}=e.getNodeProperties(this),i=this.needsSplitAssign(e),s=n.getNodeType(e),a=n.build(e),o=r.build(e,s),l=r.getNodeType(e),u=e.getDataFromNode(this);let c;if(!0===u.initialized)"void"!==t&&(c=a);else if(i){const r=e.getVarFromNode(this,null,s),i=e.getPropertyName(r);e.addLineFlowCode(`${i} = ${o}`,this);const l=n.node,u=l.node.context({assign:!0}).build(e);for(let t=0;t<l.components.length;t++){const n=l.components[t];e.addLineFlowCode(`${u}.${n} = ${i}[ ${t} ]`,this)}"void"!==t&&(c=a)}else c=`${a} = ${o}`,"void"!==t&&"void"!==l||(e.addLineFlowCode(c,this),"void"!==t&&(c=a));return u.initialized=!0,e.format(c,s,t)}}Mf("assign",Jf(dg).setParameterLength(2));class pg extends df{static get type(){return"FunctionCallNode"}constructor(e=null,t={}){super(),this.functionNode=e,this.parameters=t}setParameters(e){return this.parameters=e,this}getParameters(){return this.parameters}getNodeType(e){return this.functionNode.getNodeType(e)}generate(e){const t=[],n=this.functionNode,r=n.getInputs(e),i=this.parameters,s=(t,n)=>{const r=n.type;let i;return i="pointer"===r?"&"+t.build(e):t.build(e,r),i};if(Array.isArray(i)){if(i.length>r.length)console.error("THREE.TSL: The number of provided parameters exceeds the expected number of inputs in 'Fn()'."),i.length=r.length;else if(i.length<r.length)for(console.error("THREE.TSL: The number of provided parameters is less than the expected number of inputs in 'Fn()'.");i.length<r.length;)i.push(lm(0));for(let e=0;e<i.length;e++)t.push(s(i[e],r[e]))}else for(const e of r){const n=i[e.name];void 0!==n?t.push(s(n,e)):(console.error(`THREE.TSL: Input '${e.name}' not found in 'Fn()'.`),t.push(s(lm(0),e)))}return`${n.build(e,"property")}( ${t.join(", ")} )`}}Mf("call",(e,...t)=>(t=t.length>1||t[0]&&!0===t[0].isNode?Zf(t):Qf(t[0]),Kf(new pg(Kf(e),t))));const fg={"==":"equal","!=":"notEqual","<":"lessThan",">":"greaterThan","<=":"lessThanEqual",">=":"greaterThanEqual","%":"mod"};class mg extends df{static get type(){return"OperatorNode"}constructor(e,t,n,...r){if(super(),r.length>0){let i=new mg(e,t,n);for(let t=0;t<r.length-1;t++)i=new mg(e,i,r[t]);t=i,n=r[r.length-1]}this.op=e,this.aNode=t,this.bNode=n,this.isOperatorNode=!0}getOperatorMethod(e,t){return e.getMethod(fg[this.op],t)}getNodeType(e){const t=this.op,n=this.aNode,r=this.bNode,i=n.getNodeType(e),s=r?r.getNodeType(e):null;if("void"===i||"void"===s)return"void";if("%"===t)return i;if("~"===t||"&"===t||"|"===t||"^"===t||">>"===t||"<<"===t)return e.getIntegerType(i);if("!"===t||"&&"===t||"||"===t||"^^"===t)return"bool";if("=="===t||"!="===t||"<"===t||">"===t||"<="===t||">="===t){const t=Math.max(e.getTypeLength(i),e.getTypeLength(s));return t>1?`bvec${t}`:"bool"}if(e.isMatrix(i)){if("float"===s)return i;if(e.isVector(s))return e.getVectorFromMatrix(i);if(e.isMatrix(s))return i}else if(e.isMatrix(s)){if("float"===i)return s;if(e.isVector(i))return e.getVectorFromMatrix(s)}return e.getTypeLength(s)>e.getTypeLength(i)?s:i}generate(e,t){const n=this.op,{aNode:r,bNode:i}=this,s=this.getNodeType(e);let a=null,o=null;"void"!==s?(a=r.getNodeType(e),o=i?i.getNodeType(e):null,"<"===n||">"===n||"<="===n||">="===n||"=="===n||"!="===n?e.isVector(a)?o=a:e.isVector(o)?a=o:a!==o&&(a=o="float"):">>"===n||"<<"===n?(a=s,o=e.changeComponentType(o,"uint")):"%"===n?(a=s,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=s):a=e.isMatrix(o)?"float"===a?"float":e.isVector(a)?e.getVectorFromMatrix(o):o=s:o=s):a=o=s;const l=r.build(e,a),u=i?i.build(e,o):null,c=e.getFunctionOperator(n);if("void"!==t){const r=e.renderer.coordinateSystem===yt;if("=="===n||"!="===n||"<"===n||">"===n||"<="===n||">="===n)return r&&e.isVector(a)?e.format(`${this.getOperatorMethod(e,t)}( ${l}, ${u} )`,s,t):e.format(`( ${l} ${n} ${u} )`,s,t);if("%"===n)return e.isInteger(o)?e.format(`( ${l} % ${u} )`,s,t):e.format(`${this.getOperatorMethod(e,s)}( ${l}, ${u} )`,s,t);if("!"===n||"~"===n)return e.format(`(${n}${l})`,a,t);if(c)return e.format(`${c}( ${l}, ${u} )`,s,t);if(e.isMatrix(a)&&"float"===o)return e.format(`( ${u} ${n} ${l} )`,s,t);if("float"===a&&e.isMatrix(o))return e.format(`${l} ${n} ${u}`,s,t);{let i=`( ${l} ${n} ${u} )`;return!r&&"bool"===s&&e.isVector(a)&&e.isVector(o)&&(i=`all${i}`),e.format(i,s,t)}}if("void"!==a)return c?e.format(`${c}( ${l}, ${u} )`,s,t):e.isMatrix(a)&&"float"===o?e.format(`${u} ${n} ${l}`,s,t):e.format(`${l} ${n} ${u}`,s,t)}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const gg=Jf(mg,"+").setParameterLength(2,1/0).setName("add"),_g=Jf(mg,"-").setParameterLength(2,1/0).setName("sub"),vg=Jf(mg,"*").setParameterLength(2,1/0).setName("mul"),yg=Jf(mg,"/").setParameterLength(2,1/0).setName("div"),xg=Jf(mg,"%").setParameterLength(2).setName("mod"),bg=Jf(mg,"==").setParameterLength(2).setName("equal"),Tg=Jf(mg,"!=").setParameterLength(2).setName("notEqual"),Sg=Jf(mg,"<").setParameterLength(2).setName("lessThan"),Mg=Jf(mg,">").setParameterLength(2).setName("greaterThan"),wg=Jf(mg,"<=").setParameterLength(2).setName("lessThanEqual"),Eg=Jf(mg,">=").setParameterLength(2).setName("greaterThanEqual"),Ag=Jf(mg,"&&").setParameterLength(2,1/0).setName("and"),Rg=Jf(mg,"||").setParameterLength(2,1/0).setName("or"),Cg=Jf(mg,"!").setParameterLength(1).setName("not"),Ng=Jf(mg,"^^").setParameterLength(2).setName("xor"),Pg=Jf(mg,"&").setParameterLength(2).setName("bitAnd"),Lg=Jf(mg,"~").setParameterLength(2).setName("bitNot"),Dg=Jf(mg,"|").setParameterLength(2).setName("bitOr"),Ig=Jf(mg,"^").setParameterLength(2).setName("bitXor"),Ug=Jf(mg,"<<").setParameterLength(2).setName("shiftLeft"),Og=Jf(mg,">>").setParameterLength(2).setName("shiftRight"),Fg=nm(([e])=>(e.addAssign(1),e)),Bg=nm(([e])=>(e.subAssign(1),e)),kg=nm(([e])=>{const t=um(e).toConst();return e.addAssign(1),t}),zg=nm(([e])=>{const t=um(e).toConst();return e.subAssign(1),t});Mf("add",gg),Mf("sub",_g),Mf("mul",vg),Mf("div",yg),Mf("mod",xg),Mf("equal",bg),Mf("notEqual",Tg),Mf("lessThan",Sg),Mf("greaterThan",Mg),Mf("lessThanEqual",wg),Mf("greaterThanEqual",Eg),Mf("and",Ag),Mf("or",Rg),Mf("not",Cg),Mf("xor",Ng),Mf("bitAnd",Pg),Mf("bitNot",Lg),Mf("bitOr",Dg),Mf("bitXor",Ig),Mf("shiftLeft",Ug),Mf("shiftRight",Og),Mf("incrementBefore",Fg),Mf("decrementBefore",Bg),Mf("increment",kg),Mf("decrement",zg);Mf("modInt",(e,t)=>(console.warn('THREE.TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.'),xg(um(e),um(t))));class Vg extends df{static get type(){return"MathNode"}constructor(e,t,n=null,r=null){if(super(),(e===Vg.MAX||e===Vg.MIN)&&arguments.length>3){let i=new Vg(e,t,n);for(let t=2;t<arguments.length-1;t++)i=new Vg(e,i,arguments[t]);t=i,n=arguments[arguments.length-1],r=null}this.method=e,this.aNode=t,this.bNode=n,this.cNode=r,this.isMathNode=!0}getInputType(e){const t=this.aNode.getNodeType(e),n=this.bNode?this.bNode.getNodeType(e):null,r=this.cNode?this.cNode.getNodeType(e):null,i=e.isMatrix(t)?0:e.getTypeLength(t),s=e.isMatrix(n)?0:e.getTypeLength(n),a=e.isMatrix(r)?0:e.getTypeLength(r);return i>s&&i>a?t:s>a?n:a>i?r:t}getNodeType(e){const t=this.method;return t===Vg.LENGTH||t===Vg.DISTANCE||t===Vg.DOT?"float":t===Vg.CROSS?"vec3":t===Vg.ALL||t===Vg.ANY?"bool":t===Vg.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):this.getInputType(e)}setup(e){const{aNode:t,bNode:n,method:r}=this;let i=null;if(r===Vg.ONE_MINUS)i=_g(1,t);else if(r===Vg.RECIPROCAL)i=yg(1,t);else if(r===Vg.DIFFERENCE)i=c_(_g(t,n));else if(r===Vg.TRANSFORM_DIRECTION){let r=t,s=n;e.isMatrix(r.getNodeType(e))?s=xm(gm(s),0):r=xm(gm(r),0);const a=vg(r,s).xyz;i=n_(a)}return null!==i?i:super.setup(e)}generate(e,t){if(e.getNodeProperties(this).outputNode)return super.generate(e,t);let n=this.method;const r=this.getNodeType(e),i=this.getInputType(e),s=this.aNode,a=this.bNode,o=this.cNode,l=e.renderer.coordinateSystem;if(n===Vg.NEGATE)return e.format("( - "+s.build(e,i)+" )",r,t);{const u=[];return n===Vg.CROSS?u.push(s.build(e,r),a.build(e,r)):l===yt&&n===Vg.STEP?u.push(s.build(e,1===e.getTypeLength(s.getNodeType(e))?"float":i),a.build(e,i)):l!==yt||n!==Vg.MIN&&n!==Vg.MAX?n===Vg.REFRACT?u.push(s.build(e,i),a.build(e,i),o.build(e,"float")):n===Vg.MIX?u.push(s.build(e,i),a.build(e,i),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":i)):(l===xt&&n===Vg.ATAN&&null!==a&&(n="atan2"),"fragment"===e.shaderStage||n!==Vg.DFDX&&n!==Vg.DFDY||(console.warn(`THREE.TSL: '${n}' is not supported in the ${e.shaderStage} stage.`),n="/*"+n+"*/"),u.push(s.build(e,i)),null!==a&&u.push(a.build(e,i)),null!==o&&u.push(o.build(e,i))):u.push(s.build(e,i),a.build(e,1===e.getTypeLength(a.getNodeType(e))?"float":i)),e.format(`${e.getMethod(n,r)}( ${u.join(", ")} )`,r,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}Vg.ALL="all",Vg.ANY="any",Vg.RADIANS="radians",Vg.DEGREES="degrees",Vg.EXP="exp",Vg.EXP2="exp2",Vg.LOG="log",Vg.LOG2="log2",Vg.SQRT="sqrt",Vg.INVERSE_SQRT="inversesqrt",Vg.FLOOR="floor",Vg.CEIL="ceil",Vg.NORMALIZE="normalize",Vg.FRACT="fract",Vg.SIN="sin",Vg.COS="cos",Vg.TAN="tan",Vg.ASIN="asin",Vg.ACOS="acos",Vg.ATAN="atan",Vg.ABS="abs",Vg.SIGN="sign",Vg.LENGTH="length",Vg.NEGATE="negate",Vg.ONE_MINUS="oneMinus",Vg.DFDX="dFdx",Vg.DFDY="dFdy",Vg.ROUND="round",Vg.RECIPROCAL="reciprocal",Vg.TRUNC="trunc",Vg.FWIDTH="fwidth",Vg.TRANSPOSE="transpose",Vg.BITCAST="bitcast",Vg.EQUALS="equals",Vg.MIN="min",Vg.MAX="max",Vg.STEP="step",Vg.REFLECT="reflect",Vg.DISTANCE="distance",Vg.DIFFERENCE="difference",Vg.DOT="dot",Vg.CROSS="cross",Vg.POW="pow",Vg.TRANSFORM_DIRECTION="transformDirection",Vg.MIX="mix",Vg.CLAMP="clamp",Vg.REFRACT="refract",Vg.SMOOTHSTEP="smoothstep",Vg.FACEFORWARD="faceforward";const Gg=lm(1e-6),Hg=lm(Math.PI),jg=Jf(Vg,Vg.ALL).setParameterLength(1),Wg=Jf(Vg,Vg.ANY).setParameterLength(1),Xg=Jf(Vg,Vg.RADIANS).setParameterLength(1),qg=Jf(Vg,Vg.DEGREES).setParameterLength(1),$g=Jf(Vg,Vg.EXP).setParameterLength(1),Yg=Jf(Vg,Vg.EXP2).setParameterLength(1),Kg=Jf(Vg,Vg.LOG).setParameterLength(1),Qg=Jf(Vg,Vg.LOG2).setParameterLength(1),Zg=Jf(Vg,Vg.SQRT).setParameterLength(1),Jg=Jf(Vg,Vg.INVERSE_SQRT).setParameterLength(1),e_=Jf(Vg,Vg.FLOOR).setParameterLength(1),t_=Jf(Vg,Vg.CEIL).setParameterLength(1),n_=Jf(Vg,Vg.NORMALIZE).setParameterLength(1),r_=Jf(Vg,Vg.FRACT).setParameterLength(1),i_=Jf(Vg,Vg.SIN).setParameterLength(1),s_=Jf(Vg,Vg.COS).setParameterLength(1),a_=Jf(Vg,Vg.TAN).setParameterLength(1),o_=Jf(Vg,Vg.ASIN).setParameterLength(1),l_=Jf(Vg,Vg.ACOS).setParameterLength(1),u_=Jf(Vg,Vg.ATAN).setParameterLength(1,2),c_=Jf(Vg,Vg.ABS).setParameterLength(1),h_=Jf(Vg,Vg.SIGN).setParameterLength(1),d_=Jf(Vg,Vg.LENGTH).setParameterLength(1),p_=Jf(Vg,Vg.NEGATE).setParameterLength(1),f_=Jf(Vg,Vg.ONE_MINUS).setParameterLength(1),m_=Jf(Vg,Vg.DFDX).setParameterLength(1),g_=Jf(Vg,Vg.DFDY).setParameterLength(1),__=Jf(Vg,Vg.ROUND).setParameterLength(1),v_=Jf(Vg,Vg.RECIPROCAL).setParameterLength(1),y_=Jf(Vg,Vg.TRUNC).setParameterLength(1),x_=Jf(Vg,Vg.FWIDTH).setParameterLength(1),b_=Jf(Vg,Vg.TRANSPOSE).setParameterLength(1),T_=Jf(Vg,Vg.MIN).setParameterLength(2,1/0),S_=Jf(Vg,Vg.MAX).setParameterLength(2,1/0),M_=Jf(Vg,Vg.STEP).setParameterLength(2),w_=Jf(Vg,Vg.REFLECT).setParameterLength(2),E_=Jf(Vg,Vg.DISTANCE).setParameterLength(2),A_=Jf(Vg,Vg.DIFFERENCE).setParameterLength(2),R_=Jf(Vg,Vg.DOT).setParameterLength(2),C_=Jf(Vg,Vg.CROSS).setParameterLength(2),N_=Jf(Vg,Vg.POW).setParameterLength(2),P_=Jf(Vg,Vg.POW,2).setParameterLength(1),L_=Jf(Vg,Vg.POW,3).setParameterLength(1),D_=Jf(Vg,Vg.POW,4).setParameterLength(1),I_=Jf(Vg,Vg.TRANSFORM_DIRECTION).setParameterLength(2),U_=e=>R_(e,e),O_=Jf(Vg,Vg.MIX).setParameterLength(3),F_=(e,t=0,n=1)=>Kf(new Vg(Vg.CLAMP,Kf(e),Kf(t),Kf(n))),B_=e=>F_(e),k_=Jf(Vg,Vg.REFRACT).setParameterLength(3),z_=Jf(Vg,Vg.SMOOTHSTEP).setParameterLength(3),V_=Jf(Vg,Vg.FACEFORWARD).setParameterLength(3),G_=nm(([e])=>{const t=R_(e.xy,dm(12.9898,78.233)),n=xg(t,Hg);return r_(i_(n).mul(43758.5453))});Mf("all",jg),Mf("any",Wg),Mf("equals",(e,t)=>(console.warn('THREE.TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"'),bg(e,t))),Mf("radians",Xg),Mf("degrees",qg),Mf("exp",$g),Mf("exp2",Yg),Mf("log",Kg),Mf("log2",Qg),Mf("sqrt",Zg),Mf("inverseSqrt",Jg),Mf("floor",e_),Mf("ceil",t_),Mf("normalize",n_),Mf("fract",r_),Mf("sin",i_),Mf("cos",s_),Mf("tan",a_),Mf("asin",o_),Mf("acos",l_),Mf("atan",u_),Mf("abs",c_),Mf("sign",h_),Mf("length",d_),Mf("lengthSq",U_),Mf("negate",p_),Mf("oneMinus",f_),Mf("dFdx",m_),Mf("dFdy",g_),Mf("round",__),Mf("reciprocal",v_),Mf("trunc",y_),Mf("fwidth",x_),Mf("atan2",(e,t)=>(console.warn('THREE.TSL: "atan2" is overloaded. Use "atan" instead.'),u_(e,t))),Mf("min",T_),Mf("max",S_),Mf("step",(e,t)=>M_(t,e)),Mf("reflect",w_),Mf("distance",E_),Mf("dot",R_),Mf("cross",C_),Mf("pow",N_),Mf("pow2",P_),Mf("pow3",L_),Mf("pow4",D_),Mf("transformDirection",I_),Mf("mix",(e,t,n)=>O_(t,n,e)),Mf("clamp",F_),Mf("refract",k_),Mf("smoothstep",(e,t,n)=>z_(t,n,e)),Mf("faceForward",V_),Mf("difference",A_),Mf("saturate",B_),Mf("cbrt",e=>vg(h_(e),N_(c_(e),1/3))),Mf("transpose",b_),Mf("rand",G_);class H_ extends uf{static get type(){return"ConditionalNode"}constructor(e,t,n=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=n}getNodeType(e){const{ifNode:t,elseNode:n}=e.getNodeProperties(this);if(void 0===t)return this.setup(e),this.getNodeType(e);const r=t.getNodeType(e);if(null!==n){const t=n.getNodeType(e);if(e.getTypeLength(t)>e.getTypeLength(r))return t}return r}setup(e){const t=this.condNode.cache(),n=this.ifNode.cache(),r=this.elseNode?this.elseNode.cache():null,i=e.context.nodeBlock;e.getDataFromNode(n).parentNodeBlock=i,null!==r&&(e.getDataFromNode(r).parentNodeBlock=i);const s=e.getNodeProperties(this);s.condNode=t,s.ifNode=n.context({nodeBlock:n}),s.elseNode=r?r.context({nodeBlock:r}):null}generate(e,t){const n=this.getNodeType(e),r=e.getDataFromNode(this);if(void 0!==r.nodeProperty)return r.nodeProperty;const{condNode:i,ifNode:s,elseNode:a}=e.getNodeProperties(this),o=e.currentFunctionNode,l="void"!==t,u=l?Rm(n).build(e):"";r.nodeProperty=u;const c=i.build(e,"bool");e.addFlowCode(`\n${e.tab}if ( ${c} ) {\n\n`).addFlowTab();let h=s.build(e,n);if(h&&(l?h=u+" = "+h+";":(h="return "+h+";",null===o&&(console.warn("THREE.TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values."),h="// "+h))),e.removeFlowTab().addFlowCode(e.tab+"\t"+h+"\n\n"+e.tab+"}"),null!==a){e.addFlowCode(" else {\n\n").addFlowTab();let t=a.build(e,n);t&&(l?t=u+" = "+t+";":(t="return "+t+";",null===o&&(console.warn("THREE.TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values."),t="// "+t))),e.removeFlowTab().addFlowCode(e.tab+"\t"+t+"\n\n"+e.tab+"}\n\n")}else e.addFlowCode("\n\n");return e.format(u,n,t)}}const j_=Jf(H_).setParameterLength(2,3);Mf("select",j_);class W_ extends uf{static get type(){return"ContextNode"}constructor(e,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}getNodeType(e){return this.node.getNodeType(e)}analyze(e){const t=e.getContext();e.setContext({...e.context,...this.value}),this.node.build(e),e.setContext(t)}setup(e){const t=e.getContext();e.setContext({...e.context,...this.value}),this.node.build(e),e.setContext(t)}generate(e,t){const n=e.getContext();e.setContext({...e.context,...this.value});const r=this.node.build(e,t);return e.setContext(n),r}}const X_=Jf(W_).setParameterLength(1,2);Mf("context",X_),Mf("label",(e,t)=>X_(e,{label:t}));class q_ extends uf{static get type(){return"VarNode"}constructor(e,t=null,n=!1){super(),this.node=e,this.name=t,this.global=!0,this.isVarNode=!0,this.readOnly=n,this.parents=!0}getMemberType(e,t){return this.node.getMemberType(e,t)}getElementType(e){return this.node.getElementType(e)}getNodeType(e){return this.node.getNodeType(e)}generate(e){const{node:t,name:n,readOnly:r}=this,{renderer:i}=e,s=!0===i.backend.isWebGPUBackend;let a=!1,o=!1;r&&(a=e.isDeterministic(t),o=s?r:a);const l=e.getVectorType(this.getNodeType(e)),u=t.build(e,l),c=e.getVarFromNode(this,n,l,void 0,o),h=e.getPropertyName(c);let d=h;if(o)if(s)d=a?`const ${h}`:`let ${h}`;else{const n=e.getArrayCount(t);d=`const ${e.getVar(c.type,h,n)}`}return e.addLineFlowCode(`${d} = ${u}`,this),h}}const $_=Jf(q_);Mf("toVar",(e,t=null)=>$_(e,t).toStack()),Mf("toConst",(e,t=null)=>$_(e,t,!0).toStack());Mf("temp",e=>(console.warn('TSL: "temp( node )" is deprecated. Use "Var( node )" or "node.toVar()" instead.'),$_(e)));class Y_ extends uf{static get type(){return"SubBuild"}constructor(e,t,n=null){super(n),this.node=e,this.name=t,this.isSubBuildNode=!0}getNodeType(e){if(null!==this.nodeType)return this.nodeType;e.addSubBuild(this.name);const t=this.node.getNodeType(e);return e.removeSubBuild(),t}build(e,...t){e.addSubBuild(this.name);const n=this.node.build(e,...t);return e.removeSubBuild(),n}}const K_=(e,t,n=null)=>Kf(new Y_(Kf(e),t,n));class Q_ extends uf{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=e,this.name=t,this.isVaryingNode=!0,this.interpolationType=null,this.interpolationSampling=null,this.global=!0}setInterpolation(e,t=null){return this.interpolationType=e,this.interpolationSampling=t,this}getHash(e){return this.name||super.getHash(e)}getNodeType(e){return this.node.getNodeType(e)}setupVarying(e){const t=e.getNodeProperties(this);let n=t.varying;if(void 0===n){const r=this.name,i=this.getNodeType(e),s=this.interpolationType,a=this.interpolationSampling;t.varying=n=e.getVaryingFromNode(this,r,i,s,a),t.node=K_(this.node,"VERTEX")}return n.needsInterpolation||(n.needsInterpolation="fragment"===e.shaderStage),n}setup(e){this.setupVarying(e),e.flowNodeFromShaderStage(Yp,this.node)}analyze(e){this.setupVarying(e),e.flowNodeFromShaderStage(Yp,this.node)}generate(e){const t=e.getSubBuildProperty("property",e.currentStack),n=e.getNodeProperties(this),r=this.setupVarying(e);if(void 0===n[t]){const i=this.getNodeType(e),s=e.getPropertyName(r,Yp);e.flowNodeFromShaderStage(Yp,n.node,i,s),n[t]=s}return e.getPropertyName(r)}}const Z_=Jf(Q_).setParameterLength(1,2);Mf("toVarying",Z_),Mf("toVertexStage",e=>Z_(e)),Mf("varying",(...e)=>(console.warn("THREE.TSL: .varying() has been renamed to .toVarying()."),Z_(...e))),Mf("vertexStage",(...e)=>(console.warn("THREE.TSL: .vertexStage() has been renamed to .toVertexStage()."),Z_(...e)));const J_=nm(([e])=>{const t=e.mul(.9478672986).add(.0521327014).pow(2.4),n=e.mul(.0773993808),r=e.lessThanEqual(.04045);return O_(t,n,r)}).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),ev=nm(([e])=>{const t=e.pow(.41666).mul(1.055).sub(.055),n=e.mul(12.92),r=e.lessThanEqual(.0031308);return O_(t,n,r)}).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),tv="WorkingColorSpace";class nv extends df{static get type(){return"ColorSpaceNode"}constructor(e,t,n){super("vec4"),this.colorNode=e,this.source=t,this.target=n}resolveColorSpace(e,t){return t===tv?$t.workingColorSpace:"OutputColorSpace"===t?e.context.outputColorSpace||e.renderer.outputColorSpace:t}setup(e){const{colorNode:t}=this,n=this.resolveColorSpace(e,this.source),r=this.resolveColorSpace(e,this.target);let i=t;return!1!==$t.enabled&&n!==r&&n&&r?($t.getTransfer(n)===at&&(i=xm(J_(i.rgb),i.a)),$t.getPrimaries(n)!==$t.getPrimaries(r)&&(i=xm(wm($t._getMatrix(new Bt,n,r)).mul(i.rgb),i.a)),$t.getTransfer(r)===at&&(i=xm(ev(i.rgb),i.a)),i):i}}const rv=(e,t)=>Kf(new nv(Kf(e),t,tv));Mf("workingToColorSpace",(e,t)=>Kf(new nv(Kf(e),tv,t))),Mf("colorSpaceToWorking",rv);let iv=class extends cf{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),n=this.referenceNode.getNodeType(),r=this.getNodeType();return e.format(t,n,r)}};class sv extends uf{static get type(){return"ReferenceBaseNode"}constructor(e,t,n=null,r=null){super(),this.property=e,this.uniformType=t,this.object=n,this.count=r,this.properties=e.split("."),this.reference=n,this.node=null,this.group=null,this.updateType=Jp}setGroup(e){return this.group=e,this}element(e){return Kf(new iv(this,Kf(e)))}setNodeType(e){const t=cg(null,e).getSelf();null!==this.group&&t.setGroup(this.group),this.node=t}getNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let n=e[t[0]];for(let e=1;e<t.length;e++)n=n[t[e]];return n}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 av extends sv{static get type(){return"RendererReferenceNode"}constructor(e,t,n=null){super(e,t,n),this.renderer=n,this.setGroup(og)}updateReference(e){return this.reference=null!==this.renderer?this.renderer:e.renderer,this.reference}}const ov=(e,t,n=null)=>Kf(new av(e,t,n));class lv extends df{static get type(){return"ToneMappingNode"}constructor(e,t=uv,n=null){super("vec3"),this.toneMapping=e,this.exposureNode=t,this.colorNode=n}customCacheKey(){return Vp(this.toneMapping)}setup(e){const t=this.colorNode||e.context.color,n=this.toneMapping;if(0===n)return t;let r=null;const i=e.renderer.library.getToneMappingFunction(n);return null!==i?r=xm(i(t.rgb,this.exposureNode),t.a):(console.error("ToneMappingNode: Unsupported Tone Mapping configuration.",n),r=t),r}}const uv=ov("toneMappingExposure","float");Mf("toneMapping",(e,t,n)=>((e,t,n)=>Kf(new lv(e,Kf(t),Kf(n))))(t,n,e));class cv extends vf{static get type(){return"BufferAttributeNode"}constructor(e,t=null,n=0,r=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=n,this.bufferOffset=r,this.usage=gt,this.instanced=!1,this.attribute=null,this.global=!0,e&&!0===e.isBufferAttribute&&(this.attribute=e,this.usage=e.usage,this.instanced=e.isInstancedBufferAttribute)}getHash(e){if(0===this.bufferStride&&0===this.bufferOffset){let t=e.globalCache.getData(this.value);return void 0===t&&(t={node:this},e.globalCache.setData(this.value,t)),t.node.uuid}return this.uuid}getNodeType(e){return null===this.bufferType&&(this.bufferType=e.getTypeFromAttribute(this.attribute)),this.bufferType}setup(e){if(null!==this.attribute)return;const t=this.getNodeType(e),n=this.value,r=e.getTypeLength(t),i=this.bufferStride||r,s=this.bufferOffset,a=!0===n.isInterleavedBuffer?n:new Di(n,i),o=new Ui(a,r,s);a.setUsage(this.usage),this.attribute=o,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){const t=this.getNodeType(e),n=e.getBufferAttributeFromNode(this,t),r=e.getPropertyName(n);let i=null;if("vertex"===e.shaderStage||"compute"===e.shaderStage)this.name=r,i=r;else{i=Z_(this).build(e,t)}return i}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}}const hv=(e,t=null,n=0,r=0)=>Kf(new cv(e,t,n,r)),dv=(e,t=null,n=0,r=0)=>hv(e,t,n,r).setInstanced(!0),pv=(e,t=null,n=0,r=0)=>((e,t=null,n=0,r=0)=>hv(e,t,n,r).setUsage(_t))(e,t,n,r).setInstanced(!0);Mf("toAttribute",e=>hv(e.value));class fv extends uf{static get type(){return"ComputeNode"}constructor(e,t,n=[64]){super("void"),this.isComputeNode=!0,this.computeNode=e,this.count=t,this.workgroupSize=n,this.dispatchCount=0,this.version=1,this.name="",this.updateBeforeType=Jp,this.onInitFunction=null,this.updateDispatchCount()}dispose(){this.dispatchEvent({type:"dispose"})}label(e){return this.name=e,this}updateDispatchCount(){const{count:e,workgroupSize:t}=this;let n=t[0];for(let e=1;e<t.length;e++)n*=t[e];this.dispatchCount=Math.ceil(e/n)}onInit(e){return this.onInitFunction=e,this}updateBefore({renderer:e}){e.compute(this)}setup(e){const t=this.computeNode.build(e);if(t){e.getNodeProperties(this).outputComputeNode=t.outputNode,t.outputNode=null}return t}generate(e,t){const{shaderStage:n}=e;if("compute"===n){const t=this.computeNode.build(e,"void");""!==t&&e.addLineFlowCode(t,this)}else{const n=e.getNodeProperties(this).outputComputeNode;if(n)return n.build(e,t)}}}Mf("compute",(e,t,n)=>Kf(new fv(Kf(e),t,n)));class mv extends uf{static get type(){return"CacheNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isCacheNode=!0}getNodeType(e){const t=e.getCache(),n=e.getCacheFromNode(this,this.parent);e.setCache(n);const r=this.node.getNodeType(e);return e.setCache(t),r}build(e,...t){const n=e.getCache(),r=e.getCacheFromNode(this,this.parent);e.setCache(r);const i=this.node.build(e,...t);return e.setCache(n),i}}const gv=(e,t)=>Kf(new mv(Kf(e),t));Mf("cache",gv);class _v extends uf{static get type(){return"BypassNode"}constructor(e,t){super(),this.isBypassNode=!0,this.outputNode=e,this.callNode=t}getNodeType(e){return this.outputNode.getNodeType(e)}generate(e){const t=this.callNode.build(e,"void");return""!==t&&e.addLineFlowCode(t,this),this.outputNode.build(e)}}Mf("bypass",Jf(_v).setParameterLength(2));class vv extends uf{static get type(){return"RemapNode"}constructor(e,t,n,r=lm(0),i=lm(1)){super(),this.node=e,this.inLowNode=t,this.inHighNode=n,this.outLowNode=r,this.outHighNode=i,this.doClamp=!0}setup(){const{node:e,inLowNode:t,inHighNode:n,outLowNode:r,outHighNode:i,doClamp:s}=this;let a=e.sub(t).div(n.sub(t));return!0===s&&(a=a.clamp()),a.mul(i.sub(r)).add(r)}}const yv=Jf(vv,null,null,{doClamp:!1}).setParameterLength(3,5),xv=Jf(vv).setParameterLength(3,5);Mf("remap",yv),Mf("remapClamp",xv);class bv extends uf{static get type(){return"ExpressionNode"}constructor(e="",t="void"){super(t),this.snippet=e}generate(e,t){const n=this.getNodeType(e),r=this.snippet;if("void"!==n)return e.format(r,n,t);e.addLineFlowCode(r,this)}}const Tv=Jf(bv).setParameterLength(1,2);Mf("discard",e=>(e?j_(e,Tv("discard")):Tv("discard")).toStack());class Sv extends df{static get type(){return"RenderOutputNode"}constructor(e,t,n){super("vec4"),this.colorNode=e,this.toneMapping=t,this.outputColorSpace=n,this.isRenderOutputNode=!0}setup({context:e}){let t=this.colorNode||e.color;const n=(null!==this.toneMapping?this.toneMapping:e.toneMapping)||0,r=(null!==this.outputColorSpace?this.outputColorSpace:e.outputColorSpace)||nt;return 0!==n&&(t=t.toneMapping(n)),r!==nt&&r!==$t.workingColorSpace&&(t=t.workingToColorSpace(r)),t}}Mf("renderOutput",(e,t=null,n=null)=>Kf(new Sv(Kf(e),t,n)));class Mv extends df{static get type(){return"DebugNode"}constructor(e,t=null){super(),this.node=e,this.callback=t}getNodeType(e){return this.node.getNodeType(e)}setup(e){return this.node.build(e)}analyze(e){return this.node.build(e)}generate(e){const t=this.callback,n=this.node.build(e),r="--- TSL debug - "+e.shaderStage+" shader ---",i="-".repeat(r.length);let s="";return s+="// #"+r+"#\n",s+=e.flow.code.replace(/^\t/gm,"")+"\n",s+="/* ... */ "+n+" /* ... */\n",s+="// #"+i+"#\n",null!==t?t(e,s):console.log(s),n}}Mf("debug",(e,t=null)=>Kf(new Mv(Kf(e),t)));class wv extends uf{static get type(){return"AttributeNode"}constructor(e,t=null){super(t),this.global=!0,this._attributeName=e}getHash(e){return this.getAttributeName(e)}getNodeType(e){let t=this.nodeType;if(null===t){const n=this.getAttributeName(e);if(e.hasGeometryAttribute(n)){const r=e.geometry.getAttribute(n);t=e.getTypeFromAttribute(r)}else t="float"}return t}setAttributeName(e){return this._attributeName=e,this}getAttributeName(){return this._attributeName}generate(e){const t=this.getAttributeName(e),n=this.getNodeType(e);if(!0===e.hasGeometryAttribute(t)){const r=e.geometry.getAttribute(t),i=e.getTypeFromAttribute(r),s=e.getAttribute(t,i);if("vertex"===e.shaderStage)return e.format(s.name,i,n);return Z_(this).build(e,n)}return console.warn(`AttributeNode: Vertex attribute "${t}" not found on geometry.`),e.generateConst(n)}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 Ev=(e,t=null)=>Kf(new wv(e,t)),Av=(e=0)=>Ev("uv"+(e>0?e:""),"vec2");class Rv extends uf{static get type(){return"TextureSizeNode"}constructor(e,t=null){super("uvec2"),this.isTextureSizeNode=!0,this.textureNode=e,this.levelNode=t}generate(e,t){const n=this.textureNode.build(e,"property"),r=null===this.levelNode?"0":this.levelNode.build(e,"int");return e.format(`${e.getMethod("textureDimensions")}( ${n}, ${r} )`,this.getNodeType(e),t)}}const Cv=Jf(Rv).setParameterLength(1,2);class Nv extends ug{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=Qp}get textureNode(){return this._textureNode}get texture(){return this._textureNode.value}update(){const e=this.texture,t=e.images,n=t&&t.length>0?t[0]&&t[0].image||t[0]:e.image;if(n&&void 0!==n.width){const{width:e,height:t}=n;this.value=Math.log2(Math.max(e,t))}}}const Pv=Jf(Nv).setParameterLength(1),Lv=new sn;class Dv extends ug{static get type(){return"TextureNode"}constructor(e=Lv,t=null,n=null,r=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=n,this.biasNode=r,this.compareNode=null,this.depthNode=null,this.gradNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=Kp,this.referenceNode=null,this._value=e,this._matrixUniform=null,this.setUpdateMatrix(null===t)}set value(e){this.referenceNode?this.referenceNode.value=e:this._value=e}get value(){return this.referenceNode?this.referenceNode.value:this._value}getUniformHash(){return this.value.uuid}getNodeType(){return!0===this.value.isDepthTexture?"float":this.value.type===oe?"uvec4":this.value.type===ae?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return Av(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return null===this._matrixUniform&&(this._matrixUniform=cg(this.value.matrix)),this._matrixUniform.mul(gm(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this.updateType=e?Jp:Kp,this}setupUV(e,t){const n=this.value;return e.isFlipY()&&(n.image instanceof ImageBitmap&&!0===n.flipY||!0===n.isRenderTargetTexture||!0===n.isFramebufferTexture||!0===n.isDepthTexture)&&(t=this.sampler?t.flipY():t.setY(um(Cv(this,this.levelNode).y).sub(t.y).sub(1))),t}setup(e){const t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;const n=this.value;if(!n||!0!==n.isTexture)throw new Error("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().");let r=this.uvNode;null!==r&&!0!==e.context.forceUVContext||!e.context.getUV||(r=e.context.getUV(this,e)),r||(r=this.getDefaultUV()),!0===this.updateMatrix&&(r=this.getTransformedUV(r)),r=this.setupUV(e,r);let i=this.levelNode;null===i&&e.context.getTextureLevel&&(i=e.context.getTextureLevel(this)),t.uvNode=r,t.levelNode=i,t.biasNode=this.biasNode,t.compareNode=this.compareNode,t.gradNode=this.gradNode,t.depthNode=this.depthNode}generateUV(e,t){return t.build(e,!0===this.sampler?"vec2":"ivec2")}generateSnippet(e,t,n,r,i,s,a,o){const l=this.value;let u;return u=r?e.generateTextureLevel(l,t,n,r,s):i?e.generateTextureBias(l,t,n,i,s):o?e.generateTextureGrad(l,t,n,o,s):a?e.generateTextureCompare(l,t,n,a,s):!1===this.sampler?e.generateTextureLoad(l,t,n,s):e.generateTexture(l,t,n,s),u}generate(e,t){const n=this.value,r=e.getNodeProperties(this),i=super.generate(e,"property");if(/^sampler/.test(t))return i+"_sampler";if(e.isReference(t))return i;{const s=e.getDataFromNode(this);let a=s.propertyName;if(void 0===a){const{uvNode:t,levelNode:n,biasNode:o,compareNode:l,depthNode:u,gradNode:c}=r,h=this.generateUV(e,t),d=n?n.build(e,"float"):null,p=o?o.build(e,"float"):null,f=u?u.build(e,"int"):null,m=l?l.build(e,"float"):null,g=c?[c[0].build(e,"vec2"),c[1].build(e,"vec2")]:null,_=e.getVarFromNode(this);a=e.getPropertyName(_);const v=this.generateSnippet(e,i,h,d,p,f,m,g);e.addLineFlowCode(`${a} = ${v}`,this),s.snippet=v,s.propertyName=a}let o=a;const l=this.getNodeType(e);return e.needsToWorkingColorSpace(n)&&(o=rv(Tv(o,l),n.colorSpace).setup(e).build(e,l)),e.format(o,l,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}uv(e){return console.warn("THREE.TextureNode: .uv() has been renamed. Use .sample() instead."),this.sample(e)}sample(e){const t=this.clone();return t.uvNode=Kf(e),t.referenceNode=this.getSelf(),Kf(t)}blur(e){const t=this.clone();t.biasNode=Kf(e).mul(Pv(t)),t.referenceNode=this.getSelf();const n=t.value;return!1===t.generateMipmaps&&(n&&!1===n.generateMipmaps||n.minFilter===K||n.magFilter===K)&&(console.warn("THREE.TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture."),t.biasNode=null),Kf(t)}level(e){const t=this.clone();return t.levelNode=Kf(e),t.referenceNode=this.getSelf(),Kf(t)}size(e){return Cv(this,e)}bias(e){const t=this.clone();return t.biasNode=Kf(e),t.referenceNode=this.getSelf(),Kf(t)}compare(e){const t=this.clone();return t.compareNode=Kf(e),t.referenceNode=this.getSelf(),Kf(t)}grad(e,t){const n=this.clone();return n.gradNode=[Kf(e),Kf(t)],n.referenceNode=this.getSelf(),Kf(n)}depth(e){const t=this.clone();return t.depthNode=Kf(e),t.referenceNode=this.getSelf(),Kf(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()}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}}const Iv=Jf(Dv).setParameterLength(1,4).setName("texture"),Uv=(e=Lv,t=null,n=null,r=null)=>{let i;return e&&!0===e.isTextureNode?(i=Kf(e.clone()),i.referenceNode=e.getSelf(),null!==t&&(i.uvNode=Kf(t)),null!==n&&(i.levelNode=Kf(n)),null!==r&&(i.biasNode=Kf(r))):i=Iv(e,t,n,r),i},Ov=(...e)=>Uv(...e).setSampler(!1);class Fv extends ug{static get type(){return"BufferNode"}constructor(e,t,n=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=n}getElementType(e){return this.getNodeType(e)}getInputType(){return"buffer"}}const Bv=(e,t,n)=>Kf(new Fv(e,t,n));class kv extends cf{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),n=this.getNodeType(),r=this.node.getPaddedType();return e.format(t,r,n)}}class zv extends Fv{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=null===t?Xp(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=Zp,this.isArrayBufferNode=!0}getNodeType(){return this.paddedType}getElementType(){return this.elementType}getPaddedType(){const e=this.elementType;let t="vec4";return"mat2"===e?t="mat2":!0===/mat/.test(e)?t="mat4":"i"===e.charAt(0)?t="ivec4":"u"===e.charAt(0)&&(t="uvec4"),t}update(){const{array:e,value:t}=this,n=this.elementType;if("float"===n||"int"===n||"uint"===n)for(let n=0;n<e.length;n++){t[4*n]=e[n]}else if("color"===n)for(let n=0;n<e.length;n++){const r=4*n,i=e[n];t[r]=i.r,t[r+1]=i.g,t[r+2]=i.b||0}else if("mat2"===n)for(let n=0;n<e.length;n++){const r=4*n,i=e[n];t[r]=i.elements[0],t[r+1]=i.elements[1],t[r+2]=i.elements[2],t[r+3]=i.elements[3]}else if("mat3"===n)for(let n=0;n<e.length;n++){const r=16*n,i=e[n];t[r]=i.elements[0],t[r+1]=i.elements[1],t[r+2]=i.elements[2],t[r+4]=i.elements[3],t[r+5]=i.elements[4],t[r+6]=i.elements[5],t[r+8]=i.elements[6],t[r+9]=i.elements[7],t[r+10]=i.elements[8],t[r+15]=1}else if("mat4"===n)for(let n=0;n<e.length;n++){const r=16*n,i=e[n];for(let e=0;e<i.elements.length;e++)t[r+e]=i.elements[e]}else for(let n=0;n<e.length;n++){const r=4*n,i=e[n];t[r]=i.x,t[r+1]=i.y,t[r+2]=i.z||0,t[r+3]=i.w||0}}setup(e){const t=this.array.length,n=this.elementType;let r=Float32Array;const i=this.paddedType,s=e.getTypeLength(i);return"i"===n.charAt(0)&&(r=Int32Array),"u"===n.charAt(0)&&(r=Uint32Array),this.value=new r(t*s),this.bufferCount=t,this.bufferType=i,super.setup(e)}element(e){return Kf(new kv(this,Kf(e)))}}const Vv=(e,t)=>Kf(new zv(e,t));const Gv=Jf(class extends uf{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}}).setParameterLength(1),Hv=cg(0,"uint").label("u_cameraIndex").setGroup(sg("cameraIndex")).toVarying("v_cameraIndex"),jv=cg("float").label("cameraNear").setGroup(og).onRenderUpdate(({camera:e})=>e.near),Wv=cg("float").label("cameraFar").setGroup(og).onRenderUpdate(({camera:e})=>e.far),Xv=nm(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const n=[];for(const t of e.cameras)n.push(t.projectionMatrix);t=Vv(n).setGroup(og).label("cameraProjectionMatrices").element(e.isMultiViewCamera?Gv("gl_ViewID_OVR"):Hv).toVar("cameraProjectionMatrix")}else t=cg("mat4").label("cameraProjectionMatrix").setGroup(og).onRenderUpdate(({camera:e})=>e.projectionMatrix);return t}).once()(),qv=nm(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const n=[];for(const t of e.cameras)n.push(t.matrixWorldInverse);t=Vv(n).setGroup(og).label("cameraViewMatrices").element(e.isMultiViewCamera?Gv("gl_ViewID_OVR"):Hv).toVar("cameraViewMatrix")}else t=cg("mat4").label("cameraViewMatrix").setGroup(og).onRenderUpdate(({camera:e})=>e.matrixWorldInverse);return t}).once()(),$v=cg(new Ut).label("cameraPosition").setGroup(og).onRenderUpdate(({camera:e},t)=>t.value.setFromMatrixPosition(e.matrixWorld)),Yv=new Cn;class Kv extends uf{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=Jp,this.uniformNode=new ug(null)}getNodeType(){const e=this.scope;return e===Kv.WORLD_MATRIX?"mat4":e===Kv.POSITION||e===Kv.VIEW_POSITION||e===Kv.DIRECTION||e===Kv.SCALE?"vec3":e===Kv.RADIUS?"float":void 0}update(e){const t=this.object3d,n=this.uniformNode,r=this.scope;if(r===Kv.WORLD_MATRIX)n.value=t.matrixWorld;else if(r===Kv.POSITION)n.value=n.value||new Ut,n.value.setFromMatrixPosition(t.matrixWorld);else if(r===Kv.SCALE)n.value=n.value||new Ut,n.value.setFromMatrixScale(t.matrixWorld);else if(r===Kv.DIRECTION)n.value=n.value||new Ut,t.getWorldDirection(n.value);else if(r===Kv.VIEW_POSITION){const r=e.camera;n.value=n.value||new Ut,n.value.setFromMatrixPosition(t.matrixWorld),n.value.applyMatrix4(r.matrixWorldInverse)}else if(r===Kv.RADIUS){const r=e.object.geometry;null===r.boundingSphere&&r.computeBoundingSphere(),Yv.copy(r.boundingSphere).applyMatrix4(t.matrixWorld),n.value=Yv.radius}}generate(e){const t=this.scope;return t===Kv.WORLD_MATRIX?this.uniformNode.nodeType="mat4":t===Kv.POSITION||t===Kv.VIEW_POSITION||t===Kv.DIRECTION||t===Kv.SCALE?this.uniformNode.nodeType="vec3":t===Kv.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}}Kv.WORLD_MATRIX="worldMatrix",Kv.POSITION="position",Kv.SCALE="scale",Kv.VIEW_POSITION="viewPosition",Kv.DIRECTION="direction",Kv.RADIUS="radius";const Qv=Jf(Kv,Kv.POSITION).setParameterLength(1);class Zv extends Kv{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const Jv=em(Zv,Zv.WORLD_MATRIX),ey=cg(new Bt).onObjectUpdate(({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld)),ty=nm(e=>e.renderer.overrideNodes.modelViewMatrix||ny).once()().toVar("modelViewMatrix"),ny=qv.mul(Jv),ry=nm(e=>(e.context.isHighPrecisionModelViewMatrix=!0,cg("mat4").onObjectUpdate(({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld)))).once()().toVar("highpModelViewMatrix"),iy=nm(e=>{const t=e.context.isHighPrecisionModelViewMatrix;return cg("mat3").onObjectUpdate(({object:e,camera:n})=>(!0!==t&&e.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix)))}).once()().toVar("highpModelNormalViewMatrix"),sy=Ev("position","vec3"),ay=sy.toVarying("positionLocal"),oy=sy.toVarying("positionPrevious"),ly=nm(e=>Jv.mul(ay).xyz.toVarying(e.getSubBuildProperty("v_positionWorld")),"vec3").once(["POSITION"])(),uy=nm(()=>ay.transformDirection(Jv).toVarying("v_positionWorldDirection").normalize().toVar("positionWorldDirection"),"vec3").once(["POSITION"])(),cy=nm(e=>e.context.setupPositionView().toVarying("v_positionView"),"vec3").once(["POSITION"])(),hy=cy.negate().toVarying("v_positionViewDirection").normalize().toVar("positionViewDirection");class dy extends uf{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){if("fragment"!==e.shaderStage)return"true";const{renderer:t,material:n}=e;return t.coordinateSystem===yt&&1===n.side?"false":e.getFrontFacing()}}const py=lm(em(dy)).mul(2).sub(1),fy=nm(([e],{material:t})=>{const n=t.side;return 1===n?e=e.mul(-1):2===n&&(e=e.mul(py)),e}),my=Ev("normal","vec3"),gy=nm(e=>!1===e.geometry.hasAttribute("normal")?(console.warn('THREE.TSL: Vertex attribute "normal" not found on geometry.'),gm(0,1,0)):my,"vec3").once()().toVar("normalLocal"),_y=cy.dFdx().cross(cy.dFdy()).normalize().toVar("normalFlat"),vy=nm(e=>{let t;return t=!0===e.material.flatShading?_y:My(gy).toVarying("v_normalViewGeometry").normalize(),t},"vec3").once()().toVar("normalViewGeometry"),yy=nm(e=>{let t=vy.transformDirection(qv);return!0!==e.material.flatShading&&(t=t.toVarying("v_normalWorldGeometry")),t.normalize().toVar("normalWorldGeometry")},"vec3").once()(),xy=nm(({subBuildFn:e,material:t,context:n})=>{let r;return"NORMAL"===e||"VERTEX"===e?(r=vy,!0!==t.flatShading&&(r=fy(r))):r=n.setupNormal().context({getUV:null}),r},"vec3").once(["NORMAL","VERTEX"])().toVar("normalView"),by=xy.transformDirection(qv).toVar("normalWorld"),Ty=nm(({subBuildFn:e,context:t})=>{let n;return n="NORMAL"===e||"VERTEX"===e?xy:t.setupClearcoatNormal().context({getUV:null}),n},"vec3").once(["NORMAL","VERTEX"])().toVar("clearcoatNormalView"),Sy=nm(([e,t=Jv])=>{const n=wm(t),r=e.div(gm(n[0].dot(n[0]),n[1].dot(n[1]),n[2].dot(n[2])));return n.mul(r).xyz}),My=nm(([e],t)=>{const n=t.renderer.overrideNodes.modelNormalViewMatrix;if(null!==n)return n.transformDirection(e);const r=ey.mul(e);return qv.transformDirection(r)});nm(()=>(console.warn('THREE.TSL: "transformedNormalView" is deprecated. Use "normalView" instead.'),xy)).once(["NORMAL","VERTEX"])(),nm(()=>(console.warn('THREE.TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.'),by)).once(["NORMAL","VERTEX"])(),nm(()=>(console.warn('THREE.TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.'),Ty)).once(["NORMAL","VERTEX"])();const wy=new $n,Ey=new Bn,Ay=cg(0).onReference(({material:e})=>e).onObjectUpdate(({material:e})=>e.refractionRatio),Ry=cg(1).onReference(({material:e})=>e).onObjectUpdate(function({material:e,scene:t}){return e.envMap?e.envMapIntensity:t.environmentIntensity}),Cy=cg(new Bn).onReference(function(e){return e.material}).onObjectUpdate(function({material:e,scene:t}){const n=null!==t.environment&&null===e.envMap?t.environmentRotation:e.envMapRotation;return n?(wy.copy(n),Ey.makeRotationFromEuler(wy)):Ey.identity(),Ey}),Ny=hy.negate().reflect(xy),Py=hy.negate().refract(xy,Ay),Ly=Ny.transformDirection(qv).toVar("reflectVector"),Dy=Py.transformDirection(qv).toVar("reflectVector"),Iy=new Ai;class Uy extends Dv{static get type(){return"CubeTextureNode"}constructor(e,t=null,n=null,r=null){super(e,t,n,r),this.isCubeTextureNode=!0}getInputType(){return"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===G?Ly:e.mapping===H?Dy:(console.error('THREE.CubeTextureNode: Mapping "%s" not supported.',e.mapping),gm(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const n=this.value;return e.renderer.coordinateSystem!==xt&&n.isRenderTargetTexture||(t=gm(t.x.negate(),t.yz)),Cy.mul(t)}generateUV(e,t){return t.build(e,"vec3")}}const Oy=Jf(Uy).setParameterLength(1,4).setName("cubeTexture"),Fy=(e=Iy,t=null,n=null,r=null)=>{let i;return e&&!0===e.isCubeTextureNode?(i=Kf(e.clone()),i.referenceNode=e.getSelf(),null!==t&&(i.uvNode=Kf(t)),null!==n&&(i.levelNode=Kf(n)),null!==r&&(i.biasNode=Kf(r))):i=Oy(e,t,n,r),i};class By extends cf{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),n=this.referenceNode.getNodeType(),r=this.getNodeType();return e.format(t,n,r)}}class ky extends uf{static get type(){return"ReferenceNode"}constructor(e,t,n=null,r=null){super(),this.property=e,this.uniformType=t,this.object=n,this.count=r,this.properties=e.split("."),this.reference=n,this.node=null,this.group=null,this.name=null,this.updateType=Jp}element(e){return Kf(new By(this,Kf(e)))}setGroup(e){return this.group=e,this}label(e){return this.name=e,this}setNodeType(e){let t=null;t=null!==this.count?Bv(null,e,this.count):Array.isArray(this.getValueFromReference())?Vv(null,e):"texture"===e?Uv(null):"cubeTexture"===e?Fy(null):cg(null,e),null!==this.group&&t.setGroup(this.group),null!==this.name&&t.label(this.name),this.node=t.getSelf()}getNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let n=e[t[0]];for(let e=1;e<t.length;e++)n=n[t[e]];return n}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 zy=(e,t,n)=>Kf(new ky(e,t,n)),Vy=(e,t,n,r)=>Kf(new ky(e,t,r,n));class Gy extends ky{static get type(){return"MaterialReferenceNode"}constructor(e,t,n=null){super(e,t,n),this.material=n,this.isMaterialReferenceNode=!0}updateReference(e){return this.reference=null!==this.material?this.material:e.material,this.reference}}const Hy=(e,t,n=null)=>Kf(new Gy(e,t,n)),jy=Av(),Wy=cy.dFdx(),Xy=cy.dFdy(),qy=jy.dFdx(),$y=jy.dFdy(),Yy=xy,Ky=Xy.cross(Yy),Qy=Yy.cross(Wy),Zy=Ky.mul(qy.x).add(Qy.mul($y.x)),Jy=Ky.mul(qy.y).add(Qy.mul($y.y)),ex=Zy.dot(Zy).max(Jy.dot(Jy)),tx=ex.equal(0).select(0,ex.inverseSqrt()),nx=Zy.mul(tx).toVar("tangentViewFrame"),rx=Jy.mul(tx).toVar("bitangentViewFrame"),ix=nm(e=>(!1===e.geometry.hasAttribute("tangent")&&e.geometry.computeTangents(),Ev("tangent","vec4")))(),sx=ix.xyz.toVar("tangentLocal"),ax=nm(({subBuildFn:e,geometry:t,material:n})=>{let r;return r="VERTEX"===e||t.hasAttribute("tangent")?ty.mul(xm(sx,0)).xyz.toVarying("v_tangentView").normalize():nx,!0!==n.flatShading&&(r=fy(r)),r},"vec3").once(["NORMAL","VERTEX"])().toVar("tangentView"),ox=nm(([e,t],{subBuildFn:n,material:r})=>{let i=e.mul(ix.w).xyz;return"NORMAL"===n&&!0!==r.flatShading&&(i=i.toVarying(t)),i}).once(["NORMAL"]),lx=wm(ax,nm(({subBuildFn:e,geometry:t,material:n})=>{let r;return r="VERTEX"===e||t.hasAttribute("tangent")?ox(xy.cross(ax),"v_bitangentView").normalize():rx,!0!==n.flatShading&&(r=fy(r)),r},"vec3").once(["NORMAL","VERTEX"])().toVar("bitangentView"),xy).toVar("TBNViewMatrix"),ux=nm(()=>{let e=jm.cross(hy);return e=e.cross(jm).normalize(),e=O_(e,xy,Gm.mul(Lm.oneMinus()).oneMinus().pow2().pow2()).normalize(),e}).once()();class cx extends df{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=0}setup({material:e}){const{normalMapType:t,scaleNode:n}=this;let r=this.node.mul(2).sub(1);if(null!==n){let t=n;!0===e.flatShading&&(t=fy(t)),r=gm(r.xy.mul(t),r.z)}let i=null;return 1===t?i=My(r):0===t?i=lx.mul(r).normalize():(console.error(`THREE.NodeMaterial: Unsupported normal map type: ${t}`),i=xy),i}}const hx=Jf(cx).setParameterLength(1,2),dx=nm(({textureNode:e,bumpScale:t})=>{const n=t=>e.cache().context({getUV:e=>t(e.uvNode||Av()),forceUVContext:!0}),r=lm(n(e=>e));return dm(lm(n(e=>e.add(e.dFdx()))).sub(r),lm(n(e=>e.add(e.dFdy()))).sub(r)).mul(t)}),px=nm(e=>{const{surf_pos:t,surf_norm:n,dHdxy:r}=e,i=t.dFdx().normalize(),s=n,a=t.dFdy().normalize().cross(s),o=s.cross(i),l=i.dot(a).mul(py),u=l.sign().mul(r.x.mul(a).add(r.y.mul(o)));return l.abs().mul(n).sub(u).normalize()});class fx extends df{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=dx({textureNode:this.textureNode,bumpScale:e});return px({surf_pos:cy,surf_norm:xy,dHdxy:t})}}const mx=Jf(fx).setParameterLength(1,2),gx=new Map;class _x extends uf{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let n=gx.get(e);return void 0===n&&(n=Hy(e,t),gx.set(e,n)),n}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,n=this.scope;let r=null;if(n===_x.COLOR){const e=void 0!==t.color?this.getColor(n):gm();r=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(n===_x.OPACITY){const e=this.getFloat(n);r=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(n===_x.SPECULAR_STRENGTH)r=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture("specular").r:lm(1);else if(n===_x.SPECULAR_INTENSITY){const e=this.getFloat(n);r=t.specularIntensityMap&&!0===t.specularIntensityMap.isTexture?e.mul(this.getTexture(n).a):e}else if(n===_x.SPECULAR_COLOR){const e=this.getColor(n);r=t.specularColorMap&&!0===t.specularColorMap.isTexture?e.mul(this.getTexture(n).rgb):e}else if(n===_x.ROUGHNESS){const e=this.getFloat(n);r=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(n).g):e}else if(n===_x.METALNESS){const e=this.getFloat(n);r=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(n).b):e}else if(n===_x.EMISSIVE){const e=this.getFloat("emissiveIntensity"),i=this.getColor(n).mul(e);r=t.emissiveMap&&!0===t.emissiveMap.isTexture?i.mul(this.getTexture(n)):i}else if(n===_x.NORMAL)t.normalMap?(r=hx(this.getTexture("normal"),this.getCache("normalScale","vec2")),r.normalMapType=t.normalMapType):r=t.bumpMap?mx(this.getTexture("bump").r,this.getFloat("bumpScale")):xy;else if(n===_x.CLEARCOAT){const e=this.getFloat(n);r=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(n).r):e}else if(n===_x.CLEARCOAT_ROUGHNESS){const e=this.getFloat(n);r=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(n).r):e}else if(n===_x.CLEARCOAT_NORMAL)r=t.clearcoatNormalMap?hx(this.getTexture(n),this.getCache(n+"Scale","vec2")):xy;else if(n===_x.SHEEN){const e=this.getColor("sheenColor").mul(this.getFloat("sheen"));r=t.sheenColorMap&&!0===t.sheenColorMap.isTexture?e.mul(this.getTexture("sheenColor").rgb):e}else if(n===_x.SHEEN_ROUGHNESS){const e=this.getFloat(n);r=t.sheenRoughnessMap&&!0===t.sheenRoughnessMap.isTexture?e.mul(this.getTexture(n).a):e,r=r.clamp(.07,1)}else if(n===_x.ANISOTROPY)if(t.anisotropyMap&&!0===t.anisotropyMap.isTexture){const e=this.getTexture(n);r=Mm(eb.x,eb.y,eb.y.negate(),eb.x).mul(e.rg.mul(2).sub(dm(1)).normalize().mul(e.b))}else r=eb;else if(n===_x.IRIDESCENCE_THICKNESS){const e=zy("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const i=zy("0","float",t.iridescenceThicknessRange);r=e.sub(i).mul(this.getTexture(n).g).add(i)}else r=e}else if(n===_x.TRANSMISSION){const e=this.getFloat(n);r=t.transmissionMap?e.mul(this.getTexture(n).r):e}else if(n===_x.THICKNESS){const e=this.getFloat(n);r=t.thicknessMap?e.mul(this.getTexture(n).g):e}else if(n===_x.IOR)r=this.getFloat(n);else if(n===_x.LIGHT_MAP)r=this.getTexture(n).rgb.mul(this.getFloat("lightMapIntensity"));else if(n===_x.AO)r=this.getTexture(n).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1);else if(n===_x.LINE_DASH_OFFSET)r=t.dashOffset?this.getFloat(n):lm(0);else{const t=this.getNodeType(e);r=this.getCache(n,t)}return r}}_x.ALPHA_TEST="alphaTest",_x.COLOR="color",_x.OPACITY="opacity",_x.SHININESS="shininess",_x.SPECULAR="specular",_x.SPECULAR_STRENGTH="specularStrength",_x.SPECULAR_INTENSITY="specularIntensity",_x.SPECULAR_COLOR="specularColor",_x.REFLECTIVITY="reflectivity",_x.ROUGHNESS="roughness",_x.METALNESS="metalness",_x.NORMAL="normal",_x.CLEARCOAT="clearcoat",_x.CLEARCOAT_ROUGHNESS="clearcoatRoughness",_x.CLEARCOAT_NORMAL="clearcoatNormal",_x.EMISSIVE="emissive",_x.ROTATION="rotation",_x.SHEEN="sheen",_x.SHEEN_ROUGHNESS="sheenRoughness",_x.ANISOTROPY="anisotropy",_x.IRIDESCENCE="iridescence",_x.IRIDESCENCE_IOR="iridescenceIOR",_x.IRIDESCENCE_THICKNESS="iridescenceThickness",_x.IOR="ior",_x.TRANSMISSION="transmission",_x.THICKNESS="thickness",_x.ATTENUATION_DISTANCE="attenuationDistance",_x.ATTENUATION_COLOR="attenuationColor",_x.LINE_SCALE="scale",_x.LINE_DASH_SIZE="dashSize",_x.LINE_GAP_SIZE="gapSize",_x.LINE_WIDTH="linewidth",_x.LINE_DASH_OFFSET="dashOffset",_x.POINT_SIZE="size",_x.DISPERSION="dispersion",_x.LIGHT_MAP="light",_x.AO="ao";const vx=em(_x,_x.ALPHA_TEST),yx=em(_x,_x.COLOR),xx=em(_x,_x.SHININESS),bx=em(_x,_x.EMISSIVE),Tx=em(_x,_x.OPACITY),Sx=em(_x,_x.SPECULAR),Mx=em(_x,_x.SPECULAR_INTENSITY),wx=em(_x,_x.SPECULAR_COLOR),Ex=em(_x,_x.SPECULAR_STRENGTH),Ax=em(_x,_x.REFLECTIVITY),Rx=em(_x,_x.ROUGHNESS),Cx=em(_x,_x.METALNESS),Nx=em(_x,_x.NORMAL),Px=em(_x,_x.CLEARCOAT),Lx=em(_x,_x.CLEARCOAT_ROUGHNESS),Dx=em(_x,_x.CLEARCOAT_NORMAL),Ix=em(_x,_x.ROTATION),Ux=em(_x,_x.SHEEN),Ox=em(_x,_x.SHEEN_ROUGHNESS),Fx=em(_x,_x.ANISOTROPY),Bx=em(_x,_x.IRIDESCENCE),kx=em(_x,_x.IRIDESCENCE_IOR),zx=em(_x,_x.IRIDESCENCE_THICKNESS),Vx=em(_x,_x.TRANSMISSION),Gx=em(_x,_x.THICKNESS),Hx=em(_x,_x.IOR),jx=em(_x,_x.ATTENUATION_DISTANCE),Wx=em(_x,_x.ATTENUATION_COLOR),Xx=em(_x,_x.LINE_SCALE),qx=em(_x,_x.LINE_DASH_SIZE),$x=em(_x,_x.LINE_GAP_SIZE);_x.LINE_WIDTH;const Yx=em(_x,_x.LINE_DASH_OFFSET),Kx=em(_x,_x.POINT_SIZE),Qx=em(_x,_x.DISPERSION),Zx=em(_x,_x.LIGHT_MAP),Jx=em(_x,_x.AO),eb=cg(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))}),tb=nm(e=>e.context.setupModelViewProjection(),"vec4").once()().toVarying("v_modelViewProjection");class nb extends uf{static get type(){return"IndexNode"}constructor(e){super("uint"),this.scope=e,this.isIndexNode=!0}generate(e){const t=this.getNodeType(e),n=this.scope;let r,i;if(n===nb.VERTEX)r=e.getVertexIndex();else if(n===nb.INSTANCE)r=e.getInstanceIndex();else if(n===nb.DRAW)r=e.getDrawIndex();else if(n===nb.INVOCATION_LOCAL)r=e.getInvocationLocalIndex();else if(n===nb.INVOCATION_SUBGROUP)r=e.getInvocationSubgroupIndex();else{if(n!==nb.SUBGROUP)throw new Error("THREE.IndexNode: Unknown scope: "+n);r=e.getSubgroupIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)i=r;else{i=Z_(this).build(e,t)}return i}}nb.VERTEX="vertex",nb.INSTANCE="instance",nb.SUBGROUP="subgroup",nb.INVOCATION_LOCAL="invocationLocal",nb.INVOCATION_SUBGROUP="invocationSubgroup",nb.DRAW="draw";const rb=em(nb,nb.VERTEX),ib=em(nb,nb.INSTANCE);nb.SUBGROUP,nb.INVOCATION_SUBGROUP,nb.INVOCATION_LOCAL;const sb=em(nb,nb.DRAW);class ab extends uf{static get type(){return"InstanceNode"}constructor(e,t,n=null){super("void"),this.count=e,this.instanceMatrix=t,this.instanceColor=n,this.instanceMatrixNode=null,this.instanceColorNode=null,this.updateType=Qp,this.buffer=null,this.bufferColor=null}setup(e){const{count:t,instanceMatrix:n,instanceColor:r}=this;let{instanceMatrixNode:i,instanceColorNode:s}=this;if(null===i){if(t<=1e3)i=Bv(n.array,"mat4",Math.max(t,1)).element(ib);else{const e=new ha(n.array,16,1);this.buffer=e;const t=n.usage===_t?pv:dv,r=[t(e,"vec4",16,0),t(e,"vec4",16,4),t(e,"vec4",16,8),t(e,"vec4",16,12)];i=Em(...r)}this.instanceMatrixNode=i}if(r&&null===s){const e=new Bi(r.array,3),t=r.usage===_t?pv:dv;this.bufferColor=e,s=gm(t(e,"vec3",3,0)),this.instanceColorNode=s}const a=i.mul(ay).xyz;if(ay.assign(a),e.hasGeometryAttribute("normal")){const e=Sy(gy,i);gy.assign(e)}null!==this.instanceColorNode&&Cm("vec3","vInstanceColor").assign(this.instanceColorNode)}update(){this.instanceMatrix.usage!==_t&&null!==this.buffer&&this.instanceMatrix.version!==this.buffer.version&&(this.buffer.version=this.instanceMatrix.version),this.instanceColor&&this.instanceColor.usage!==_t&&null!==this.bufferColor&&this.instanceColor.version!==this.bufferColor.version&&(this.bufferColor.version=this.instanceColor.version)}}class ob extends ab{static get type(){return"InstancedMeshNode"}constructor(e){const{count:t,instanceMatrix:n,instanceColor:r}=e;super(t,n,r),this.instancedMesh=e}}const lb=Jf(ob).setParameterLength(1);class ub extends uf{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=ib:this.batchingIdNode=sb);const t=nm(([e])=>{const t=um(Cv(Ov(this.batchMesh._indirectTexture),0).x),n=um(e).mod(t),r=um(e).div(t);return Ov(this.batchMesh._indirectTexture,pm(n,r)).x}).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]}),n=t(um(this.batchingIdNode)),r=this.batchMesh._matricesTexture,i=um(Cv(Ov(r),0).x),s=lm(n).mul(4).toInt().toVar(),a=s.mod(i),o=s.div(i),l=Em(Ov(r,pm(a,o)),Ov(r,pm(a.add(1),o)),Ov(r,pm(a.add(2),o)),Ov(r,pm(a.add(3),o))),u=this.batchMesh._colorsTexture;if(null!==u){const e=nm(([e])=>{const t=um(Cv(Ov(u),0).x),n=e,r=n.mod(t),i=n.div(t);return Ov(u,pm(r,i)).rgb}).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]}),t=e(n);Cm("vec3","vBatchColor").assign(t)}const c=wm(l);ay.assign(l.mul(ay));const h=gy.div(gm(c[0].dot(c[0]),c[1].dot(c[1]),c[2].dot(c[2]))),d=c.mul(h).xyz;gy.assign(d),e.hasGeometryAttribute("tangent")&&sx.mulAssign(c)}}const cb=Jf(ub).setParameterLength(1),hb=new WeakMap;class db extends uf{static get type(){return"SkinningNode"}constructor(e){super("void"),this.skinnedMesh=e,this.updateType=Jp,this.skinIndexNode=Ev("skinIndex","uvec4"),this.skinWeightNode=Ev("skinWeight","vec4"),this.bindMatrixNode=zy("bindMatrix","mat4"),this.bindMatrixInverseNode=zy("bindMatrixInverse","mat4"),this.boneMatricesNode=Vy("skeleton.boneMatrices","mat4",e.skeleton.bones.length),this.positionNode=ay,this.toPositionNode=ay,this.previousBoneMatricesNode=null}getSkinnedPosition(e=this.boneMatricesNode,t=this.positionNode){const{skinIndexNode:n,skinWeightNode:r,bindMatrixNode:i,bindMatrixInverseNode:s}=this,a=e.element(n.x),o=e.element(n.y),l=e.element(n.z),u=e.element(n.w),c=i.mul(t),h=gg(a.mul(r.x).mul(c),o.mul(r.y).mul(c),l.mul(r.z).mul(c),u.mul(r.w).mul(c));return s.mul(h).xyz}getSkinnedNormal(e=this.boneMatricesNode,t=gy){const{skinIndexNode:n,skinWeightNode:r,bindMatrixNode:i,bindMatrixInverseNode:s}=this,a=e.element(n.x),o=e.element(n.y),l=e.element(n.z),u=e.element(n.w);let c=gg(r.x.mul(a),r.y.mul(o),r.z.mul(l),r.w.mul(u));return c=s.mul(c).mul(i),c.transformDirection(t).xyz}getPreviousSkinnedPosition(e){const t=e.object;return null===this.previousBoneMatricesNode&&(t.skeleton.previousBoneMatrices=new Float32Array(t.skeleton.boneMatrices),this.previousBoneMatricesNode=Vy("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,oy)}needsPreviousBoneMatrices(e){const t=e.renderer.getMRT();return t&&t.has("velocity")||!0===$p(e.object).useVelocity}setup(e){this.needsPreviousBoneMatrices(e)&&oy.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(this.toPositionNode&&this.toPositionNode.assign(t),e.hasGeometryAttribute("normal")){const t=this.getSkinnedNormal();gy.assign(t),e.hasGeometryAttribute("tangent")&&sx.assign(t)}return t}generate(e,t){if("void"!==t)return super.generate(e,t)}update(e){const t=e.object&&e.object.skeleton?e.object.skeleton:this.skinnedMesh.skeleton;hb.get(t)!==e.frameId&&(hb.set(t,e.frameId),null!==this.previousBoneMatricesNode&&t.previousBoneMatrices.set(t.boneMatrices),t.update())}}class pb extends uf{static get type(){return"LoopNode"}constructor(e=[]){super(),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 n={};for(let e=0,t=this.params.length-1;e<t;e++){const t=this.params[e],r=!0!==t.isNode&&t.name||this.getVarName(e),i=!0!==t.isNode&&t.type||"int";n[r]=Tv(r,i)}const r=e.addStack();t.returnsNode=this.params[this.params.length-1](n,e),t.stackNode=r;const i=this.params[0];return!0!==i.isNode&&"function"==typeof i.update&&(t.updateNode=nm(this.params[0].update)(n)),e.removeStack(),t}getNodeType(e){const{returnsNode:t}=this.getProperties(e);return t?t.getNodeType(e):"void"}setup(e){this.getProperties(e)}generate(e){const t=this.getProperties(e),n=this.params,r=t.stackNode;for(let r=0,i=n.length-1;r<i;r++){const i=n[r];let s,a=!1,o=null,l=null,u=null,c=null,h=null,d=null;if(i.isNode?"bool"===i.getNodeType(e)?(a=!0,c="bool",l=i.build(e,c)):(c="int",u=this.getVarName(r),o="0",l=i.build(e,c),h="<"):(c=i.type||"int",u=i.name||this.getVarName(r),o=i.start,l=i.end,h=i.condition,d=i.update,"number"==typeof o?o=e.generateConst(c,o):o&&o.isNode&&(o=o.build(e,c)),"number"==typeof l?l=e.generateConst(c,l):l&&l.isNode&&(l=l.build(e,c)),void 0!==o&&void 0===l?(o+=" - 1",l="0",h=">="):void 0!==l&&void 0===o&&(o="0",h="<"),void 0===h&&(h=Number(o)>Number(l)?">=":"<")),a)s=`while ( ${l} )`;else{const n={start:o,end:l},r=n.start,i=n.end;let a;const p=()=>h.includes("<")?"+=":"-=";if(null!=d)switch(typeof d){case"function":a=e.flowStagesNode(t.updateNode,"void").code.replace(/\t|;/g,"");break;case"number":a=u+" "+p()+" "+e.generateConst(c,d);break;case"string":a=u+" "+d;break;default:d.isNode?a=u+" "+p()+" "+d.build(e):(console.error("THREE.TSL: 'Loop( { update: ... } )' is not a function, string or number."),a="break /* invalid update */")}else d="int"===c||"uint"===c?h.includes("<")?"++":"--":p()+" 1.",a=u+" "+d;s=`for ( ${e.getVar(c,u)+" = "+r}; ${u+" "+h+" "+i}; ${a} )`}e.addFlowCode((0===r?"\n":"")+e.tab+s+" {\n\n").addFlowTab()}const i=r.build(e,"void"),s=t.returnsNode?t.returnsNode.build(e):"";e.removeFlowTab().addFlowCode("\n"+e.tab+i);for(let t=0,n=this.params.length-1;t<n;t++)e.addFlowCode((0===t?"":e.tab)+"}\n\n").removeFlowTab();return e.addFlowTab(),s}}const fb=(...e)=>Kf(new pb(Zf(e,"int"))).toStack(),mb=new WeakMap,gb=new an,_b=nm(({bufferMap:e,influence:t,stride:n,width:r,depth:i,offset:s})=>{const a=um(rb).mul(n).add(s),o=a.div(r),l=a.sub(o.mul(r));return Ov(e,pm(l,o)).depth(i).xyz.mul(t)});class vb extends uf{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=cg(1),this.updateType=Jp}setup(e){const{geometry:t}=e,n=void 0!==t.morphAttributes.position,r=t.hasAttribute("normal")&&void 0!==t.morphAttributes.normal,i=t.morphAttributes.position||t.morphAttributes.normal||t.morphAttributes.color,s=void 0!==i?i.length:0,{texture:a,stride:o,size:l}=function(e){const t=void 0!==e.morphAttributes.position,n=void 0!==e.morphAttributes.normal,r=void 0!==e.morphAttributes.color,i=e.morphAttributes.position||e.morphAttributes.normal||e.morphAttributes.color,s=void 0!==i?i.length:0;let a=mb.get(e);if(void 0===a||a.count!==s){void 0!==a&&a.texture.dispose();const o=e.morphAttributes.position||[],l=e.morphAttributes.normal||[],u=e.morphAttributes.color||[];let c=0;!0===t&&(c=1),!0===n&&(c=2),!0===r&&(c=3);let h=e.attributes.position.count*c,d=1;const p=4096;h>p&&(d=Math.ceil(h/p),h=p);const f=new Float32Array(h*d*4*s),m=new un(f,h,d,s);m.type=le,m.needsUpdate=!0;const g=4*c;for(let v=0;v<s;v++){const y=o[v],x=l[v],b=u[v],T=h*d*4*v;for(let S=0;S<y.count;S++){const M=S*g;!0===t&&(gb.fromBufferAttribute(y,S),f[T+M+0]=gb.x,f[T+M+1]=gb.y,f[T+M+2]=gb.z,f[T+M+3]=0),!0===n&&(gb.fromBufferAttribute(x,S),f[T+M+4]=gb.x,f[T+M+5]=gb.y,f[T+M+6]=gb.z,f[T+M+7]=0),!0===r&&(gb.fromBufferAttribute(b,S),f[T+M+8]=gb.x,f[T+M+9]=gb.y,f[T+M+10]=gb.z,f[T+M+11]=4===b.itemSize?gb.w:1)}}function _(){m.dispose(),mb.delete(e),e.removeEventListener("dispose",_)}a={count:s,texture:m,stride:c,size:new Dt(h,d)},mb.set(e,a),e.addEventListener("dispose",_)}return a}(t);!0===n&&ay.mulAssign(this.morphBaseInfluence),!0===r&&gy.mulAssign(this.morphBaseInfluence);const u=um(l.width);fb(s,({i:e})=>{const t=lm(0).toVar();this.mesh.count>1&&null!==this.mesh.morphTexture&&void 0!==this.mesh.morphTexture?t.assign(Ov(this.mesh.morphTexture,pm(um(e).add(1),um(ib))).r):t.assign(zy("morphTargetInfluences","float").element(e).toVar()),sm(t.notEqual(0),()=>{!0===n&&ay.addAssign(_b({bufferMap:a,influence:t,stride:o,width:u,depth:e,offset:um(0)})),!0===r&&gy.addAssign(_b({bufferMap:a,influence:t,stride:o,width:u,depth:e,offset:um(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 yb=Jf(vb).setParameterLength(1);class xb extends uf{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class bb extends xb{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class Tb extends W_{static get type(){return"LightingContextNode"}constructor(e,t=null,n=null,r=null){super(e),this.lightingModel=t,this.backdropNode=n,this.backdropAlphaNode=r,this._value=null}getContext(){const{backdropNode:e,backdropAlphaNode:t}=this,n={directDiffuse:gm().toVar("directDiffuse"),directSpecular:gm().toVar("directSpecular"),indirectDiffuse:gm().toVar("indirectDiffuse"),indirectSpecular:gm().toVar("indirectSpecular")};return{radiance:gm().toVar("radiance"),irradiance:gm().toVar("irradiance"),iblIrradiance:gm().toVar("iblIrradiance"),ambientOcclusion:lm(1).toVar("ambientOcclusion"),reflectedLight:n,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 Sb=Jf(Tb);class Mb extends xb{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}let wb,Eb;class Ab extends uf{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this.isViewportNode=!0}getNodeType(){return this.scope===Ab.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=Kp;return this.scope!==Ab.SIZE&&this.scope!==Ab.VIEWPORT||(e=Zp),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===Ab.VIEWPORT?null!==t?Eb.copy(t.viewport):(e.getViewport(Eb),Eb.multiplyScalar(e.getPixelRatio())):null!==t?(wb.width=t.width,wb.height=t.height):e.getDrawingBufferSize(wb)}setup(){const e=this.scope;let t=null;return t=e===Ab.SIZE?cg(wb||(wb=new Dt)):e===Ab.VIEWPORT?cg(Eb||(Eb=new an)):dm(Nb.div(Cb)),t}generate(e){if(this.scope===Ab.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const n=e.getNodeProperties(Cb).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${n}.y - ${t}.y )`}return t}return super.generate(e)}}Ab.COORDINATE="coordinate",Ab.VIEWPORT="viewport",Ab.SIZE="size",Ab.UV="uv";const Rb=em(Ab,Ab.UV),Cb=em(Ab,Ab.SIZE),Nb=em(Ab,Ab.COORDINATE),Pb=em(Ab,Ab.VIEWPORT);Pb.zw,Pb.xy;const Lb=new Dt;class Db extends Dv{static get type(){return"ViewportTextureNode"}constructor(e=Rb,t=null,n=null){null===n&&((n=new as).minFilter=te),super(n,e,t),this.generateMipmaps=!1,this.isOutputTextureNode=!0,this.updateBeforeType=Qp}updateBefore(e){const t=e.renderer;t.getDrawingBufferSize(Lb);const n=this.value;n.image.width===Lb.width&&n.image.height===Lb.height||(n.image.width=Lb.width,n.image.height=Lb.height,n.needsUpdate=!0);const r=n.generateMipmaps;n.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(n),n.generateMipmaps=r}clone(){const e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}}const Ib=Jf(Db,null,null,{generateMipmaps:!0}).setParameterLength(0,3);let Ub=null;class Ob extends Db{static get type(){return"ViewportDepthTextureNode"}constructor(e=Rb,t=null){null===Ub&&(Ub=new os),super(e,t,Ub)}}const Fb=Jf(Ob).setParameterLength(0,2);class Bb extends uf{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===Bb.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,n=this.valueNode;let r=null;if(t===Bb.DEPTH_BASE)null!==n&&(r=Hb().assign(n));else if(t===Bb.DEPTH)r=e.isPerspectiveCamera?zb(cy.z,jv,Wv):kb(cy.z,jv,Wv);else if(t===Bb.LINEAR_DEPTH)if(null!==n)if(e.isPerspectiveCamera){const e=Vb(n,jv,Wv);r=kb(e,jv,Wv)}else r=n;else r=kb(cy.z,jv,Wv);return r}}Bb.DEPTH_BASE="depthBase",Bb.DEPTH="depth",Bb.LINEAR_DEPTH="linearDepth";const kb=(e,t,n)=>e.add(t).div(t.sub(n)),zb=(e,t,n)=>t.add(e).mul(n).div(n.sub(t).mul(e)),Vb=(e,t,n)=>t.mul(n).div(n.sub(t).mul(e).sub(n)),Gb=(e,t,n)=>{t=t.max(1e-6).toVar();const r=Qg(e.negate().div(t)),i=Qg(n.div(t));return r.div(i)},Hb=Jf(Bb,Bb.DEPTH_BASE),jb=em(Bb,Bb.DEPTH);Fb(),jb.assign=e=>Hb(e);class Wb extends uf{static get type(){return"ClippingNode"}constructor(e=Wb.DEFAULT){super(),this.scope=e}setup(e){super.setup(e);const t=e.clippingContext,{intersectionPlanes:n,unionPlanes:r}=t;return this.hardwareClipping=e.material.hardwareClipping,this.scope===Wb.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(n,r):this.scope===Wb.HARDWARE?this.setupHardwareClipping(r,e):this.setupDefault(n,r)}setupAlphaToCoverage(e,t){return nm(()=>{const n=lm().toVar("distanceToPlane"),r=lm().toVar("distanceToGradient"),i=lm(1).toVar("clipOpacity"),s=t.length;if(!1===this.hardwareClipping&&s>0){const e=Vv(t);fb(s,({i:t})=>{const s=e.element(t);n.assign(cy.dot(s.xyz).negate().add(s.w)),r.assign(n.fwidth().div(2)),i.mulAssign(z_(r.negate(),r,n))})}const a=e.length;if(a>0){const t=Vv(e),s=lm(1).toVar("intersectionClipOpacity");fb(a,({i:e})=>{const i=t.element(e);n.assign(cy.dot(i.xyz).negate().add(i.w)),r.assign(n.fwidth().div(2)),s.mulAssign(z_(r.negate(),r,n).oneMinus())}),i.mulAssign(s.oneMinus())}Nm.a.mulAssign(i),Nm.a.equal(0).discard()})()}setupDefault(e,t){return nm(()=>{const n=t.length;if(!1===this.hardwareClipping&&n>0){const e=Vv(t);fb(n,({i:t})=>{const n=e.element(t);cy.dot(n.xyz).greaterThan(n.w).discard()})}const r=e.length;if(r>0){const t=Vv(e),n=hm(!0).toVar("clipped");fb(r,({i:e})=>{const r=t.element(e);n.assign(cy.dot(r.xyz).greaterThan(r.w).and(n))}),n.discard()}})()}setupHardwareClipping(e,t){const n=e.length;return t.enableHardwareClipping(n),nm(()=>{const r=Vv(e),i=Gv(t.getClipDistance());fb(n,({i:e})=>{const t=r.element(e),n=cy.dot(t.xyz).sub(t.w).negate();i.element(e).assign(n)})})()}}Wb.ALPHA_TO_COVERAGE="alphaToCoverage",Wb.DEFAULT="default",Wb.HARDWARE="hardware";const Xb=nm(([e])=>r_(vg(1e4,i_(vg(17,e.x).add(vg(.1,e.y)))).mul(gg(.1,c_(i_(vg(13,e.y).add(e.x))))))),qb=nm(([e])=>Xb(dm(Xb(e.xy),e.z))),$b=nm(([e])=>{const t=S_(d_(m_(e.xyz)),d_(g_(e.xyz))),n=lm(1).div(lm(.05).mul(t)).toVar("pixScale"),r=dm(Yg(e_(Qg(n))),Yg(t_(Qg(n)))),i=dm(qb(e_(r.x.mul(e.xyz))),qb(e_(r.y.mul(e.xyz)))),s=r_(Qg(n)),a=gg(vg(s.oneMinus(),i.x),vg(s,i.y)),o=T_(s,s.oneMinus()),l=gm(a.mul(a).div(vg(2,o).mul(_g(1,o))),a.sub(vg(.5,o)).div(_g(1,o)),_g(1,_g(1,a).mul(_g(1,a)).div(vg(2,o).mul(_g(1,o))))),u=a.lessThan(o.oneMinus()).select(a.lessThan(o).select(l.x,l.y),l.z);return F_(u,1e-6,1)}).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class Yb extends wv{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 n;return n=!0===e.hasGeometryAttribute(t)?super.generate(e):e.generateConst(this.nodeType,new an(1,1,1,1)),n}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const Kb=nm(([e])=>xm(e.rgb.mul(e.a),e.a),{color:"vec4",return:"vec4"});class Qb extends Dr{static get type(){return"NodeMaterial"}get type(){return this.constructor.type}set type(e){}constructor(){super(),this.isNodeMaterial=!0,this.fog=!0,this.lights=!1,this.hardwareClipping=!1,this.lightsNode=null,this.envNode=null,this.aoNode=null,this.colorNode=null,this.normalNode=null,this.opacityNode=null,this.backdropNode=null,this.backdropAlphaNode=null,this.alphaTestNode=null,this.maskNode=null,this.positionNode=null,this.geometryNode=null,this.depthNode=null,this.receivedShadowPositionNode=null,this.castShadowPositionNode=null,this.receivedShadowNode=null,this.castShadowNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null,Object.defineProperty(this,"shadowPositionNode",{get:()=>this.receivedShadowPositionNode,set:e=>{console.warn('THREE.NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".'),this.receivedShadowPositionNode=e}})}customProgramCacheKey(){return this.type+Gp(this)}build(e){this.setup(e)}setupObserver(e){return new Bp(e)}setup(e){e.context.setupNormal=()=>K_(this.setupNormal(e),"NORMAL","vec3"),e.context.setupPositionView=()=>this.setupPositionView(e),e.context.setupModelViewProjection=()=>this.setupModelViewProjection(e);const t=e.renderer,n=t.getRenderTarget();e.addStack();const r=K_(this.setupVertex(e),"VERTEX"),i=this.vertexNode||r;let s;e.stack.outputNode=i,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!==n?!0===n.depthBuffer&&this.setupDepth(e):!0===t.depth&&this.setupDepth(e)),null===this.fragmentNode){this.setupDiffuseColor(e),this.setupVariants(e);const r=this.setupLighting(e);null!==a&&e.stack.add(a);const i=xm(r,Nm.a).max(0);s=this.setupOutput(e,i),$m.assign(s);const o=null!==this.outputNode;if(o&&(s=this.outputNode),null!==n){const e=t.getMRT(),n=this.mrtNode;null!==e?(o&&$m.assign(s),s=e,null!==n&&(s=e.merge(n))):null!==n&&(s=n)}}else{let t=this.fragmentNode;!0!==t.isOutputStructNode&&(t=xm(t)),s=this.setupOutput(e,t)}e.stack.outputNode=s,e.addFlow("fragment",e.removeStack()),e.observer=this.setupObserver(e)}setupClipping(e){if(null===e.clippingContext)return null;const{unionPlanes:t,intersectionPlanes:n}=e.clippingContext;let r=null;if(t.length>0||n.length>0){const t=e.renderer.samples;this.alphaToCoverage&&t>1?r=Kf(new Wb(Wb.ALPHA_TO_COVERAGE)):e.stack.add(Kf(new Wb))}return r}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.add(Kf(new Wb(Wb.HARDWARE))),this.hardwareClipping=!0)}setupDepth(e){const{renderer:t,camera:n}=e;let r=this.depthNode;if(null===r){const e=t.getMRT();e&&e.has("depth")?r=e.get("depth"):!0===t.logarithmicDepthBuffer&&(r=n.isPerspectiveCamera?Gb(cy.z,jv,Wv):kb(cy.z,jv,Wv))}null!==r&&jb.assign(r).toStack()}setupPositionView(){return ty.mul(ay).xyz}setupModelViewProjection(){return Xv.mul(cy)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.vertex=e.removeStack(),tb}setupPosition(e){const{object:t,geometry:n}=e;var r;if((n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color)&&yb(t).toStack(),!0===t.isSkinnedMesh&&(r=t,Kf(new db(r))).toStack(),this.displacementMap){const e=Hy("displacementMap","texture"),t=Hy("displacementScale","float"),n=Hy("displacementBias","float");ay.addAssign(gy.normalize().mul(e.x.mul(t).add(n)))}return t.isBatchedMesh&&cb(t).toStack(),t.isInstancedMesh&&t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&lb(t).toStack(),null!==this.positionNode&&ay.assign(K_(this.positionNode,"POSITION","vec3")),ay}setupDiffuseColor({object:e,geometry:t}){null!==this.maskNode&&hm(this.maskNode).not().discard();let n=this.colorNode?xm(this.colorNode):yx;if(!0===this.vertexColors&&t.hasAttribute("color")&&(n=n.mul(((e=0)=>Kf(new Yb(e)))())),e.instanceColor){n=Cm("vec3","vInstanceColor").mul(n)}if(e.isBatchedMesh&&e._colorsTexture){n=Cm("vec3","vBatchColor").mul(n)}Nm.assign(n);const r=this.opacityNode?lm(this.opacityNode):Tx;Nm.a.assign(Nm.a.mul(r));let i=null;(null!==this.alphaTestNode||this.alphaTest>0)&&(i=null!==this.alphaTestNode?lm(this.alphaTestNode):vx,Nm.a.lessThanEqual(i).discard()),!0===this.alphaHash&&Nm.a.lessThan($b(ay)).discard();!1===this.transparent&&1===this.blending&&!1===this.alphaToCoverage?Nm.a.assign(1):null===i&&Nm.a.lessThanEqual(0).discard()}setupVariants(){}setupOutgoingLight(){return!0===this.lights?gm(0):Nm.rgb}setupNormal(){return this.normalNode?gm(this.normalNode):Nx}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?Hy("envMap","cubeTexture"):Hy("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new Mb(Zx)),t}setupLights(e){const t=[],n=this.setupEnvironment(e);n&&n.isLightingNode&&t.push(n);const r=this.setupLightMap(e);if(r&&r.isLightingNode&&t.push(r),null!==this.aoNode||e.material.aoMap){const e=null!==this.aoNode?this.aoNode:Jx;t.push(new bb(e))}let i=this.lightsNode||e.lightsNode;return t.length>0&&(i=e.renderer.lighting.createNode([...i.getLights(),...t])),i}setupLightingModel(){}setupLighting(e){const{material:t}=e,{backdropNode:n,backdropAlphaNode:r,emissiveNode:i}=this,s=!0===this.lights||null!==this.lightsNode?this.setupLights(e):null;let a=this.setupOutgoingLight(e);if(s&&s.getScope().hasLights){const t=this.setupLightingModel(e)||null;a=Sb(s,t,n,r)}else null!==n&&(a=gm(null!==r?O_(a,n,r):n));return(i&&!0===i.isNode||t.emissive&&!0===t.emissive.isColor)&&(Pm.assign(gm(i||bx)),a=a.add(Pm)),a}setupFog(e,t){const n=e.fogNode;return n&&($m.assign(t),t=xm(n)),t}setupPremultipliedAlpha(e,t){return Kb(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 n=e[t];void 0===this[t]&&(this[t]=n,n&&n.clone&&(this[t]=n.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 n=Dr.prototype.toJSON.call(this,e),r=Hp(this);n.inputNodes={};for(const{property:t,childNode:i}of r)n.inputNodes[t]=i.toJSON(e).uuid;function i(e){const t=[];for(const n in e){const r=e[n];delete r.metadata,t.push(r)}return t}if(t){const t=i(e.textures),r=i(e.images),s=i(e.nodes);t.length>0&&(n.textures=t),r.length>0&&(n.images=r),s.length>0&&(n.nodes=s)}return n}copy(e){return this.lightsNode=e.lightsNode,this.envNode=e.envNode,this.colorNode=e.colorNode,this.normalNode=e.normalNode,this.opacityNode=e.opacityNode,this.backdropNode=e.backdropNode,this.backdropAlphaNode=e.backdropAlphaNode,this.alphaTestNode=e.alphaTestNode,this.maskNode=e.maskNode,this.positionNode=e.positionNode,this.geometryNode=e.geometryNode,this.depthNode=e.depthNode,this.receivedShadowPositionNode=e.receivedShadowPositionNode,this.castShadowPositionNode=e.castShadowPositionNode,this.receivedShadowNode=e.receivedShadowNode,this.castShadowNode=e.castShadowNode,this.outputNode=e.outputNode,this.mrtNode=e.mrtNode,this.fragmentNode=e.fragmentNode,this.vertexNode=e.vertexNode,super.copy(e)}}const Zb=new Ki;class Jb extends Qb{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(Zb),this.setValues(e)}}const eT=new Os;class tT extends Qb{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(eT),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?lm(this.offsetNode):Yx,t=this.dashScaleNode?lm(this.dashScaleNode):Xx,n=this.dashSizeNode?lm(this.dashSizeNode):qx,r=this.gapSizeNode?lm(this.gapSizeNode):$x;Ym.assign(n),Km.assign(r);const i=Z_(Ev("lineDistance").mul(t));(e?i.add(e):i).mod(Ym.add(Km)).greaterThan(Ym).discard()}}const nT=new Ps;class rT extends Qb{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(nT),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?lm(this.opacityNode):Tx;Nm.assign(rv(xm(Kf(xy).mul(.5).add(.5),e),rt))}}const iT=nm(([e=uy])=>{const t=e.z.atan(e.x).mul(1/(2*Math.PI)).add(.5),n=e.y.clamp(-1,1).asin().mul(1/Math.PI).add(.5);return dm(t,n)});class sT extends Ri{constructor(e=1,t={}){super(e,t),this.isCubeRenderTarget=!0}fromEquirectangularTexture(e,t){const n=t.minFilter,r=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 i=new fi(5,5,5),s=iT(uy),a=new Qb;a.colorNode=Uv(t,s,0),a.side=1,a.blending=0;const o=new di(i,a),l=new Li;l.add(o),t.minFilter===te&&(t.minFilter=J);const u=new Ei(1,10,this),c=e.getMRT();return e.setMRT(null),u.update(e,l),e.setMRT(c),t.minFilter=n,t.currentGenerateMipmaps=r,o.geometry.dispose(),o.material.dispose(),this}}const aT=new WeakMap;class oT extends df{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=Fy(null);const t=new Ai;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=Zp}updateBefore(e){const{renderer:t,material:n}=e,r=this.envNode;if(r.isTextureNode||r.isMaterialReferenceNode){const e=r.isTextureNode?r.value:n[r.property];if(e&&e.isTexture){const n=e.mapping;if(n===j||n===W){if(aT.has(e)){const t=aT.get(e);uT(t,e.mapping),this._cubeTexture=t}else{const n=e.image;if(function(e){return null!=e&&e.height>0}(n)){const r=new sT(n.height);r.fromEquirectangularTexture(t,e),uT(r.texture,e.mapping),this._cubeTexture=r.texture,aT.set(e,r.texture),e.addEventListener("dispose",lT)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function lT(e){const t=e.target;t.removeEventListener("dispose",lT);const n=aT.get(t);void 0!==n&&(aT.delete(t),n.dispose())}function uT(e,t){t===j?e.mapping=G:t===W&&(e.mapping=H)}const cT=Jf(oT).setParameterLength(1);class hT extends xb{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=cT(this.envNode)}}class dT extends xb{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=lm(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class pT{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class fT extends pT{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,n=e.reflectedLight,r=e.irradianceLightMap;n.indirectDiffuse.assign(xm(0)),r?n.indirectDiffuse.addAssign(r):n.indirectDiffuse.addAssign(xm(1,1,1,0)),n.indirectDiffuse.mulAssign(t),n.indirectDiffuse.mulAssign(Nm.rgb)}finish(e){const{material:t,context:n}=e,r=n.outgoingLight,i=e.context.environment;if(i)switch(t.combine){case 0:r.rgb.assign(O_(r.rgb,r.rgb.mul(i.rgb),Ex.mul(Ax)));break;case 1:r.rgb.assign(O_(r.rgb,i.rgb,Ex.mul(Ax)));break;case 2:r.rgb.addAssign(i.rgb.mul(Ex.mul(Ax)));break;default:console.warn("THREE.BasicLightingModel: Unsupported .combine value:",t.combine)}}}const mT=new Ir;class gT extends Qb{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(mT),this.setValues(e)}setupNormal(){return fy(vy)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new hT(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new dT(Zx)),t}setupOutgoingLight(){return Nm.rgb}setupLightingModel(){return new fT}}const _T=nm(({f0:e,f90:t,dotVH:n})=>{const r=n.mul(-5.55473).sub(6.98316).mul(n).exp2();return e.mul(r.oneMinus()).add(t.mul(r))}),vT=nm(e=>e.diffuseColor.mul(1/Math.PI)),yT=nm(({dotNH:e})=>qm.mul(lm(.5)).add(1).mul(lm(1/Math.PI)).mul(e.pow(qm))),xT=nm(({lightDirection:e})=>{const t=e.add(hy).normalize(),n=xy.dot(t).clamp(),r=hy.dot(t).clamp(),i=_T({f0:Wm,f90:1,dotVH:r}),s=lm(.25),a=yT({dotNH:n});return i.mul(s).mul(a)});class bT extends fT{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:n}){const r=xy.dot(e).clamp().mul(t);n.directDiffuse.addAssign(r.mul(vT({diffuseColor:Nm.rgb}))),!0===this.specular&&n.directSpecular.addAssign(r.mul(xT({lightDirection:e})).mul(Ex))}indirect(e){const{ambientOcclusion:t,irradiance:n,reflectedLight:r}=e.context;r.indirectDiffuse.addAssign(n.mul(vT({diffuseColor:Nm}))),r.indirectDiffuse.mulAssign(t)}}const TT=new Ls;class ST extends Qb{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(TT),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new hT(t):null}setupLightingModel(){return new bT(!1)}}const MT=new Cs;class wT extends Qb{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(MT),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new hT(t):null}setupLightingModel(){return new bT}setupVariants(){const e=(this.shininessNode?lm(this.shininessNode):xx).max(1e-4);qm.assign(e);const t=this.specularNode||Sx;Wm.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}const ET=nm(e=>{if(!1===e.geometry.hasAttribute("normal"))return lm(0);const t=vy.dFdx().abs().max(vy.dFdy().abs());return t.x.max(t.y).max(t.z)}),AT=nm(e=>{const{roughness:t}=e,n=ET();let r=t.max(.0525);return r=r.add(n),r=r.min(1),r}),RT=nm(({alpha:e,dotNL:t,dotNV:n})=>{const r=e.pow2(),i=t.mul(r.add(r.oneMinus().mul(n.pow2())).sqrt()),s=n.mul(r.add(r.oneMinus().mul(t.pow2())).sqrt());return yg(.5,i.add(s).max(Gg))}).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),CT=nm(({alphaT:e,alphaB:t,dotTV:n,dotBV:r,dotTL:i,dotBL:s,dotNV:a,dotNL:o})=>{const l=o.mul(gm(e.mul(n),t.mul(r),a).length()),u=a.mul(gm(e.mul(i),t.mul(s),o).length());return yg(.5,l.add(u)).saturate()}).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"}]}),NT=nm(({alpha:e,dotNH:t})=>{const n=e.pow2(),r=t.pow2().mul(n.oneMinus()).oneMinus();return n.div(r.pow2()).mul(1/Math.PI)}).setLayout({name:"D_GGX",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNH",type:"float"}]}),PT=lm(1/Math.PI),LT=nm(({alphaT:e,alphaB:t,dotNH:n,dotTH:r,dotBH:i})=>{const s=e.mul(t),a=gm(t.mul(r),e.mul(i),s.mul(n)),o=a.dot(a),l=s.div(o);return PT.mul(s.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"}]}),DT=nm(({lightDirection:e,f0:t,f90:n,roughness:r,f:i,normalView:s=xy,USE_IRIDESCENCE:a,USE_ANISOTROPY:o})=>{const l=r.pow2(),u=e.add(hy).normalize(),c=s.dot(e).clamp(),h=s.dot(hy).clamp(),d=s.dot(u).clamp(),p=hy.dot(u).clamp();let f,m,g=_T({f0:t,f90:n,dotVH:p});if($f(a)&&(g=Bm.mix(g,i)),$f(o)){const t=Hm.dot(e),n=Hm.dot(hy),r=Hm.dot(u),i=jm.dot(e),s=jm.dot(hy),a=jm.dot(u);f=CT({alphaT:Vm,alphaB:l,dotTV:n,dotBV:s,dotTL:t,dotBL:i,dotNV:h,dotNL:c}),m=LT({alphaT:Vm,alphaB:l,dotNH:d,dotTH:r,dotBH:a})}else f=RT({alpha:l,dotNL:c,dotNV:h}),m=NT({alpha:l,dotNH:d});return g.mul(f).mul(m)}),IT=nm(({roughness:e,dotNV:t})=>{const n=xm(-1,-.0275,-.572,.022),r=xm(1,.0425,1.04,-.04),i=e.mul(n).add(r),s=i.x.mul(i.x).min(t.mul(-9.28).exp2()).mul(i.x).add(i.y);return dm(-1.04,1.04).mul(s).add(i.zw)}).setLayout({name:"DFGApprox",type:"vec2",inputs:[{name:"roughness",type:"float"},{name:"dotNV",type:"vec3"}]}),UT=nm(e=>{const{dotNV:t,specularColor:n,specularF90:r,roughness:i}=e,s=IT({dotNV:t,roughness:i});return n.mul(s.x).add(r.mul(s.y))}),OT=nm(({f:e,f90:t,dotVH:n})=>{const r=n.oneMinus().saturate(),i=r.mul(r),s=r.mul(i,i).clamp(0,.9999);return e.sub(gm(t).mul(s)).div(s.oneMinus())}).setLayout({name:"Schlick_to_F0",type:"vec3",inputs:[{name:"f",type:"vec3"},{name:"f90",type:"float"},{name:"dotVH",type:"float"}]}),FT=nm(({roughness:e,dotNH:t})=>{const n=e.pow2(),r=lm(1).div(n),i=t.pow2().oneMinus().max(.0078125);return lm(2).add(r).mul(i.pow(r.mul(.5))).div(2*Math.PI)}).setLayout({name:"D_Charlie",type:"float",inputs:[{name:"roughness",type:"float"},{name:"dotNH",type:"float"}]}),BT=nm(({dotNV:e,dotNL:t})=>lm(1).div(lm(4).mul(t.add(e).sub(t.mul(e))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),kT=nm(({lightDirection:e})=>{const t=e.add(hy).normalize(),n=xy.dot(e).clamp(),r=xy.dot(hy).clamp(),i=xy.dot(t).clamp(),s=FT({roughness:Fm,dotNH:i}),a=BT({dotNV:r,dotNL:n});return Om.mul(s).mul(a)}),zT=nm(({N:e,V:t,roughness:n})=>{const r=e.dot(t).saturate(),i=dm(n,r.oneMinus().sqrt());return i.assign(i.mul(.984375).add(.0078125)),i}).setLayout({name:"LTC_Uv",type:"vec2",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"roughness",type:"float"}]}),VT=nm(({f:e})=>{const t=e.length();return S_(t.mul(t).add(e.z).div(t.add(1)),0)}).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),GT=nm(({v1:e,v2:t})=>{const n=e.dot(t),r=n.abs().toVar(),i=r.mul(.0145206).add(.4965155).mul(r).add(.8543985).toVar(),s=r.add(4.1616724).mul(r).add(3.417594).toVar(),a=i.div(s),o=n.greaterThan(0).select(a,S_(n.mul(n).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"}]}),HT=nm(({N:e,V:t,P:n,mInv:r,p0:i,p1:s,p2:a,p3:o})=>{const l=s.sub(i).toVar(),u=o.sub(i).toVar(),c=l.cross(u),h=gm().toVar();return sm(c.dot(n.sub(i)).greaterThanEqual(0),()=>{const l=t.sub(e.mul(t.dot(e))).normalize(),u=e.cross(l).negate(),c=r.mul(wm(l,u,e).transpose()).toVar(),d=c.mul(i.sub(n)).normalize().toVar(),p=c.mul(s.sub(n)).normalize().toVar(),f=c.mul(a.sub(n)).normalize().toVar(),m=c.mul(o.sub(n)).normalize().toVar(),g=gm(0).toVar();g.addAssign(GT({v1:d,v2:p})),g.addAssign(GT({v1:p,v2:f})),g.addAssign(GT({v1:f,v2:m})),g.addAssign(GT({v1:m,v2:d})),h.assign(gm(VT({f:g})))}),h}).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"}]}),jT=1/6,WT=e=>vg(jT,vg(e,vg(e,e.negate().add(3)).sub(3)).add(1)),XT=e=>vg(jT,vg(e,vg(e,vg(3,e).sub(6))).add(4)),qT=e=>vg(jT,vg(e,vg(e,vg(-3,e).add(3)).add(3)).add(1)),$T=e=>vg(jT,N_(e,3)),YT=e=>WT(e).add(XT(e)),KT=e=>qT(e).add($T(e)),QT=e=>gg(-1,XT(e).div(WT(e).add(XT(e)))),ZT=e=>gg(1,$T(e).div(qT(e).add($T(e)))),JT=(e,t,n)=>{const r=e.uvNode,i=vg(r,t.zw).add(.5),s=e_(i),a=r_(i),o=YT(a.x),l=KT(a.x),u=QT(a.x),c=ZT(a.x),h=QT(a.y),d=ZT(a.y),p=dm(s.x.add(u),s.y.add(h)).sub(.5).mul(t.xy),f=dm(s.x.add(c),s.y.add(h)).sub(.5).mul(t.xy),m=dm(s.x.add(u),s.y.add(d)).sub(.5).mul(t.xy),g=dm(s.x.add(c),s.y.add(d)).sub(.5).mul(t.xy),_=YT(a.y).mul(gg(o.mul(e.sample(p).level(n)),l.mul(e.sample(f).level(n)))),v=KT(a.y).mul(gg(o.mul(e.sample(m).level(n)),l.mul(e.sample(g).level(n))));return _.add(v)},eS=nm(([e,t])=>{const n=dm(e.size(um(t))),r=dm(e.size(um(t.add(1)))),i=yg(1,n),s=yg(1,r),a=JT(e,xm(i,n),e_(t)),o=JT(e,xm(s,r),t_(t));return r_(t).mix(a,o)}),tS=nm(([e,t,n,r,i])=>{const s=gm(k_(t.negate(),n_(e),yg(1,r))),a=gm(d_(i[0].xyz),d_(i[1].xyz),d_(i[2].xyz));return n_(s).mul(n.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"}]}),nS=nm(([e,t])=>e.mul(F_(t.mul(2).sub(2),0,1))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),rS=Ib(),iS=Ib(),sS=nm(([e,t,n],{material:r})=>{const i=(1===r.side?rS:iS).sample(e),s=Qg(Cb.x).mul(nS(t,n));return eS(i,s)}),aS=nm(([e,t,n])=>(sm(n.notEqual(0),()=>{const r=Kg(t).negate().div(n);return $g(r.negate().mul(e))}),gm(1))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),oS=nm(([e,t,n,r,i,s,a,o,l,u,c,h,d,p,f])=>{let m,g;if(f){m=xm().toVar(),g=gm().toVar();const i=c.sub(1).mul(f.mul(.025)),s=gm(c.sub(i),c,c.add(i));fb({start:0,end:3},({i:i})=>{const c=s.element(i),f=tS(e,t,h,c,o),_=a.add(f),v=u.mul(l.mul(xm(_,1))),y=dm(v.xy.div(v.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(dm(y.x,y.y.oneMinus()));const x=sS(y,n,c);m.element(i).assign(x.element(i)),m.a.addAssign(x.a),g.element(i).assign(r.element(i).mul(aS(d_(f),d,p).element(i)))}),m.a.divAssign(3)}else{const i=tS(e,t,h,c,o),s=a.add(i),f=u.mul(l.mul(xm(s,1))),_=dm(f.xy.div(f.w)).toVar();_.addAssign(1),_.divAssign(2),_.assign(dm(_.x,_.y.oneMinus())),m=sS(_,n,c),g=r.mul(aS(d_(i),d,p))}const _=g.rgb.mul(m.rgb),v=e.dot(t).clamp(),y=gm(UT({dotNV:v,specularColor:i,specularF90:s,roughness:n})),x=g.r.add(g.g,g.b).div(3);return xm(y.oneMinus().mul(_),m.a.oneMinus().mul(x).oneMinus())}),lS=wm(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),uS=(e,t)=>e.sub(t).div(e.add(t)).pow2(),cS=nm(({outsideIOR:e,eta2:t,cosTheta1:n,thinFilmThickness:r,baseF0:i})=>{const s=O_(e,t,z_(0,.03,r)),a=e.div(s).pow2().mul(n.pow2().oneMinus()).oneMinus();sm(a.lessThan(0),()=>gm(1));const o=a.sqrt(),l=uS(s,e),u=_T({f0:l,f90:1,dotVH:n}),c=u.oneMinus(),h=s.lessThan(e).select(Math.PI,0),d=lm(Math.PI).sub(h),p=(e=>{const t=e.sqrt();return gm(1).add(t).div(gm(1).sub(t))})(i.clamp(0,.9999)),f=uS(p,s.toVec3()),m=_T({f0:f,f90:1,dotVH:o}),g=gm(p.x.lessThan(s).select(Math.PI,0),p.y.lessThan(s).select(Math.PI,0),p.z.lessThan(s).select(Math.PI,0)),_=s.mul(r,o,2),v=gm(d).add(g),y=u.mul(m).clamp(1e-5,.9999),x=y.sqrt(),b=c.pow2().mul(m).div(gm(1).sub(y)),T=u.add(b).toVar(),S=b.sub(c).toVar();return fb({start:1,end:2,condition:"<=",name:"m"},({m:e})=>{S.mulAssign(x);const t=((e,t)=>{const n=e.mul(2*Math.PI*1e-9),r=gm(54856e-17,44201e-17,52481e-17),i=gm(1681e3,1795300,2208400),s=gm(43278e5,93046e5,66121e5),a=lm(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(n.mul(2239900).add(t.x).cos()).mul(n.pow2().mul(-45282e5).exp());let o=r.mul(s.mul(2*Math.PI).sqrt()).mul(i.mul(n).add(t).cos()).mul(n.pow2().negate().mul(s).exp());return o=gm(o.x.add(a),o.y,o.z).div(1.0685e-7),lS.mul(o)})(lm(e).mul(_),lm(e).mul(v)).mul(2);T.addAssign(S.mul(t))}),T.max(gm(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"}]}),hS=nm(({normal:e,viewDir:t,roughness:n})=>{const r=e.dot(t).saturate(),i=n.pow2(),s=j_(n.lessThan(.25),lm(-339.2).mul(i).add(lm(161.4).mul(n)).sub(25.9),lm(-8.48).mul(i).add(lm(14.3).mul(n)).sub(9.95)),a=j_(n.lessThan(.25),lm(44).mul(i).sub(lm(23.7).mul(n)).add(3.26),lm(1.97).mul(i).sub(lm(3.27).mul(n)).add(.72));return j_(n.lessThan(.25),0,lm(.1).mul(n).sub(.025)).add(s.mul(r).add(a).exp()).mul(1/Math.PI).saturate()}),dS=gm(.04),pS=lm(1);class fS extends pT{constructor(e=!1,t=!1,n=!1,r=!1,i=!1,s=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=n,this.anisotropy=r,this.transmission=i,this.dispersion=s,this.clearcoatRadiance=null,this.clearcoatSpecularDirect=null,this.clearcoatSpecularIndirect=null,this.sheenSpecularDirect=null,this.sheenSpecularIndirect=null,this.iridescenceFresnel=null,this.iridescenceF0=null}start(e){if(!0===this.clearcoat&&(this.clearcoatRadiance=gm().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=gm().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=gm().toVar("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=gm().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=gm().toVar("sheenSpecularIndirect")),!0===this.iridescence){const e=xy.dot(hy).clamp();this.iridescenceFresnel=cS({outsideIOR:lm(1),eta2:km,cosTheta1:e,thinFilmThickness:zm,baseF0:Wm}),this.iridescenceF0=OT({f:this.iridescenceFresnel,f90:1,dotVH:e})}if(!0===this.transmission){const t=ly,n=$v.sub(ly).normalize(),r=by,i=e.context;i.backdrop=oS(r,n,Lm,Nm,Wm,Xm,t,Jv,qv,Xv,Qm,Jm,tg,eg,this.dispersion?ng:null),i.backdropAlpha=Zm,Nm.a.mulAssign(O_(1,i.backdrop.a,Zm))}super.start(e)}computeMultiscattering(e,t,n){const r=xy.dot(hy).clamp(),i=IT({roughness:Lm,dotNV:r}),s=(this.iridescenceF0?Bm.mix(Wm,this.iridescenceF0):Wm).mul(i.x).add(n.mul(i.y)),a=i.x.add(i.y).oneMinus(),o=Wm.add(Wm.oneMinus().mul(.047619)),l=s.mul(o).div(a.mul(o).oneMinus());e.addAssign(s),t.addAssign(l.mul(a))}direct({lightDirection:e,lightColor:t,reflectedLight:n}){const r=xy.dot(e).clamp().mul(t);if(!0===this.sheen&&this.sheenSpecularDirect.addAssign(r.mul(kT({lightDirection:e}))),!0===this.clearcoat){const n=Ty.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(n.mul(DT({lightDirection:e,f0:dS,f90:pS,roughness:Um,normalView:Ty})))}n.directDiffuse.addAssign(r.mul(vT({diffuseColor:Nm.rgb}))),n.directSpecular.addAssign(r.mul(DT({lightDirection:e,f0:Wm,f90:1,roughness:Lm,iridescence:this.iridescence,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy})))}directRectArea({lightColor:e,lightPosition:t,halfWidth:n,halfHeight:r,reflectedLight:i,ltc_1:s,ltc_2:a}){const o=t.add(n).sub(r),l=t.sub(n).sub(r),u=t.sub(n).add(r),c=t.add(n).add(r),h=xy,d=hy,p=cy.toVar(),f=zT({N:h,V:d,roughness:Lm}),m=s.sample(f).toVar(),g=a.sample(f).toVar(),_=wm(gm(m.x,0,m.y),gm(0,1,0),gm(m.z,0,m.w)).toVar(),v=Wm.mul(g.x).add(Wm.oneMinus().mul(g.y)).toVar();i.directSpecular.addAssign(e.mul(v).mul(HT({N:h,V:d,P:p,mInv:_,p0:o,p1:l,p2:u,p3:c}))),i.directDiffuse.addAssign(e.mul(Nm).mul(HT({N:h,V:d,P:p,mInv:wm(1,0,0,0,1,0,0,0,1),p0:o,p1:l,p2:u,p3:c})))}indirect(e){this.indirectDiffuse(e),this.indirectSpecular(e),this.ambientOcclusion(e)}indirectDiffuse(e){const{irradiance:t,reflectedLight:n}=e.context;n.indirectDiffuse.addAssign(t.mul(vT({diffuseColor:Nm})))}indirectSpecular(e){const{radiance:t,iblIrradiance:n,reflectedLight:r}=e.context;if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(n.mul(Om,hS({normal:xy,viewDir:hy,roughness:Fm}))),!0===this.clearcoat){const e=Ty.dot(hy).clamp(),t=UT({dotNV:e,specularColor:dS,specularF90:pS,roughness:Um});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const i=gm().toVar("singleScattering"),s=gm().toVar("multiScattering"),a=n.mul(1/Math.PI);this.computeMultiscattering(i,s,Xm);const o=i.add(s),l=Nm.mul(o.r.max(o.g).max(o.b).oneMinus());r.indirectSpecular.addAssign(t.mul(i)),r.indirectSpecular.addAssign(s.mul(a)),r.indirectDiffuse.addAssign(l.mul(a))}ambientOcclusion(e){const{ambientOcclusion:t,reflectedLight:n}=e.context,r=xy.dot(hy).clamp().add(t),i=Lm.mul(-16).oneMinus().negate().exp2(),s=t.sub(r.pow(i).oneMinus()).clamp();!0===this.clearcoat&&this.clearcoatSpecularIndirect.mulAssign(t),!0===this.sheen&&this.sheenSpecularIndirect.mulAssign(t),n.indirectDiffuse.mulAssign(t),n.indirectSpecular.mulAssign(s)}finish({context:e}){const{outgoingLight:t}=e;if(!0===this.clearcoat){const e=Ty.dot(hy).clamp(),n=_T({dotVH:e,f0:dS,f90:pS}),r=t.mul(Im.mul(n).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(Im));t.assign(r)}if(!0===this.sheen){const e=Om.r.max(Om.g).max(Om.b).mul(.157).oneMinus(),n=t.mul(e).add(this.sheenSpecularDirect,this.sheenSpecularIndirect);t.assign(n)}}}const mS=lm(1),gS=lm(-2),_S=lm(.8),vS=lm(-1),yS=lm(.4),xS=lm(2),bS=lm(.305),TS=lm(3),SS=lm(.21),MS=lm(4),wS=lm(4),ES=lm(16),AS=nm(([e])=>{const t=gm(c_(e)).toVar(),n=lm(-1).toVar();return sm(t.x.greaterThan(t.z),()=>{sm(t.x.greaterThan(t.y),()=>{n.assign(j_(e.x.greaterThan(0),0,3))}).Else(()=>{n.assign(j_(e.y.greaterThan(0),1,4))})}).Else(()=>{sm(t.z.greaterThan(t.y),()=>{n.assign(j_(e.z.greaterThan(0),2,5))}).Else(()=>{n.assign(j_(e.y.greaterThan(0),1,4))})}),n}).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),RS=nm(([e,t])=>{const n=dm().toVar();return sm(t.equal(0),()=>{n.assign(dm(e.z,e.y).div(c_(e.x)))}).ElseIf(t.equal(1),()=>{n.assign(dm(e.x.negate(),e.z.negate()).div(c_(e.y)))}).ElseIf(t.equal(2),()=>{n.assign(dm(e.x.negate(),e.y).div(c_(e.z)))}).ElseIf(t.equal(3),()=>{n.assign(dm(e.z.negate(),e.y).div(c_(e.x)))}).ElseIf(t.equal(4),()=>{n.assign(dm(e.x.negate(),e.z).div(c_(e.y)))}).Else(()=>{n.assign(dm(e.x,e.y).div(c_(e.z)))}),vg(.5,n.add(1))}).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),CS=nm(([e])=>{const t=lm(0).toVar();return sm(e.greaterThanEqual(_S),()=>{t.assign(mS.sub(e).mul(vS.sub(gS)).div(mS.sub(_S)).add(gS))}).ElseIf(e.greaterThanEqual(yS),()=>{t.assign(_S.sub(e).mul(xS.sub(vS)).div(_S.sub(yS)).add(vS))}).ElseIf(e.greaterThanEqual(bS),()=>{t.assign(yS.sub(e).mul(TS.sub(xS)).div(yS.sub(bS)).add(xS))}).ElseIf(e.greaterThanEqual(SS),()=>{t.assign(bS.sub(e).mul(MS.sub(TS)).div(bS.sub(SS)).add(TS))}).Else(()=>{t.assign(lm(-2).mul(Qg(vg(1.16,e))))}),t}).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),NS=nm(([e,t])=>{const n=e.toVar();n.assign(vg(2,n).sub(1));const r=gm(n,1).toVar();return sm(t.equal(0),()=>{r.assign(r.zyx)}).ElseIf(t.equal(1),()=>{r.assign(r.xzy),r.xz.mulAssign(-1)}).ElseIf(t.equal(2),()=>{r.x.mulAssign(-1)}).ElseIf(t.equal(3),()=>{r.assign(r.zyx),r.xz.mulAssign(-1)}).ElseIf(t.equal(4),()=>{r.assign(r.xzy),r.xy.mulAssign(-1)}).ElseIf(t.equal(5),()=>{r.z.mulAssign(-1)}),r}).setLayout({name:"getDirection",type:"vec3",inputs:[{name:"uv",type:"vec2"},{name:"face",type:"float"}]}),PS=nm(([e,t,n,r,i,s])=>{const a=lm(n),o=gm(t),l=F_(CS(a),gS,s),u=r_(l),c=e_(l),h=gm(LS(e,o,c,r,i,s)).toVar();return sm(u.notEqual(0),()=>{const t=gm(LS(e,o,c.add(1),r,i,s)).toVar();h.assign(O_(h,t,u))}),h}),LS=nm(([e,t,n,r,i,s])=>{const a=lm(n).toVar(),o=gm(t),l=lm(AS(o)).toVar(),u=lm(S_(wS.sub(a),0)).toVar();a.assign(S_(a,wS));const c=lm(Yg(a)).toVar(),h=dm(RS(o,l).mul(c.sub(2)).add(1)).toVar();return sm(l.greaterThan(2),()=>{h.y.addAssign(c),l.subAssign(3)}),h.x.addAssign(l.mul(c)),h.x.addAssign(u.mul(vg(3,ES))),h.y.addAssign(vg(4,Yg(s).sub(c))),h.x.mulAssign(r),h.y.mulAssign(i),e.sample(h).grad(dm(),dm())}),DS=nm(({envMap:e,mipInt:t,outputDirection:n,theta:r,axis:i,CUBEUV_TEXEL_WIDTH:s,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const l=s_(r),u=n.mul(l).add(i.cross(n).mul(i_(r))).add(i.mul(i.dot(n).mul(l.oneMinus())));return LS(e,u,t,s,a,o)}),IS=nm(({n:e,latitudinal:t,poleAxis:n,outputDirection:r,weights:i,samples:s,dTheta:a,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:c,CUBEUV_MAX_MIP:h})=>{const d=gm(j_(t,n,C_(n,r))).toVar();sm(d.equal(gm(0)),()=>{d.assign(gm(r.z,0,r.x.negate()))}),d.assign(n_(d));const p=gm().toVar();return p.addAssign(i.element(0).mul(DS({theta:0,axis:d,outputDirection:r,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:c,CUBEUV_MAX_MIP:h}))),fb({start:um(1),end:e},({i:e})=>{sm(e.greaterThanEqual(s),()=>{Tv("break").toStack()});const t=lm(a.mul(lm(e))).toVar();p.addAssign(i.element(e).mul(DS({theta:t.mul(-1),axis:d,outputDirection:r,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:c,CUBEUV_MAX_MIP:h}))),p.addAssign(i.element(e).mul(DS({theta:t,axis:d,outputDirection:r,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:c,CUBEUV_MAX_MIP:h})))}),xm(p,1)}),US=[.125,.215,.35,.446,.526,.582],OS=20,FS=new na(-1,1,1,-1,0,1),BS=new Mi(90,1),kS=new Nr;let zS=null,VS=0,GS=0;const HS=(1+Math.sqrt(5))/2,jS=1/HS,WS=[new Ut(-HS,jS,0),new Ut(HS,jS,0),new Ut(-jS,0,HS),new Ut(jS,0,HS),new Ut(0,HS,-jS),new Ut(0,HS,jS),new Ut(-1,1,-1),new Ut(1,1,-1),new Ut(-1,1,1),new Ut(1,1,1)],XS=new Ut,qS=new WeakMap,$S=[3,1,5,0,4,2],YS=NS(Av(),Ev("faceIndex")).normalize(),KS=gm(YS.x,YS.y,YS.z);class QS{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._backgroundBox=null}get _hasInitialized(){return this._renderer.hasInitialized()}fromScene(e,t=0,n=.1,r=100,i={}){const{size:s=256,position:a=XS,renderTarget:o=null}=i;if(this._setSize(s),!1===this._hasInitialized){console.warn("THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.");const s=o||this._allocateTarget();return i.renderTarget=s,this.fromSceneAsync(e,t,n,r,i),s}zS=this._renderer.getRenderTarget(),VS=this._renderer.getActiveCubeFace(),GS=this._renderer.getActiveMipmapLevel();const l=o||this._allocateTarget();return l.depthBuffer=!0,this._init(l),this._sceneToCubeUV(e,n,r,l,a),t>0&&this._blur(l,0,0,t),this._applyPMREM(l),this._cleanup(l),l}async fromSceneAsync(e,t=0,n=.1,r=100,i={}){return!1===this._hasInitialized&&await this._renderer.init(),this.fromScene(e,t,n,r,i)}fromEquirectangular(e,t=null){if(!1===this._hasInitialized){console.warn("THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead."),this._setSizeFromTexture(e);const n=t||this._allocateTarget();return this.fromEquirectangularAsync(e,n),n}return this._fromTexture(e,t)}async fromEquirectangularAsync(e,t=null){return!1===this._hasInitialized&&await this._renderer.init(),this._fromTexture(e,t)}fromCubemap(e,t=null){if(!1===this._hasInitialized){console.warn("THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead."),this._setSizeFromTexture(e);const n=t||this._allocateTarget();return this.fromCubemapAsync(e,t),n}return this._fromTexture(e,t)}async fromCubemapAsync(e,t=null){return!1===this._hasInitialized&&await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=tM(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=nM(),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===G||e.mapping===H?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._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodPlanes.length;e++)this._lodPlanes[e].dispose()}_cleanup(e){this._renderer.setRenderTarget(zS,VS,GS),e.scissorTest=!1,JS(e,0,0,e.width,e.height)}_fromTexture(e,t){this._setSizeFromTexture(e),zS=this._renderer.getRenderTarget(),VS=this._renderer.getActiveCubeFace(),GS=this._renderer.getActiveMipmapLevel();const n=t||this._allocateTarget();return this._init(n),this._textureToCubeUV(e,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTarget(){return ZS(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=ZS(e.width,e.height);const{_lodMax:t}=this;({sizeLods:this._sizeLods,lodPlanes:this._lodPlanes,sigmas:this._sigmas,lodMeshes:this._lodMeshes}=function(e){const t=[],n=[],r=[],i=[];let s=e;const a=e-4+1+US.length;for(let o=0;o<a;o++){const a=Math.pow(2,s);n.push(a);let l=1/a;o>e-4?l=US[o-e+4-1]:0===o&&(l=0),r.push(l);const u=1/(a-2),c=-u,h=1+u,d=[c,c,h,c,h,h,c,c,h,h,c,h],p=6,f=6,m=3,g=2,_=1,v=new Float32Array(m*f*p),y=new Float32Array(g*f*p),x=new Float32Array(_*f*p);for(let e=0;e<p;e++){const t=e%3*2/3-1,n=e>2?0:-1,r=[t,n,0,t+2/3,n,0,t+2/3,n+1,0,t,n,0,t+2/3,n+1,0,t,n+1,0],i=$S[e];v.set(r,m*f*i),y.set(d,g*f*i);const s=[i,i,i,i,i,i];x.set(s,_*f*i)}const b=new ei;b.setAttribute("position",new Gr(v,m)),b.setAttribute("uv",new Gr(y,g)),b.setAttribute("faceIndex",new Gr(x,_)),t.push(b),i.push(new di(b,null)),s>4&&s--}return{lodPlanes:t,sizeLods:n,sigmas:r,lodMeshes:i}}(t)),this._blurMaterial=function(e,t,n){const r=Vv(new Array(OS).fill(0)),i=cg(new Ut(0,1,0)),s=cg(0),a=lm(OS),o=cg(0),l=cg(1),u=Uv(null),c=cg(0),h=lm(1/t),d=lm(1/n),p=lm(e),f={n:a,latitudinal:o,weights:r,poleAxis:i,outputDirection:KS,dTheta:s,samples:l,envMap:u,mipInt:c,CUBEUV_TEXEL_WIDTH:h,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:p},m=eM("blur");return m.fragmentNode=IS({...f,latitudinal:o.equal(1)}),qS.set(m,f),m}(t,e.width,e.height)}}async _compileMaterial(e){const t=new di(this._lodPlanes[0],e);await this._renderer.compile(t,FS)}_sceneToCubeUV(e,t,n,r,i){const s=BS;s.near=t,s.far=n;const a=[1,1,1,1,-1,1],o=[1,-1,1,-1,1,-1],l=this._renderer,u=l.autoClear;l.getClearColor(kS),l.autoClear=!1;let c=this._backgroundBox;if(null===c){const e=new Ir({name:"PMREM.Background",side:1,depthWrite:!1,depthTest:!1});c=new di(new fi,e)}let h=!1;const d=e.background;d?d.isColor&&(c.material.color.copy(d),e.background=null,h=!0):(c.material.color.copy(kS),h=!0),l.setRenderTarget(r),l.clear(),h&&l.render(c,s);for(let t=0;t<6;t++){const n=t%3;0===n?(s.up.set(0,a[t],0),s.position.set(i.x,i.y,i.z),s.lookAt(i.x+o[t],i.y,i.z)):1===n?(s.up.set(0,0,a[t]),s.position.set(i.x,i.y,i.z),s.lookAt(i.x,i.y+o[t],i.z)):(s.up.set(0,a[t],0),s.position.set(i.x,i.y,i.z),s.lookAt(i.x,i.y,i.z+o[t]));const u=this._cubeSize;JS(r,n*u,t>2?u:0,u,u),l.render(e,s)}l.autoClear=u,e.background=d}_textureToCubeUV(e,t){const n=this._renderer,r=e.mapping===G||e.mapping===H;r?null===this._cubemapMaterial&&(this._cubemapMaterial=tM(e)):null===this._equirectMaterial&&(this._equirectMaterial=nM(e));const i=r?this._cubemapMaterial:this._equirectMaterial;i.fragmentNode.value=e;const s=this._lodMeshes[0];s.material=i;const a=this._cubeSize;JS(t,0,0,3*a,2*a),n.setRenderTarget(t),n.render(s,FS)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;const r=this._lodPlanes.length;for(let t=1;t<r;t++){const n=Math.sqrt(this._sigmas[t]*this._sigmas[t]-this._sigmas[t-1]*this._sigmas[t-1]),i=WS[(r-t-1)%WS.length];this._blur(e,t-1,t,n,i)}t.autoClear=n}_blur(e,t,n,r,i){const s=this._pingPongRenderTarget;this._halfBlur(e,s,t,n,r,"latitudinal",i),this._halfBlur(s,e,n,n,r,"longitudinal",i)}_halfBlur(e,t,n,r,i,s,a){const o=this._renderer,l=this._blurMaterial;"latitudinal"!==s&&"longitudinal"!==s&&console.error("blur direction must be either latitudinal or longitudinal!");const u=this._lodMeshes[r];u.material=l;const c=qS.get(l),h=this._sizeLods[n]-1,d=isFinite(i)?Math.PI/(2*h):2*Math.PI/39,p=i/d,f=isFinite(i)?1+Math.floor(3*p):OS;f>OS&&console.warn(`sigmaRadians, ${i}, is too large and will clip, as it requested ${f} samples when the maximum is set to 20`);const m=[];let g=0;for(let e=0;e<OS;++e){const t=e/p,n=Math.exp(-t*t/2);m.push(n),0===e?g+=n:e<f&&(g+=2*n)}for(let e=0;e<m.length;e++)m[e]=m[e]/g;e.texture.frame=(e.texture.frame||0)+1,c.envMap.value=e.texture,c.samples.value=f,c.weights.array=m,c.latitudinal.value="latitudinal"===s?1:0,a&&(c.poleAxis.value=a);const{_lodMax:_}=this;c.dTheta.value=d,c.mipInt.value=_-n;const v=this._sizeLods[r];JS(t,3*v*(r>_-4?r-_+4:0),4*(this._cubeSize-v),3*v,2*v),o.setRenderTarget(t),o.render(u,FS)}}function ZS(e,t){const n=new on(e,t,{magFilter:J,minFilter:J,generateMipmaps:!1,type:ue,format:ge,colorSpace:it});return n.texture.mapping=X,n.texture.name="PMREM.cubeUv",n.texture.isPMREMTexture=!0,n.scissorTest=!0,n}function JS(e,t,n,r,i){e.viewport.set(t,n,r,i),e.scissor.set(t,n,r,i)}function eM(e){const t=new Qb;return t.depthTest=!1,t.depthWrite=!1,t.blending=0,t.name=`PMREM_${e}`,t}function tM(e){const t=eM("cubemap");return t.fragmentNode=Fy(e,KS),t}function nM(e){const t=eM("equirect");return t.fragmentNode=Uv(e,iT(KS),0),t}const rM=new WeakMap;function iM(e,t,n){const r=function(e){let t=rM.get(e);void 0===t&&(t=new WeakMap,rM.set(e,t));return t}(t);let i=r.get(e);if((void 0!==i?i.pmremVersion:-1)!==e.pmremVersion){const t=e.image;if(e.isCubeTexture){if(!function(e){if(null==e)return!1;let t=0;const n=6;for(let r=0;r<n;r++)void 0!==e[r]&&t++;return t===n}(t))return null;i=n.fromCubemap(e,i)}else{if(!function(e){return null!=e&&e.height>0}(t))return null;i=n.fromEquirectangular(e,i)}i.pmremVersion=e.pmremVersion,r.set(e,i)}return i.texture}class sM extends df{static get type(){return"PMREMNode"}constructor(e,t=null,n=null){super("vec3"),this._value=e,this._pmrem=null,this.uvNode=t,this.levelNode=n,this._generator=null;const r=new sn;r.isRenderTargetTexture=!0,this._texture=Uv(r),this._width=cg(0),this._height=cg(0),this._maxMip=cg(0),this.updateBeforeType=Zp}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,n=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,t),112)),texelHeight:n,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 n=t?t.pmremVersion:-1,r=this._value;n!==r.pmremVersion&&(t=!0===r.isPMREMTexture?r:iM(r,e.renderer,this._generator),null!==t&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){null===this._generator&&(this._generator=new QS(e.renderer)),this.updateBefore(e);let t=this.uvNode;null===t&&e.context.getUV&&(t=e.context.getUV(this)),t=Cy.mul(gm(t.x,t.y.negate(),t.z));let n=this.levelNode;return null===n&&e.context.getTextureLevel&&(n=e.context.getTextureLevel(this)),PS(this._texture,t,n,this._width,this._height,this._maxMip)}dispose(){super.dispose(),null!==this._generator&&this._generator.dispose()}}const aM=Jf(sM).setParameterLength(1,3),oM=new WeakMap;class lM extends xb{static get type(){return"EnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){const{material:t}=e;let n=this.envNode;if(n.isTextureNode||n.isMaterialReferenceNode){const e=n.isTextureNode?n.value:t[n.property];let r=oM.get(e);void 0===r&&(r=aM(e),oM.set(e,r)),n=r}const r=!0===t.useAnisotropy||t.anisotropy>0?ux:xy,i=n.context(uM(Lm,r)).mul(Ry),s=n.context(cM(by)).mul(Math.PI).mul(Ry),a=gv(i),o=gv(s);e.context.radiance.addAssign(a),e.context.iblIrradiance.addAssign(o);const l=e.context.lightingModel.clearcoatRadiance;if(l){const e=n.context(uM(Um,Ty)).mul(Ry),t=gv(e);l.addAssign(t)}}}const uM=(e,t)=>{let n=null;return{getUV:()=>(null===n&&(n=hy.negate().reflect(t),n=e.mul(e).mix(n,t).normalize(),n=n.transformDirection(qv)),n),getTextureLevel:()=>e}},cM=e=>({getUV:()=>e,getTextureLevel:()=>lm(1)}),hM=new As;class dM extends Qb{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(hM),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return null===t&&e.environmentNode&&(t=e.environmentNode),t?new lM(t):null}setupLightingModel(){return new fS}setupSpecular(){const e=O_(gm(.04),Nm.rgb,Dm);Wm.assign(e),Xm.assign(1)}setupVariants(){const e=this.metalnessNode?lm(this.metalnessNode):Cx;Dm.assign(e);let t=this.roughnessNode?lm(this.roughnessNode):Rx;t=AT({roughness:t}),Lm.assign(t),this.setupSpecular(),Nm.assign(xm(Nm.rgb.mul(e.oneMinus()),Nm.a))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}const pM=new Rs;class fM extends dM{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(pM),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?lm(this.iorNode):Hx;Qm.assign(e),Wm.assign(O_(T_(P_(Qm.sub(1).div(Qm.add(1))).mul(wx),gm(1)).mul(Mx),Nm.rgb,Dm)),Xm.assign(O_(Mx,1,Dm))}setupLightingModel(){return new fS(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?lm(this.clearcoatNode):Px,t=this.clearcoatRoughnessNode?lm(this.clearcoatRoughnessNode):Lx;Im.assign(e),Um.assign(AT({roughness:t}))}if(this.useSheen){const e=this.sheenNode?gm(this.sheenNode):Ux,t=this.sheenRoughnessNode?lm(this.sheenRoughnessNode):Ox;Om.assign(e),Fm.assign(t)}if(this.useIridescence){const e=this.iridescenceNode?lm(this.iridescenceNode):Bx,t=this.iridescenceIORNode?lm(this.iridescenceIORNode):kx,n=this.iridescenceThicknessNode?lm(this.iridescenceThicknessNode):zx;Bm.assign(e),km.assign(t),zm.assign(n)}if(this.useAnisotropy){const e=(this.anisotropyNode?dm(this.anisotropyNode):Fx).toVar();Gm.assign(e.length()),sm(Gm.equal(0),()=>{e.assign(dm(1,0))}).Else(()=>{e.divAssign(dm(Gm)),Gm.assign(Gm.saturate())}),Vm.assign(Gm.pow2().mix(Lm.pow2(),1)),Hm.assign(lx[0].mul(e.x).add(lx[1].mul(e.y))),jm.assign(lx[1].mul(e.x).sub(lx[0].mul(e.y)))}if(this.useTransmission){const e=this.transmissionNode?lm(this.transmissionNode):Vx,t=this.thicknessNode?lm(this.thicknessNode):Gx,n=this.attenuationDistanceNode?lm(this.attenuationDistanceNode):jx,r=this.attenuationColorNode?gm(this.attenuationColorNode):Wx;if(Zm.assign(e),Jm.assign(t),eg.assign(n),tg.assign(r),this.useDispersion){const e=this.dispersionNode?lm(this.dispersionNode):Qx;ng.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?gm(this.clearcoatNormalNode):Dx}setup(e){e.context.setupClearcoatNormal=()=>K_(this.setupClearcoatNormal(e),"NORMAL","vec3"),super.setup(e)}copy(e){return this.clearcoatNode=e.clearcoatNode,this.clearcoatRoughnessNode=e.clearcoatRoughnessNode,this.clearcoatNormalNode=e.clearcoatNormalNode,this.sheenNode=e.sheenNode,this.sheenRoughnessNode=e.sheenRoughnessNode,this.iridescenceNode=e.iridescenceNode,this.iridescenceIORNode=e.iridescenceIORNode,this.iridescenceThicknessNode=e.iridescenceThicknessNode,this.specularIntensityNode=e.specularIntensityNode,this.specularColorNode=e.specularColorNode,this.transmissionNode=e.transmissionNode,this.thicknessNode=e.thicknessNode,this.attenuationDistanceNode=e.attenuationDistanceNode,this.attenuationColorNode=e.attenuationColorNode,this.dispersionNode=e.dispersionNode,this.anisotropyNode=e.anisotropyNode,super.copy(e)}}const mM=nm(({normal:e,lightDirection:t,builder:n})=>{const r=e.dot(t),i=dm(r.mul(.5).add(.5),0);if(n.material.gradientMap){const e=Hy("gradientMap","texture").context({getUV:()=>i});return gm(e.r)}{const e=i.fwidth().mul(.5);return O_(gm(.7),gm(1),z_(lm(.7).sub(e.x),lm(.7).add(e.x),i.x))}});class gM extends pT{direct({lightDirection:e,lightColor:t,reflectedLight:n},r){const i=mM({normal:my,lightDirection:e,builder:r}).mul(t);n.directDiffuse.addAssign(i.mul(vT({diffuseColor:Nm.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:n,reflectedLight:r}=e.context;r.indirectDiffuse.addAssign(n.mul(vT({diffuseColor:Nm}))),r.indirectDiffuse.mulAssign(t)}}const _M=new Ns;class vM extends Qb{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(_M),this.setValues(e)}setupLightingModel(){return new gM}}const yM=nm(()=>{const e=gm(hy.z,0,hy.x.negate()).normalize(),t=hy.cross(e);return dm(e.dot(xy),t.dot(xy)).mul(.495).add(.5)}).once(["NORMAL","VERTEX"])().toVar("matcapUV"),xM=new Us;class bM extends Qb{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(xM),this.setValues(e)}setupVariants(e){const t=yM;let n;n=e.material.matcap?Hy("matcap","texture").context({getUV:()=>t}):gm(O_(.2,.8,t.y)),Nm.rgb.mulAssign(n.rgb)}}class TM extends df{static get type(){return"RotateNode"}constructor(e,t){super(),this.positionNode=e,this.rotationNode=t}getNodeType(e){return this.positionNode.getNodeType(e)}setup(e){const{rotationNode:t,positionNode:n}=this;if("vec2"===this.getNodeType(e)){const e=t.cos(),r=t.sin();return Mm(e,r,r.negate(),e).mul(n)}{const e=t,r=Em(xm(1,0,0,0),xm(0,s_(e.x),i_(e.x).negate(),0),xm(0,i_(e.x),s_(e.x),0),xm(0,0,0,1)),i=Em(xm(s_(e.y),0,i_(e.y),0),xm(0,1,0,0),xm(i_(e.y).negate(),0,s_(e.y),0),xm(0,0,0,1)),s=Em(xm(s_(e.z),i_(e.z).negate(),0,0),xm(i_(e.z),s_(e.z),0,0),xm(0,0,1,0),xm(0,0,0,1));return r.mul(i).mul(s).mul(xm(n,1)).xyz}}}const SM=Jf(TM).setParameterLength(2),MM=new Oi;class wM extends Qb{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(MM),this.setValues(e)}setupPositionView(e){const{object:t,camera:n}=e,r=this.sizeAttenuation,{positionNode:i,rotationNode:s,scaleNode:a}=this,o=ty.mul(gm(i||0));let l=dm(Jv[0].xyz.length(),Jv[1].xyz.length());if(null!==a&&(l=l.mul(dm(a))),!1===r)if(n.isPerspectiveCamera)l=l.mul(o.z.negate());else{const e=lm(2).div(Xv.element(1).element(1));l=l.mul(e.mul(2))}let u=sy.xy;if(t.center&&!0===t.center.isVector2){const e=((e,t,n)=>Kf(new sv(e,t,n)))("center","vec2",t);u=u.sub(e.sub(.5))}u=u.mul(l);const c=lm(s||Ix),h=SM(u,c);return xm(o.xy.add(h),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 EM=new ss;class AM extends wM{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(EM),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return ty.mul(gm(e||ay)).xyz}setupVertex(e){const t=super.setupVertex(e);if(!0!==e.material.isNodeMaterial)return t;const{rotationNode:n,scaleNode:r,sizeNode:i}=this,s=sy.xy.toVar(),a=Pb.z.div(Pb.w);if(n&&n.isNode){const e=lm(n);s.assign(SM(s,e))}let o=null!==i?dm(i):Kx;return!0===this.sizeAttenuation&&(o=o.mul(o.div(cy.z.negate()))),r&&r.isNode&&(o=o.mul(dm(r))),s.mulAssign(o.mul(2)),s.assign(s.div(Pb.z)),s.y.assign(s.y.mul(a)),s.assign(s.mul(t.w)),t.addAssign(xm(s,0,0)),t}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}}class RM extends pT{constructor(){super(),this.shadowNode=lm(1).toVar("shadowMask")}direct({lightNode:e}){null!==e.shadowNode&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){Nm.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(Nm.rgb)}}const CM=new Es;class NM extends Qb{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(CM),this.setValues(e)}setupLightingModel(){return new RM}}Rm("vec3"),Rm("vec3"),Rm("vec3");class PM{constructor(e,t){this.nodes=e,this.info=t,this._context="undefined"!=typeof self?self:null,this._animationLoop=null,this._requestId=null}start(){const e=(t,n)=>{this._requestId=this._context.requestAnimationFrame(e),!0===this.info.autoReset&&this.info.reset(),this.nodes.nodeFrame.update(),this.info.frame=this.nodes.nodeFrame.frameId,null!==this._animationLoop&&this._animationLoop(t,n)};e()}stop(){this._context.cancelAnimationFrame(this._requestId),this._requestId=null}getAnimationLoop(){return this._animationLoop}setAnimationLoop(e){this._animationLoop=e}getContext(){return this._context}setContext(e){this._context=e}dispose(){this.stop()}}class LM{constructor(){this.weakMap=new WeakMap}get(e){let t=this.weakMap;for(let n=0;n<e.length-1;n++)if(t=t.get(e[n]),void 0===t)return;return t.get(e[e.length-1])}set(e,t){let n=this.weakMap;for(let t=0;t<e.length-1;t++){const r=e[t];!1===n.has(r)&&n.set(r,new WeakMap),n=n.get(r)}return n.set(e[e.length-1],t),this}delete(e){let t=this.weakMap;for(let n=0;n<e.length-1;n++)if(t=t.get(e[n]),void 0===t)return!1;return t.delete(e[e.length-1])}}let DM=0;class IM{constructor(e,t,n,r,i,s,a,o,l,u){this.id=DM++,this._nodes=e,this._geometries=t,this.renderer=n,this.object=r,this.material=i,this.scene=s,this.camera=a,this.lightsNode=o,this.context=l,this.geometry=r.geometry,this.version=i.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=u,this.clippingContextCacheKey=null!==u?u.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)}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,n=[],r=new Set,i={};for(const s of e){let e;if(s.node&&s.node.attribute?e=s.node.attribute:(e=t.getAttribute(s.name),i[s.name]=e.version),void 0===e)continue;n.push(e);const a=e.isInterleavedBufferAttribute?e.data:e;r.add(a)}return this.attributes=n,this.attributesId=i,this.vertexBuffers=Array.from(r.values()),n}getVertexBuffers(){return null===this.vertexBuffers&&this.getAttributes(),this.vertexBuffers}getDrawParameters(){const{object:e,material:t,geometry:n,group:r,drawRange:i}=this,s=this.drawParams||(this.drawParams={vertexCount:0,firstVertex:0,instanceCount:0,firstInstance:0}),a=this.getIndex(),o=null!==a;let l=1;if(!0===n.isInstancedBufferGeometry?l=n.instanceCount:void 0!==e.count&&(l=Math.max(0,e.count)),0===l)return null;if(s.instanceCount=l,!0===e.isBatchedMesh)return s;let u=1;!0!==t.wireframe||e.isPoints||e.isLineSegments||e.isLine||e.isLineLoop||(u=2);let c=i.start*u,h=(i.start+i.count)*u;null!==r&&(c=Math.max(c,r.start*u),h=Math.min(h,(r.start+r.count)*u));const d=n.attributes.position;let p=1/0;o?p=a.count:null!=d&&(p=d.count),c=Math.max(c,0),h=Math.min(h,p);const f=h-c;return f<0||f===1/0?null:(s.vertexCount=f,s.firstVertex=c,s)}getGeometryCacheKey(){const{geometry:e}=this;let t="";for(const n of Object.keys(e.attributes).sort()){const r=e.attributes[n];t+=n+",",r.data&&(t+=r.data.stride+","),r.offset&&(t+=r.offset+","),r.itemSize&&(t+=r.itemSize+","),r.normalized&&(t+="n,")}for(const n of Object.keys(e.morphAttributes).sort()){const r=e.morphAttributes[n];t+="morph-"+n+",";for(let e=0,n=r.length;e<n;e++){t+=r[e].id+","}}return e.index&&(t+="index,"),t}getMaterialCacheKey(){const{object:e,material:t}=this;let n=t.customProgramCacheKey();for(const e of function(e){const t=Object.keys(e);let n=Object.getPrototypeOf(e);for(;n;){const e=Object.getOwnPropertyDescriptors(n);for(const n in e)if(void 0!==e[n]){const r=e[n];r&&"function"==typeof r.get&&t.push(n)}n=Object.getPrototypeOf(n)}return t}(t)){if(/^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test(e))continue;const r=t[e];let i;if(null!==r){const e=typeof r;"number"===e?i=0!==r?"1":"0":"object"===e?(i="{",r.isTexture&&(i+=r.mapping),i+="}"):i=String(r)}else i=String(r);n+=i+","}return n+=this.clippingContextCacheKey+",",e.geometry&&(n+=this.getGeometryCacheKey()),e.skeleton&&(n+=e.skeleton.bones.length+","),e.isBatchedMesh&&(n+=e._matricesTexture.uuid+",",null!==e._colorsTexture&&(n+=e._colorsTexture.uuid+",")),e.count>1&&(n+=e.uuid+","),n+=e.receiveShadow+",",kp(n)}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 n=this.geometry.getAttribute(t);if(void 0===n||e[t]!==n.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=Vp(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=Vp(e,1)),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.geometry.removeEventListener("dispose",this.onGeometryDispose),this.onDispose()}}const UM=[];class OM{constructor(e,t,n,r,i,s){this.renderer=e,this.nodes=t,this.geometries=n,this.pipelines=r,this.bindings=i,this.info=s,this.chainMaps={}}get(e,t,n,r,i,s,a,o){const l=this.getChainMap(o);UM[0]=e,UM[1]=t,UM[2]=s,UM[3]=i;let u=l.get(UM);return void 0===u?(u=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,n,r,i,s,a,o),l.set(UM,u)):(u.updateClipping(a),u.needsGeometryUpdate&&u.setGeometry(e.geometry),(u.version!==t.version||u.needsUpdate)&&(u.initialCacheKey!==u.getCacheKey()?(u.dispose(),u=this.get(e,t,n,r,i,s,a,o)):u.version=t.version)),UM.length=0,u}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new LM)}dispose(){this.chainMaps={}}createRenderObject(e,t,n,r,i,s,a,o,l,u,c){const h=this.getChainMap(c),d=new IM(e,t,n,r,i,s,a,o,l,u);return d.onDispose=()=>{this.pipelines.delete(d),this.bindings.delete(d),this.nodes.delete(d),h.delete(d.getChainArray())},d}}class FM{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 BM=1,kM=2,zM=3,VM=4,GM=16;class HM extends FM{constructor(e){super(),this.backend=e}delete(e){const t=super.delete(e);return null!==t&&this.backend.destroyAttribute(e),t}update(e,t){const n=this.get(e);if(void 0===n.version)t===BM?this.backend.createAttribute(e):t===kM?this.backend.createIndexAttribute(e):t===zM?this.backend.createStorageAttribute(e):t===VM&&this.backend.createIndirectStorageAttribute(e),n.version=this._getBufferAttribute(e).version;else{const t=this._getBufferAttribute(e);(n.version<t.version||t.usage===_t)&&(this.backend.updateAttribute(e),n.version=t.version)}}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}function jM(e){return null!==e.index?e.index.version:e.attributes.position.version}function WM(e){const t=[],n=e.index,r=e.attributes.position;if(null!==n){const e=n.array;for(let n=0,r=e.length;n<r;n+=3){const r=e[n+0],i=e[n+1],s=e[n+2];t.push(r,i,i,s,s,r)}}else{for(let e=0,n=r.array.length/3-1;e<n;e+=3){const n=e+0,r=e+1,i=e+2;t.push(n,r,r,i,i,n)}}const i=new(zt(t)?jr:Hr)(t,1);return i.version=jM(e),i}class XM extends FM{constructor(e,t){super(),this.attributes=e,this.info=t,this.wireframes=new WeakMap,this.attributeCall=new WeakMap}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 n=()=>{this.info.memory.geometries--;const r=t.index,i=e.getAttributes();null!==r&&this.attributes.delete(r);for(const e of i)this.attributes.delete(e);const s=this.wireframes.get(t);void 0!==s&&this.attributes.delete(s),t.removeEventListener("dispose",n)};t.addEventListener("dispose",n)}updateAttributes(e){const t=e.getAttributes();for(const e of t)e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute?this.updateAttribute(e,zM):this.updateAttribute(e,BM);const n=this.getIndex(e);null!==n&&this.updateAttribute(n,kM);const r=e.geometry.indirect;null!==r&&this.updateAttribute(r,VM)}updateAttribute(e,t){const n=this.info.render.calls;e.isInterleavedBufferAttribute?void 0===this.attributeCall.get(e)?(this.attributes.update(e,t),this.attributeCall.set(e,n)):this.attributeCall.get(e.data)!==n&&(this.attributes.update(e,t),this.attributeCall.set(e.data,n),this.attributeCall.set(e,n)):this.attributeCall.get(e)!==n&&(this.attributes.update(e,t),this.attributeCall.set(e,n))}getIndirect(e){return e.geometry.indirect}getIndex(e){const{geometry:t,material:n}=e;let r=t.index;if(!0===n.wireframe){const e=this.wireframes;let n=e.get(t);void 0===n?(n=WM(t),e.set(t,n)):n.version!==jM(t)&&(this.attributes.delete(n),n=WM(t),e.set(t,n)),r=n}return r}}class qM{constructor(){this.autoReset=!0,this.frame=0,this.calls=0,this.render={calls:0,frameCalls:0,drawCalls:0,triangles:0,points:0,lines:0,timestamp:0},this.compute={calls:0,frameCalls:0,timestamp:0},this.memory={geometries:0,textures:0}}update(e,t,n){this.render.drawCalls++,e.isMesh||e.isSprite?this.render.triangles+=n*(t/3):e.isPoints?this.render.points+=n*t:e.isLineSegments?this.render.lines+=n*(t/2):e.isLine?this.render.lines+=n*(t-1):console.error("THREE.WebGPUInfo: Unknown object type.")}reset(){this.render.drawCalls=0,this.render.frameCalls=0,this.compute.frameCalls=0,this.render.triangles=0,this.render.points=0,this.render.lines=0}dispose(){this.reset(),this.calls=0,this.render.calls=0,this.compute.calls=0,this.render.timestamp=0,this.compute.timestamp=0,this.memory.geometries=0,this.memory.textures=0}}class $M{constructor(e){this.cacheKey=e,this.usedTimes=0}}class YM extends $M{constructor(e,t,n){super(e),this.vertexProgram=t,this.fragmentProgram=n}}class KM extends $M{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let QM=0;class ZM{constructor(e,t,n,r=null,i=null){this.id=QM++,this.code=e,this.stage=t,this.name=n,this.transforms=r,this.attributes=i,this.usedTimes=0}}class JM extends FM{constructor(e,t){super(),this.backend=e,this.nodes=t,this.bindings=null,this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}getForCompute(e,t){const{backend:n}=this,r=this.get(e);if(this._needsComputeUpdate(e)){const i=r.pipeline;i&&(i.usedTimes--,i.computeProgram.usedTimes--);const s=this.nodes.getForCompute(e);let a=this.programs.compute.get(s.computeShader);void 0===a&&(i&&0===i.computeProgram.usedTimes&&this._releaseProgram(i.computeProgram),a=new ZM(s.computeShader,"compute",e.name,s.transforms,s.nodeAttributes),this.programs.compute.set(s.computeShader,a),n.createProgram(a));const o=this._getComputeCacheKey(e,a);let l=this.caches.get(o);void 0===l&&(i&&0===i.usedTimes&&this._releasePipeline(i),l=this._getComputePipeline(e,a,o,t)),l.usedTimes++,a.usedTimes++,r.version=e.version,r.pipeline=l}return r.pipeline}getForRender(e,t=null){const{backend:n}=this,r=this.get(e);if(this._needsRenderUpdate(e)){const i=r.pipeline;i&&(i.usedTimes--,i.vertexProgram.usedTimes--,i.fragmentProgram.usedTimes--);const s=e.getNodeBuilderState(),a=e.material?e.material.name:"";let o=this.programs.vertex.get(s.vertexShader);void 0===o&&(i&&0===i.vertexProgram.usedTimes&&this._releaseProgram(i.vertexProgram),o=new ZM(s.vertexShader,"vertex",a),this.programs.vertex.set(s.vertexShader,o),n.createProgram(o));let l=this.programs.fragment.get(s.fragmentShader);void 0===l&&(i&&0===i.fragmentProgram.usedTimes&&this._releaseProgram(i.fragmentProgram),l=new ZM(s.fragmentShader,"fragment",a),this.programs.fragment.set(s.fragmentShader,l),n.createProgram(l));const u=this._getRenderCacheKey(e,o,l);let c=this.caches.get(u);void 0===c?(i&&0===i.usedTimes&&this._releasePipeline(i),c=this._getRenderPipeline(e,o,l,u,t)):e.pipeline=c,c.usedTimes++,o.usedTimes++,l.usedTimes++,r.pipeline=c}return r.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,n,r){n=n||this._getComputeCacheKey(e,t);let i=this.caches.get(n);return void 0===i&&(i=new KM(n,t),this.caches.set(n,i),this.backend.createComputePipeline(i,r)),i}_getRenderPipeline(e,t,n,r,i){r=r||this._getRenderCacheKey(e,t,n);let s=this.caches.get(r);return void 0===s&&(s=new YM(r,t,n),this.caches.set(r,s),e.pipeline=s,this.backend.createRenderPipeline(e,i)),s}_getComputeCacheKey(e,t){return e.id+","+t.id}_getRenderCacheKey(e,t,n){return t.id+","+n.id+","+this.backend.getRenderCacheKey(e)}_releasePipeline(e){this.caches.delete(e.cacheKey)}_releaseProgram(e){const t=e.code,n=e.stage;this.programs[n].delete(t)}_needsComputeUpdate(e){const t=this.get(e);return void 0===t.pipeline||t.version!==e.version}_needsRenderUpdate(e){return void 0===this.get(e).pipeline||this.backend.needsRenderUpdate(e)}}class ew extends FM{constructor(e,t,n,r,i,s){super(),this.backend=e,this.textures=n,this.pipelines=i,this.attributes=r,this.nodes=t,this.info=s,this.pipelines.bindings=this}getForRender(e){const t=e.getBindings();for(const e of t){const n=this.get(e);void 0===n.bindGroup&&(this._init(e),this.backend.createBindings(e,t,0),n.bindGroup=e)}return t}getForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const e of t){const n=this.get(e);void 0===n.bindGroup&&(this._init(e),this.backend.createBindings(e,t,0),n.bindGroup=e)}return t}updateForCompute(e){this._updateBindings(this.getForCompute(e))}updateForRender(e){this._updateBindings(this.getForRender(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.isStorageBuffer){const e=t.attribute,n=e.isIndirectStorageBufferAttribute?VM:zM;this.attributes.update(e,n)}}_update(e,t){const{backend:n}=this;let r=!1,i=!0,s=0,a=0;for(const t of e.bindings){if(t.isNodeUniformsGroup){if(!1===this.nodes.updateGroup(t))continue}if(t.isStorageBuffer){const e=t.attribute,n=e.isIndirectStorageBufferAttribute?VM:zM;this.attributes.update(e,n)}if(t.isUniformBuffer){t.update()&&n.updateBinding(t)}else if(t.isSampler)t.update();else if(t.isSampledTexture){const e=this.textures.get(t.texture);t.needsBindingsUpdate(e.generation)&&(r=!0);const o=t.update(),l=t.texture;o&&this.textures.updateTexture(l);const u=n.get(l);if(void 0!==u.externalTexture||e.isDefaultTexture?i=!1:(s=10*s+l.id,a+=l.version),!0===n.isWebGPUBackend&&void 0===u.texture&&void 0===u.externalTexture&&(console.error("Bindings._update: binding should be available:",t,o,l,t.textureNode.value,r),this.textures.updateTexture(l),r=!0),!0===l.isStorageTexture){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)}}}!0===r&&this.backend.updateBindings(e,t,i?s:0,a)}}function tw(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 nw(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 rw(e){return(e.transmission>0||e.transmissionNode)&&2===e.side&&!1===e.forceSinglePass}class iw{constructor(e,t,n){this.renderItems=[],this.renderItemsIndex=0,this.opaque=[],this.transparentDoublePass=[],this.transparent=[],this.bundles=[],this.lightsNode=e.getNode(t,n),this.lightsArray=[],this.scene=t,this.camera=n,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,n,r,i,s,a){let o=this.renderItems[this.renderItemsIndex];return void 0===o?(o={id:e.id,object:e,geometry:t,material:n,groupOrder:r,renderOrder:e.renderOrder,z:i,group:s,clippingContext:a},this.renderItems[this.renderItemsIndex]=o):(o.id=e.id,o.object=e,o.geometry=t,o.material=n,o.groupOrder=r,o.renderOrder=e.renderOrder,o.z=i,o.group=s,o.clippingContext=a),this.renderItemsIndex++,o}push(e,t,n,r,i,s,a){const o=this.getNextRenderItem(e,t,n,r,i,s,a);!0===e.occlusionTest&&this.occlusionQueryCount++,!0===n.transparent||n.transmission>0?(rw(n)&&this.transparentDoublePass.push(o),this.transparent.push(o)):this.opaque.push(o)}unshift(e,t,n,r,i,s,a){const o=this.getNextRenderItem(e,t,n,r,i,s,a);!0===n.transparent||n.transmission>0?(rw(n)&&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||tw),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||nw),this.transparent.length>1&&this.transparent.sort(t||nw)}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 sw=[];class aw{constructor(e){this.lighting=e,this.lists=new LM}get(e,t){const n=this.lists;sw[0]=e,sw[1]=t;let r=n.get(sw);return void 0===r&&(r=new iw(this.lighting,e,t),n.set(sw,r)),sw.length=0,r}dispose(){this.lists=new LM}}let ow=0;class lw{constructor(){this.id=ow++,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 an,this.scissor=!1,this.scissorValue=new an,this.renderTarget=null,this.textures=null,this.depthTexture=null,this.activeCubeFace=0,this.activeMipmapLevel=0,this.sampleCount=1,this.width=0,this.height=0,this.occlusionQueryCount=0,this.clippingContext=null,this.isRenderContext=!0}getCacheKey(){return uw(this)}}function uw(e){const{textures:t,activeCubeFace:n}=e,r=[n];for(const e of t)r.push(e.id);return zp(r)}const cw=[],hw=new Li,dw=new xi;class pw{constructor(){this.chainMaps={}}get(e,t,n=null){let r;if(cw[0]=e,cw[1]=t,null===n)r="default";else{const e=n.texture.format;r=`${n.textures.length}:${e}:${n.samples}:${n.depthBuffer}:${n.stencilBuffer}`}const i=this._getChainMap(r);let s=i.get(cw);return void 0===s&&(s=new lw,i.set(cw,s)),cw.length=0,null!==n&&(s.sampleCount=0===n.samples?1:n.samples),s}getForClear(e=null){return this.get(hw,dw,e)}_getChainMap(e){return this.chainMaps[e]||(this.chainMaps[e]=new LM)}dispose(){this.chainMaps={}}}const fw=new Ut;class mw extends FM{constructor(e,t,n){super(),this.renderer=e,this.backend=t,this.info=n}updateRenderTarget(e,t=0){const n=this.get(e),r=0===e.samples?1:e.samples,i=n.depthTextureMips||(n.depthTextureMips={}),s=e.textures,a=this.getSize(s[0]),o=a.width>>t,l=a.height>>t;let u=e.depthTexture||i[t];const c=!0===e.depthBuffer||!0===e.stencilBuffer;let h=!1;void 0===u&&c&&(u=new os,u.format=e.stencilBuffer?ve:_e,u.type=e.stencilBuffer?de:oe,u.image.width=o,u.image.height=l,u.image.depth=a.depth,u.isArrayTexture=!0===e.multiview&&a.depth>1,i[t]=u),n.width===a.width&&a.height===n.height||(h=!0,u&&(u.needsUpdate=!0,u.image.width=o,u.image.height=l,u.image.depth=u.isArrayTexture?u.image.depth:1)),n.width=a.width,n.height=a.height,n.textures=s,n.depthTexture=u||null,n.depth=e.depthBuffer,n.stencil=e.stencilBuffer,n.renderTarget=e,n.sampleCount!==r&&(h=!0,u&&(u.needsUpdate=!0),n.sampleCount=r);const d={sampleCount:r};if(!0!==e.isXRRenderTarget){for(let e=0;e<s.length;e++){const t=s[e];h&&(t.needsUpdate=!0),this.updateTexture(t,d)}u&&this.updateTexture(u,d)}if(!0!==n.initialized){n.initialized=!0;const t=()=>{e.removeEventListener("dispose",t);for(let e=0;e<s.length;e++)this._destroyTexture(s[e]);u&&this._destroyTexture(u),this.delete(e)};e.addEventListener("dispose",t)}}updateTexture(e,t={}){const n=this.get(e);if(!0===n.initialized&&n.version===e.version)return;const r=e.isRenderTargetTexture||e.isDepthTexture||e.isFramebufferTexture,i=this.backend;if(r&&!0===n.initialized&&(i.destroySampler(e),i.destroyTexture(e)),e.isFramebufferTexture){const t=this.renderer.getRenderTarget();e.type=t?t.texture.type:ne}const{width:s,height:a,depth:o}=this.getSize(e);if(t.width=s,t.height=a,t.depth=o,t.needsMipmaps=this.needsMipmaps(e),t.levels=t.needsMipmaps?this.getMipLevels(e,s,a):1,r||!0===e.isStorageTexture)i.createSampler(e),i.createTexture(e,t),n.generation=e.version;else{if(!0!==n.initialized&&i.createSampler(e),e.version>0){const r=e.image;if(void 0===r)console.warn("THREE.Renderer: Texture marked for update but image is undefined.");else if(!1===r.complete)console.warn("THREE.Renderer: Texture marked for update but image is incomplete.");else{if(e.images){const n=[];for(const t of e.images)n.push(t);t.images=n}else t.image=r;void 0!==n.isDefaultTexture&&!0!==n.isDefaultTexture||(i.createTexture(e,t),n.isDefaultTexture=!1,n.generation=e.version),!0===e.source.dataReady&&i.updateTexture(e,t),t.needsMipmaps&&0===e.mipmaps.length&&i.generateMipmaps(e)}}else i.createDefaultTexture(e),n.isDefaultTexture=!0,n.generation=e.version}if(!0!==n.initialized){n.initialized=!0,n.generation=e.version,this.info.memory.textures++;const t=()=>{e.removeEventListener("dispose",t),this._destroyTexture(e)};e.addEventListener("dispose",t)}n.version=e.version}getSize(e,t=fw){let n=e.images?e.images[0]:e.image;return n?(void 0!==n.image&&(n=n.image),t.width=n.width||1,t.height=n.height||1,t.depth=e.isCubeTexture?6:n.depth||1):t.width=t.height=t.depth=1,t}getMipLevels(e,t,n){let r;return r=e.isCompressedTexture?e.mipmaps?e.mipmaps.length:1:Math.floor(Math.log2(Math.max(t,n)))+1,r}needsMipmaps(e){return!0===e.isCompressedTexture||e.generateMipmaps}_destroyTexture(e){!0===this.has(e)&&(this.backend.destroySampler(e),this.backend.destroyTexture(e),this.delete(e),this.info.memory.textures--)}}class gw extends Nr{constructor(e,t,n,r=1){super(e,t,n),this.a=r}set(e,t,n,r=1){return this.a=r,super.set(e,t,n)}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 _w extends Am{static get type(){return"ParameterNode"}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getHash(){return this.uuid}generate(){return this.name}}class vw extends uf{static get type(){return"StackNode"}constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this._expressionNode=null,this.isStackNode=!0}getNodeType(e){return this.outputNode?this.outputNode.getNodeType(e):"void"}getMemberType(e,t){return this.outputNode?this.outputNode.getMemberType(e,t):"void"}add(e){return this.nodes.push(e),this}If(e,t){const n=new Yf(t);return this._currentCond=j_(e,n),this.add(this._currentCond)}ElseIf(e,t){const n=new Yf(t),r=j_(e,n);return this._currentCond.elseNode=r,this._currentCond=r,this}Else(e){return this._currentCond.elseNode=new Yf(e),this}Switch(e){return this._expressionNode=Kf(e),this}Case(...e){const t=[];if(!(e.length>=2))throw new Error("TSL: Invalid parameter length. Case() requires at least two parameters.");for(let n=0;n<e.length-1;n++)t.push(this._expressionNode.equal(Kf(e[n])));const n=new Yf(e[e.length-1]);let r=t[0];for(let e=1;e<t.length;e++)r=r.or(t[e]);const i=j_(r,n);return null===this._currentCond?(this._currentCond=i,this.add(this._currentCond)):(this._currentCond.elseNode=i,this._currentCond=i,this)}Default(e){return this.Else(e),this}build(e,...t){const n=e.currentStack,r=im();rm(this),e.currentStack=this;const i=e.buildStage;for(const t of this.nodes)if("setup"===i)t.build(e);else if("analyze"===i)t.build(e,this);else if("generate"===i){const n=e.getDataFromNode(t,"any").stages,r=n&&n[e.shaderStage];if(t.isVarNode&&r&&1===r.length&&r[0]&&r[0].isStackNode)continue;t.build(e,"void")}const s=this.outputNode?this.outputNode.build(e,...t):super.build(e,...t);return rm(r),e.currentStack=n,s}}const yw=Jf(vw).setParameterLength(0,1);new Gi,new Ut,new Ut,new Ut,new Bn,new Ut(0,0,-1),new an,new Ut,new Ut,new an,new Dt;const xw=new on;Rb.flipX(),xw.depthTexture=new os(1,1);const bw=new na(-1,1,1,-1,0,1);class Tw extends ei{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new Xr([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new Xr(t,2))}}const Sw=new Tw;class Mw extends di{constructor(e=null){super(Sw,e),this.camera=bw,this.isQuadMesh=!0}async renderAsync(e){return e.renderAsync(this,bw)}render(e){e.render(this,bw)}}const ww=new $n,Ew=new Bn;class Aw extends uf{static get type(){return"SceneNode"}constructor(e=Aw.BACKGROUND_BLURRINESS,t=null){super(),this.scope=e,this.scene=t}setup(e){const t=this.scope,n=null!==this.scene?this.scene:e.scene;let r;return t===Aw.BACKGROUND_BLURRINESS?r=zy("backgroundBlurriness","float",n):t===Aw.BACKGROUND_INTENSITY?r=zy("backgroundIntensity","float",n):t===Aw.BACKGROUND_ROTATION?r=cg("mat4").label("backgroundRotation").setGroup(og).onRenderUpdate(()=>{const e=n.background;return null!==e&&e.isTexture&&300!==e.mapping?(ww.copy(n.backgroundRotation),ww.x*=-1,ww.y*=-1,ww.z*=-1,Ew.makeRotationFromEuler(ww)):Ew.identity(),Ew}):console.error("THREE.SceneNode: Unknown scope:",t),r}}Aw.BACKGROUND_BLURRINESS="backgroundBlurriness",Aw.BACKGROUND_INTENSITY="backgroundIntensity",Aw.BACKGROUND_ROTATION="backgroundRotation";const Rw=em(Aw,Aw.BACKGROUND_BLURRINESS),Cw=em(Aw,Aw.BACKGROUND_INTENSITY),Nw=em(Aw,Aw.BACKGROUND_ROTATION),Pw=nm(({texture:e,uv:t})=>{const n=1e-4,r=gm().toVar();return sm(t.x.lessThan(n),()=>{r.assign(gm(1,0,0))}).ElseIf(t.y.lessThan(n),()=>{r.assign(gm(0,1,0))}).ElseIf(t.z.lessThan(n),()=>{r.assign(gm(0,0,1))}).ElseIf(t.x.greaterThan(.9999),()=>{r.assign(gm(-1,0,0))}).ElseIf(t.y.greaterThan(.9999),()=>{r.assign(gm(0,-1,0))}).ElseIf(t.z.greaterThan(.9999),()=>{r.assign(gm(0,0,-1))}).Else(()=>{const n=.01,i=e.sample(t.add(gm(-.01,0,0))).r.sub(e.sample(t.add(gm(n,0,0))).r),s=e.sample(t.add(gm(0,-.01,0))).r.sub(e.sample(t.add(gm(0,n,0))).r),a=e.sample(t.add(gm(0,0,-.01))).r.sub(e.sample(t.add(gm(0,0,n))).r);r.assign(gm(i,s,a))}),r.normalize()});class Lw extends Dv{static get type(){return"Texture3DNode"}constructor(e,t=null,n=null){super(e,t,n),this.isTexture3DNode=!0}getInputType(){return"texture3D"}getDefaultUV(){return gm(.5,.5,.5)}setUpdateMatrix(){}setupUV(e,t){const n=this.value;return!e.isFlipY()||!0!==n.isRenderTargetTexture&&!0!==n.isFramebufferTexture||(t=this.sampler?t.flipY():t.setY(um(Cv(this,this.levelNode).y).sub(t.y).sub(1))),t}generateUV(e,t){return t.build(e,"vec3")}normal(e){return Pw({texture:this,uv:e})}}const Dw=Jf(Lw).setParameterLength(1,3),Iw=new Dt;class Uw extends Dv{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.setUpdateMatrix(!1)}setup(e){return e.object.isQuadMesh&&this.passNode.build(e),super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class Ow extends Uw{static get type(){return"PassMultipleTextureNode"}constructor(e,t,n=!1){super(e,null),this.textureName=t,this.previousTexture=n}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}}class Fw extends df{static get type(){return"PassNode"}constructor(e,t,n,r={}){super("vec4"),this.scope=e,this.scene=t,this.camera=n,this.options=r,this._pixelRatio=1,this._width=1,this._height=1;const i=new os;i.isRenderTargetTexture=!0,i.name="depth";const s=new on(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:ue,...r});s.texture.name="output",s.depthTexture=i,this.renderTarget=s,this._textures={output:s.texture,depth:i},this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=cg(0),this._cameraFar=cg(0),this._mrt=null,this._layers=null,this._resolution=1,this.isPassNode=!0,this.updateBeforeType=Qp,this.global=!0}setResolution(e){return this._resolution=e,this}getResolution(){return this._resolution}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 n=this._textures[e],r=this.renderTarget.textures.indexOf(n);this.renderTarget.textures[r]=t,this._textures[e]=t,this._previousTextures[e]=n,this._textureNodes[e].updateTexture(),this._previousTextureNodes[e].updateTexture()}}getTextureNode(e="output"){let t=this._textureNodes[e];return void 0===t&&(t=Kf(new Ow(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=Kf(new Ow(this,e,!0)),t.updateTexture(),this._previousTextureNodes[e]=t),t}getViewZNode(e="depth"){let t=this._viewZNodes[e];if(void 0===t){const n=this._cameraNear,r=this._cameraFar;this._viewZNodes[e]=t=Vb(this.getTextureNode(e),n,r)}return t}getLinearDepthNode(e="depth"){let t=this._linearDepthNodes[e];if(void 0===t){const n=this._cameraNear,r=this._cameraFar,i=this.getViewZNode(e);this._linearDepthNodes[e]=t=kb(i,n,r)}return t}setup({renderer:e}){return this.renderTarget.samples=void 0===this.options.samples?e.samples:this.options.samples,this.renderTarget.texture.type=e.getColorBufferType(),this.scope===Fw.COLOR?this.getTextureNode():this.getLinearDepthNode()}updateBefore(e){const{renderer:t}=e,{scene:n}=this;let r,i;const s=t.getOutputRenderTarget();s&&!0===s.isXRRenderTarget?(i=1,r=t.xr.getCamera(),t.xr.updateCamera(r),Iw.set(s.width,s.height)):(r=this.camera,i=t.getPixelRatio(),t.getSize(Iw)),this._pixelRatio=i,this.setSize(Iw.width,Iw.height);const a=t.getRenderTarget(),o=t.getMRT(),l=r.layers.mask;this._cameraNear.value=r.near,this._cameraFar.value=r.far,null!==this._layers&&(r.layers.mask=this._layers.mask);for(const e in this._previousTextures)this.toggleTexture(e);t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.render(n,r),t.setRenderTarget(a),t.setMRT(o),r.layers.mask=l}setSize(e,t){this._width=e,this._height=t;const n=this._width*this._pixelRatio*this._resolution,r=this._height*this._pixelRatio*this._resolution;this.renderTarget.setSize(n,r)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}Fw.COLOR="color",Fw.DEPTH="depth";const Bw=nm(([e,t])=>e.mul(t).clamp()).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),kw=nm(([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"}]}),zw=nm(([e,t])=>{const n=(e=(e=e.mul(t)).sub(.004).max(0)).mul(e.mul(6.2).add(.5)),r=e.mul(e.mul(6.2).add(1.7)).add(.06);return n.div(r).pow(2.2)}).setLayout({name:"cineonToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),Vw=nm(([e])=>{const t=e.mul(e.add(.0245786)).sub(90537e-9),n=e.mul(e.add(.432951).mul(.983729)).add(.238081);return t.div(n)}),Gw=nm(([e,t])=>{const n=wm(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),r=wm(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=n.mul(e),e=Vw(e),(e=r.mul(e)).clamp()}).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),Hw=wm(gm(1.6605,-.1246,-.0182),gm(-.5876,1.1329,-.1006),gm(-.0728,-.0083,1.1187)),jw=wm(gm(.6274,.0691,.0164),gm(.3293,.9195,.088),gm(.0433,.0113,.8956)),Ww=nm(([e])=>{const t=gm(e).toVar(),n=gm(t.mul(t)).toVar(),r=gm(n.mul(n)).toVar();return lm(15.5).mul(r.mul(n)).sub(vg(40.14,r.mul(t))).add(vg(31.96,r).sub(vg(6.868,n.mul(t))).add(vg(.4298,n).add(vg(.1191,t).sub(.00232))))}),Xw=nm(([e,t])=>{const n=gm(e).toVar(),r=wm(gm(.856627153315983,.137318972929847,.11189821299995),gm(.0951212405381588,.761241990602591,.0767994186031903),gm(.0482516061458583,.101439036467562,.811302368396859)),i=wm(gm(1.1271005818144368,-.1413297634984383,-.14132976349843826),gm(-.11060664309660323,1.157823702216272,-.11060664309660294),gm(-.016493938717834573,-.016493938717834257,1.2519364065950405)),s=lm(-12.47393),a=lm(4.026069);return n.mulAssign(t),n.assign(jw.mul(n)),n.assign(r.mul(n)),n.assign(S_(n,1e-10)),n.assign(Qg(n)),n.assign(n.sub(s).div(a.sub(s))),n.assign(F_(n,0,1)),n.assign(Ww(n)),n.assign(i.mul(n)),n.assign(N_(S_(gm(0),n),gm(2.2))),n.assign(Hw.mul(n)),n.assign(F_(n,0,1)),n}).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),qw=nm(([e,t])=>{const n=lm(.76),r=lm(.15);e=e.mul(t);const i=T_(e.r,T_(e.g,e.b)),s=j_(i.lessThan(.08),i.sub(vg(6.25,i.mul(i))),.04);e.subAssign(s);const a=S_(e.r,S_(e.g,e.b));sm(a.lessThan(n),()=>e);const o=_g(1,n),l=_g(1,o.mul(o).div(a.add(o.sub(n))));e.mulAssign(l.div(a));const u=_g(1,yg(1,r.mul(a.sub(l)).add(1)));return O_(e,gm(l),u)}).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class $w extends uf{static get type(){return"CodeNode"}constructor(e="",t=[],n=""){super("code"),this.isCodeNode=!0,this.global=!0,this.code=e,this.includes=t,this.language=n}setIncludes(e){return this.includes=e,this}getIncludes(){return this.includes}generate(e){const t=this.getIncludes(e);for(const n of t)n.build(e);const n=e.getCodeFromNode(this,this.getNodeType(e));return n.code=this.code,n.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 Yw extends $w{static get type(){return"FunctionNode"}constructor(e="",t=[],n=""){super(e,t,n)}getNodeType(e){return this.getNodeFunction(e).type}getInputs(e){return this.getNodeFunction(e).inputs}getNodeFunction(e){const t=e.getDataFromNode(this);let n=t.nodeFunction;return void 0===n&&(n=e.parser.parseFunction(this.code),t.nodeFunction=n),n}generate(e,t){super.generate(e);const n=this.getNodeFunction(e),r=n.name,i=n.type,s=e.getCodeFromNode(this,i);""!==r&&(s.name=r);const a=e.getPropertyName(s),o=this.getNodeFunction(e).getCode(a);return s.code=o+"\n","property"===t?a:e.format(`${a}()`,i,t)}}function Kw(e){let t;const n=e.context.getViewZ;return void 0!==n&&(t=n(this)),(t||cy.z).negate()}const Qw=nm(([e,t],n)=>{const r=Kw(n);return z_(e,t,r)}),Zw=nm(([e],t)=>{const n=Kw(t);return e.mul(e,n,n).negate().exp().oneMinus()}),Jw=nm(([e,t])=>xm(t.toFloat().mix($m.rgb,e.toVec3()),$m.a));Jf(class extends uf{constructor(e){super(),this.scope=e}generate(e){const{scope:t}=this,{renderer:n}=e;!0===n.backend.isWebGLBackend?e.addFlowCode(`\t// ${t}Barrier \n`):e.addLineFlowCode(`${t}Barrier()`,this)}});class eE extends uf{static get type(){return"AtomicFunctionNode"}constructor(e,t,n){super("uint"),this.method=e,this.pointerNode=t,this.valueNode=n,this.parents=!0}getInputType(e){return this.pointerNode.getNodeType(e)}getNodeType(e){return this.getInputType(e)}generate(e){const t=e.getNodeProperties(this),n=t.parents,r=this.method,i=this.getNodeType(e),s=this.getInputType(e),a=this.pointerNode,o=this.valueNode,l=[];l.push(`&${a.build(e,s)}`),null!==o&&l.push(o.build(e,s));const u=`${e.getMethod(r,i)}( ${l.join(", ")} )`;if(!(1===n.length&&!0===n[0].isStackNode))return void 0===t.constNode&&(t.constNode=Tv(u,i).toConst()),t.constNode.build(e);e.addLineFlowCode(u,this)}}let tE;function nE(e){tE=tE||new WeakMap;let t=tE.get(e);return void 0===t&&tE.set(e,t={}),t}function rE(e){const t=nE(e);return t.shadowMatrix||(t.shadowMatrix=cg("mat4").setGroup(og).onRenderUpdate(t=>(!0===e.castShadow&&!1!==t.renderer.shadowMap.enabled||e.shadow.updateMatrices(e),e.shadow.matrix)))}function iE(e){const t=nE(e);return t.position||(t.position=cg(new Ut).setGroup(og).onRenderUpdate((t,n)=>n.value.setFromMatrixPosition(e.matrixWorld)))}function sE(e){const t=nE(e);return t.viewPosition||(t.viewPosition=cg(new Ut).setGroup(og).onRenderUpdate(({camera:t},n)=>{n.value=n.value||new Ut,n.value.setFromMatrixPosition(e.matrixWorld),n.value.applyMatrix4(t.matrixWorldInverse)}))}eE.ATOMIC_LOAD="atomicLoad",eE.ATOMIC_STORE="atomicStore",eE.ATOMIC_ADD="atomicAdd",eE.ATOMIC_SUB="atomicSub",eE.ATOMIC_MAX="atomicMax",eE.ATOMIC_MIN="atomicMin",eE.ATOMIC_AND="atomicAnd",eE.ATOMIC_OR="atomicOr",eE.ATOMIC_XOR="atomicXor",Jf(eE);const aE=e=>qv.transformDirection(iE(e).sub(function(e){const t=nE(e);return t.targetPosition||(t.targetPosition=cg(new Ut).setGroup(og).onRenderUpdate((t,n)=>n.value.setFromMatrixPosition(e.target.matrixWorld)))}(e))),oE=(e,t)=>{for(const n of t)if(n.isAnalyticLightNode&&n.light.id===e)return n;return null},lE=new WeakMap,uE=[];class cE extends uf{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=Rm("vec3","totalDiffuse"),this.totalSpecularNode=Rm("vec3","totalSpecular"),this.outgoingLightNode=Rm("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 n=e[t];if(uE.push(n.id),uE.push(n.castShadow?1:0),!0===n.isSpotLight){const e=null!==n.map?n.map.id:-1,t=n.colorNode?n.colorNode.getCacheKey():-1;uE.push(e,t)}}const t=zp(uE);return uE.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.getSelf().getHash());this._lightNodesHash="lights-"+t.join(",")}return this._lightNodesHash}analyze(e){const t=e.getNodeProperties(this);for(const n of t.nodes)n.build(e);t.outputNode.build(e)}setupLightsNode(e){const t=[],n=this._lightNodes,r=(e=>e.sort((e,t)=>e.id-t.id))(this._lights),i=e.renderer.library;for(const e of r)if(e.isNode)t.push(Kf(e));else{let r=null;if(null!==n&&(r=oE(e.id,n)),null===r){const n=i.getLightNodeClass(e.constructor);if(null===n){console.warn(`LightsNode.setupNodeLights: Light node not found for ${e.constructor.name}`);continue}let r=null;lE.has(e)?r=lE.get(e):(r=Kf(new n(e)),lE.set(e,r)),t.push(r)}}this._lightNodes=t}setupDirectLight(e,t,n){const{lightingModel:r,reflectedLight:i}=e.context;r.direct({...n,lightNode:t,reflectedLight:i},e)}setupDirectRectAreaLight(e,t,n){const{lightingModel:r,reflectedLight:i}=e.context;r.directRectArea({...n,lightNode:t,reflectedLight:i},e)}setupLights(e,t){for(const n of t)n.build(e)}getLightNodes(e){return null===this._lightNodes&&this.setupLightsNode(e),this._lightNodes}setup(e){const t=e.lightsNode;e.lightsNode=this;let n=this.outgoingLightNode;const r=e.context,i=r.lightingModel,s=e.getNodeProperties(this);if(i){const{totalDiffuseNode:t,totalSpecularNode:a}=this;r.outgoingLight=n;const o=e.addStack();s.nodes=o.nodes,i.start(e);const{backdrop:l,backdropAlpha:u}=r,{directDiffuse:c,directSpecular:h,indirectDiffuse:d,indirectSpecular:p}=r.reflectedLight;let f=c.add(d);null!==l&&(f=gm(null!==u?u.mix(f,l):l),r.material.transparent=!0),t.assign(f),a.assign(h.add(p)),n.assign(t.add(a)),i.finish(e),n=n.bypass(e.removeStack())}else s.nodes=[];return e.lightsNode=t,n}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 hE extends uf{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=Zp,this.isShadowBaseNode=!0}setupShadowPosition({context:e,material:t}){dE.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||ly)}}const dE=Rm("vec3","shadowPositionWorld");function pE(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 Nr),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 fE=new WeakMap,mE=nm(({depthTexture:e,shadowCoord:t,depthLayer:n})=>{let r=Uv(e,t.xy).label("t_basic");return e.isArrayTexture&&(r=r.depth(n)),r.compare(t.z)}),gE=nm(({depthTexture:e,shadowCoord:t,shadow:n,depthLayer:r})=>{const i=(t,n)=>{let i=Uv(e,t);return e.isArrayTexture&&(i=i.depth(r)),i.compare(n)},s=zy("mapSize","vec2",n).setGroup(og),a=zy("radius","float",n).setGroup(og),o=dm(1).div(s),l=o.x.negate().mul(a),u=o.y.negate().mul(a),c=o.x.mul(a),h=o.y.mul(a),d=l.div(2),p=u.div(2),f=c.div(2),m=h.div(2);return gg(i(t.xy.add(dm(l,u)),t.z),i(t.xy.add(dm(0,u)),t.z),i(t.xy.add(dm(c,u)),t.z),i(t.xy.add(dm(d,p)),t.z),i(t.xy.add(dm(0,p)),t.z),i(t.xy.add(dm(f,p)),t.z),i(t.xy.add(dm(l,0)),t.z),i(t.xy.add(dm(d,0)),t.z),i(t.xy,t.z),i(t.xy.add(dm(f,0)),t.z),i(t.xy.add(dm(c,0)),t.z),i(t.xy.add(dm(d,m)),t.z),i(t.xy.add(dm(0,m)),t.z),i(t.xy.add(dm(f,m)),t.z),i(t.xy.add(dm(l,h)),t.z),i(t.xy.add(dm(0,h)),t.z),i(t.xy.add(dm(c,h)),t.z)).mul(1/17)}),_E=nm(({depthTexture:e,shadowCoord:t,shadow:n,depthLayer:r})=>{const i=(t,n)=>{let i=Uv(e,t);return e.isArrayTexture&&(i=i.depth(r)),i.compare(n)},s=zy("mapSize","vec2",n).setGroup(og),a=dm(1).div(s),o=a.x,l=a.y,u=t.xy,c=r_(u.mul(s).add(.5));return u.subAssign(c.mul(a)),gg(i(u,t.z),i(u.add(dm(o,0)),t.z),i(u.add(dm(0,l)),t.z),i(u.add(a),t.z),O_(i(u.add(dm(o.negate(),0)),t.z),i(u.add(dm(o.mul(2),0)),t.z),c.x),O_(i(u.add(dm(o.negate(),l)),t.z),i(u.add(dm(o.mul(2),l)),t.z),c.x),O_(i(u.add(dm(0,l.negate())),t.z),i(u.add(dm(0,l.mul(2))),t.z),c.y),O_(i(u.add(dm(o,l.negate())),t.z),i(u.add(dm(o,l.mul(2))),t.z),c.y),O_(O_(i(u.add(dm(o.negate(),l.negate())),t.z),i(u.add(dm(o.mul(2),l.negate())),t.z),c.x),O_(i(u.add(dm(o.negate(),l.mul(2))),t.z),i(u.add(dm(o.mul(2),l.mul(2))),t.z),c.x),c.y)).mul(1/9)}),vE=nm(({depthTexture:e,shadowCoord:t,depthLayer:n})=>{const r=lm(1).toVar();let i=Uv(e).sample(t.xy);e.isArrayTexture&&(i=i.depth(n)),i=i.rg;const s=M_(t.z,i.x);return sm(s.notEqual(lm(1)),()=>{const e=t.z.sub(i.x),n=S_(0,i.y.mul(i.y));let a=n.div(n.add(e.mul(e)));a=F_(_g(a,.3).div(.95-.3)),r.assign(F_(S_(s,a)))}),r}),yE=nm(([e,t,n])=>{let r=ly.sub(e).length();return r=r.sub(t).div(n.sub(t)),r=r.saturate(),r}),xE=e=>{let t=fE.get(e);if(void 0===t){const n=e.isPointLight?(e=>{const t=e.shadow.camera,n=zy("near","float",t).setGroup(og),r=zy("far","float",t).setGroup(og),i=Qv(e);return yE(i,n,r)})(e):null;t=new Qb,t.colorNode=xm(0,0,0,1),t.depthNode=n,t.isShadowPassMaterial=!0,t.name="ShadowMaterial",t.fog=!1,fE.set(e,t)}return t},bE=new LM,TE=[],SE=nm(({samples:e,radius:t,size:n,shadowPass:r,depthLayer:i})=>{const s=lm(0).toVar("meanVertical"),a=lm(0).toVar("squareMeanVertical"),o=e.lessThanEqual(lm(1)).select(lm(0),lm(2).div(e.sub(1))),l=e.lessThanEqual(lm(1)).select(lm(0),lm(-1));fb({start:um(0),end:um(e),type:"int",condition:"<"},({i:e})=>{const u=l.add(lm(e).mul(o));let c=r.sample(gg(Nb.xy,dm(0,u).mul(t)).div(n));r.value.isArrayTexture&&(c=c.depth(i)),c=c.x,s.addAssign(c),a.addAssign(c.mul(c))}),s.divAssign(e),a.divAssign(e);const u=Zg(a.sub(s.mul(s)));return dm(s,u)}),ME=nm(({samples:e,radius:t,size:n,shadowPass:r,depthLayer:i})=>{const s=lm(0).toVar("meanHorizontal"),a=lm(0).toVar("squareMeanHorizontal"),o=e.lessThanEqual(lm(1)).select(lm(0),lm(2).div(e.sub(1))),l=e.lessThanEqual(lm(1)).select(lm(0),lm(-1));fb({start:um(0),end:um(e),type:"int",condition:"<"},({i:e})=>{const u=l.add(lm(e).mul(o));let c=r.sample(gg(Nb.xy,dm(u,0).mul(t)).div(n));r.value.isArrayTexture&&(c=c.depth(i)),s.addAssign(c.x),a.addAssign(gg(c.y.mul(c.y),c.x.mul(c.x)))}),s.divAssign(e),a.divAssign(e);const u=Zg(a.sub(s.mul(s)));return dm(s,u)}),wE=[mE,gE,_E,vE];let EE;const AE=new Mw;class RE extends hE{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._cameraFrameId=new WeakMap,this.isShadowNode=!0,this.depthLayer=0}setupShadowFilter(e,{filterFn:t,depthTexture:n,shadowCoord:r,shadow:i,depthLayer:s}){const a=r.x.greaterThanEqual(0).and(r.x.lessThanEqual(1)).and(r.y.greaterThanEqual(0)).and(r.y.lessThanEqual(1)).and(r.z.lessThanEqual(1)),o=t({depthTexture:n,shadowCoord:r,shadow:i,depthLayer:s});return a.select(o,lm(1))}setupShadowCoord(e,t){const{shadow:n}=this,{renderer:r}=e,i=zy("bias","float",n).setGroup(og);let s,a=t;if(n.camera.isOrthographicCamera||!0!==r.logarithmicDepthBuffer)a=a.xyz.div(a.w),s=a.z,r.coordinateSystem===xt&&(s=s.mul(2).sub(1));else{const e=a.w;a=a.xy.div(e);const t=zy("near","float",n.camera).setGroup(og),r=zy("far","float",n.camera).setGroup(og);s=Gb(e.negate(),t,r)}return a=gm(a.x,a.y.oneMinus(),s.add(i)),a}getShadowFilterFn(e){return wE[e]}setupRenderTarget(e,t){const n=new os(e.mapSize.width,e.mapSize.height);n.name="ShadowDepthTexture",n.compareFunction=ut;const r=t.createRenderTarget(e.mapSize.width,e.mapSize.height);return r.texture.name="ShadowMap",r.texture.type=e.mapType,r.depthTexture=n,{shadowMap:r,depthTexture:n}}setupShadow(e){const{renderer:t}=e,{light:n,shadow:r}=this,i=t.shadowMap.type,{depthTexture:s,shadowMap:a}=this.setupRenderTarget(r,e);if(r.camera.updateProjectionMatrix(),3===i&&!0!==r.isPointLightShadow){s.compareFunction=null,a.depth>1?(a._vsmShadowMapVertical||(a._vsmShadowMapVertical=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:be,type:ue,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:be,type:ue,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:be,type:ue,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:be,type:ue,depthBuffer:!1}));let t=Uv(s);s.isArrayTexture&&(t=t.depth(this.depthLayer));let n=Uv(this.vsmShadowMapVertical.texture);s.isArrayTexture&&(n=n.depth(this.depthLayer));const i=zy("blurSamples","float",r).setGroup(og),o=zy("radius","float",r).setGroup(og),l=zy("mapSize","vec2",r).setGroup(og);let u=this.vsmMaterialVertical||(this.vsmMaterialVertical=new Qb);u.fragmentNode=SE({samples:i,radius:o,size:l,shadowPass:t,depthLayer:this.depthLayer}).context(e.getSharedContext()),u.name="VSMVertical",u=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new Qb),u.fragmentNode=ME({samples:i,radius:o,size:l,shadowPass:n,depthLayer:this.depthLayer}).context(e.getSharedContext()),u.name="VSMHorizontal"}const o=zy("intensity","float",r).setGroup(og),l=zy("normalBias","float",r).setGroup(og),u=rE(n).mul(dE.add(by.mul(l))),c=this.setupShadowCoord(e,u),h=r.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(null===h)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const d=3===i&&!0!==r.isPointLightShadow?this.vsmShadowMapHorizontal.texture:s,p=this.setupShadowFilter(e,{filterFn:h,shadowTexture:a.texture,depthTexture:d,shadowCoord:c,shadow:r,depthLayer:this.depthLayer});let f=Uv(a.texture,c);s.isArrayTexture&&(f=f.depth(this.depthLayer));const m=O_(1,p.rgb.mix(f,1),o.mul(f.a)).toVar();return this.shadowMap=a,this.shadow.map=a,m}setup(e){if(!1!==e.renderer.shadowMap.enabled)return nm(()=>{let t=this._node;return this.setupShadowPosition(e),null===t&&(this._node=t=this.setupShadow(e)),e.material.shadowNode&&console.warn('THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.'),e.material.receivedShadowNode&&(t=e.material.receivedShadowNode(t)),t})()}renderShadow(e){const{shadow:t,shadowMap:n,light:r}=this,{renderer:i,scene:s}=e;t.updateMatrices(r),n.setSize(t.mapSize.width,t.mapSize.height,n.depth),i.render(s,t.camera)}updateShadow(e){const{shadowMap:t,light:n,shadow:r}=this,{renderer:i,scene:s,camera:a}=e,o=i.shadowMap.type,l=t.depthTexture.version;this._depthVersionCached=l;const u=r.camera.layers.mask;4294967294&r.camera.layers.mask||(r.camera.layers.mask=a.layers.mask);const c=i.getRenderObjectFunction(),h=i.getMRT(),d=!!h&&h.has("velocity");EE=function(e,t,n){return n=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,n=pE(e,n)),n}(i,s,EE),s.overrideMaterial=xE(n),i.setRenderObjectFunction(((e,t,n,r)=>{TE[0]=e,TE[1]=t;let i=bE.get(TE);return void 0!==i&&i.shadowType===n&&i.useVelocity===r||(i=(i,s,a,o,l,u,...c)=>{(!0===i.castShadow||i.receiveShadow&&3===n)&&(r&&($p(i).useVelocity=!0),i.onBeforeShadow(e,i,a,t.camera,o,s.overrideMaterial,u),e.renderObject(i,s,a,o,l,u,...c),i.onAfterShadow(e,i,a,t.camera,o,s.overrideMaterial,u))},i.shadowType=n,i.useVelocity=r,bE.set(TE,i)),TE[0]=null,TE[1]=null,i})(i,r,o,d)),i.setClearColor(0,0),i.setRenderTarget(t),this.renderShadow(e),i.setRenderObjectFunction(c),3===o&&!0!==r.isPointLightShadow&&this.vsmPass(i),r.camera.layers.mask=u,function(e,t,n){!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,n),function(e,t){e.background=t.background,e.backgroundNode=t.backgroundNode,e.overrideMaterial=t.overrideMaterial}(t,n)}(i,s,EE)}vsmPass(e){const{shadow:t}=this,n=this.shadowMap.depth;this.vsmShadowMapVertical.setSize(t.mapSize.width,t.mapSize.height,n),this.vsmShadowMapHorizontal.setSize(t.mapSize.width,t.mapSize.height,n),e.setRenderTarget(this.vsmShadowMapVertical),AE.material=this.vsmMaterialVertical,AE.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),AE.material=this.vsmMaterialHorizontal,AE.render(e)}dispose(){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),super.dispose()}updateBefore(e){const{shadow:t}=this;let n=t.needsUpdate||t.autoUpdate;n&&(this._cameraFrameId[e.camera]===e.frameId&&(n=!1),this._cameraFrameId[e.camera]=e.frameId),n&&(this.updateShadow(e),this.shadowMap.depthTexture.version===this._depthVersionCached&&(t.needsUpdate=!1))}}const CE=new Nr,NE=nm(([e,t])=>{const n=e.toVar(),r=c_(n),i=yg(1,S_(r.x,S_(r.y,r.z)));r.mulAssign(i),n.mulAssign(i.mul(t.mul(2).oneMinus()));const s=dm(n.xy).toVar(),a=t.mul(1.5).oneMinus();return sm(r.z.greaterThanEqual(a),()=>{sm(n.z.greaterThan(0),()=>{s.x.assign(_g(4,n.x))})}).ElseIf(r.x.greaterThanEqual(a),()=>{const e=h_(n.x);s.x.assign(n.z.mul(e).add(e.mul(2)))}).ElseIf(r.y.greaterThanEqual(a),()=>{const e=h_(n.y);s.x.assign(n.x.add(e.mul(2)).add(2)),s.y.assign(n.z.mul(e).sub(2))}),dm(.125,.25).mul(s).add(dm(.375,.75)).flipY()}).setLayout({name:"cubeToUV",type:"vec2",inputs:[{name:"pos",type:"vec3"},{name:"texelSizeY",type:"float"}]}),PE=nm(({depthTexture:e,bd3D:t,dp:n,texelSize:r})=>Uv(e,NE(t,r.y)).compare(n)),LE=nm(({depthTexture:e,bd3D:t,dp:n,texelSize:r,shadow:i})=>{const s=zy("radius","float",i).setGroup(og),a=dm(-1,1).mul(s).mul(r.y);return Uv(e,NE(t.add(a.xyy),r.y)).compare(n).add(Uv(e,NE(t.add(a.yyy),r.y)).compare(n)).add(Uv(e,NE(t.add(a.xyx),r.y)).compare(n)).add(Uv(e,NE(t.add(a.yyx),r.y)).compare(n)).add(Uv(e,NE(t,r.y)).compare(n)).add(Uv(e,NE(t.add(a.xxy),r.y)).compare(n)).add(Uv(e,NE(t.add(a.yxy),r.y)).compare(n)).add(Uv(e,NE(t.add(a.xxx),r.y)).compare(n)).add(Uv(e,NE(t.add(a.yxx),r.y)).compare(n)).mul(1/9)}),DE=nm(({filterFn:e,depthTexture:t,shadowCoord:n,shadow:r})=>{const i=n.xyz.toVar(),s=i.length(),a=cg("float").setGroup(og).onRenderUpdate(()=>r.camera.near),o=cg("float").setGroup(og).onRenderUpdate(()=>r.camera.far),l=zy("bias","float",r).setGroup(og),u=cg(r.mapSize).setGroup(og),c=lm(1).toVar();return sm(s.sub(o).lessThanEqual(0).and(s.sub(a).greaterThanEqual(0)),()=>{const n=s.sub(a).div(o.sub(a)).toVar();n.addAssign(l);const h=i.normalize(),d=dm(1).div(u.mul(dm(4,2)));c.assign(e({depthTexture:t,bd3D:h,dp:n,texelSize:d,shadow:r}))}),c}),IE=new an,UE=new Dt,OE=new Dt;class FE extends RE{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return 0===e?PE:LE}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,shadowTexture:n,depthTexture:r,shadowCoord:i,shadow:s}){return DE({filterFn:t,shadowTexture:n,depthTexture:r,shadowCoord:i,shadow:s})}renderShadow(e){const{shadow:t,shadowMap:n,light:r}=this,{renderer:i,scene:s}=e,a=t.getFrameExtents();OE.copy(t.mapSize),OE.multiply(a),n.setSize(OE.width,OE.height),UE.copy(t.mapSize);const o=i.autoClear,l=i.getClearColor(CE),u=i.getClearAlpha();i.autoClear=!1,i.setClearColor(t.clearColor,t.clearAlpha),i.clear();const c=t.getViewportCount();for(let e=0;e<c;e++){const a=t.getViewport(e),o=UE.x*a.x,l=OE.y-UE.y-UE.y*a.y;IE.set(o,l,UE.x*a.z,UE.y*a.w),n.viewport.copy(IE),t.updateMatrices(r,e),i.render(s,t.camera)}i.autoClear=o,i.setClearColor(l,u)}}class BE extends xb{static get type(){return"AnalyticLightNode"}constructor(e=null){super(),this.light=e,this.color=new Nr,this.colorNode=e&&e.colorNode||cg(this.color).setGroup(og),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=Qp}getHash(){return this.light.uuid}getLightVector(e){return sE(this.light).sub(e.context.positionView||cy)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return((e,t)=>Kf(new RE(e,t)))(this.light)}setupShadow(e){const{renderer:t}=e;if(!1===t.shadowMap.enabled)return;let n=this.shadowColorNode;if(null===n){const e=this.light.shadow.shadowNode;let t;t=void 0!==e?Kf(e):this.setupShadowNode(),this.shadowNode=t,this.shadowColorNode=n=this.colorNode.mul(t),this.baseColorNode=this.colorNode}this.colorNode=n}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),n=this.setupDirectRectArea(e);t&&e.lightsNode.setupDirectLight(e,this,t),n&&e.lightsNode.setupDirectRectAreaLight(e,this,n)}update(){const{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}}const kE=nm(({lightDistance:e,cutoffDistance:t,decayExponent:n})=>{const r=e.pow(n).max(.01).reciprocal();return t.greaterThan(0).select(r.mul(e.div(t).pow4().oneMinus().clamp().pow2()),r)});class zE extends BE{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=cg(0).setGroup(og),this.decayExponentNode=cg(2).setGroup(og)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return((e,t)=>Kf(new FE(e,t)))(this.light)}setupDirect(e){return(({color:e,lightVector:t,cutoffDistance:n,decayExponent:r})=>{const i=t.normalize(),s=t.length(),a=kE({lightDistance:s,cutoffDistance:n,decayExponent:r});return{lightDirection:i,lightColor:e.mul(a)}})({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}}nm(([e=Av()],{renderer:t,material:n})=>{const r=U_(e.mul(2).sub(1));let i;if(n.alphaToCoverage&&t.samples>1){const e=lm(r.fwidth()).toVar();i=z_(e.oneMinus(),e.add(1),r).oneMinus()}else i=j_(r.greaterThan(1),0,1);return i});const VE=nm(([e,t])=>{const n=e.x,r=e.y,i=e.z;let s=t.element(0).mul(.886227);return s=s.add(t.element(1).mul(1.023328).mul(r)),s=s.add(t.element(2).mul(1.023328).mul(i)),s=s.add(t.element(3).mul(1.023328).mul(n)),s=s.add(t.element(4).mul(.858086).mul(n).mul(r)),s=s.add(t.element(5).mul(.858086).mul(r).mul(i)),s=s.add(t.element(6).mul(i.mul(i).mul(.743125).sub(.247708))),s=s.add(t.element(7).mul(.858086).mul(n).mul(i)),s=s.add(t.element(8).mul(.429043).mul(vg(n,n).sub(vg(r,r)))),s}),GE=new gw;class HE extends FM{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,n){const r=this.renderer,i=this.nodes.getBackgroundNode(e)||e.background;let s=!1;if(null===i)r._clearColor.getRGB(GE),GE.a=r._clearColor.a;else if(!0===i.isColor)i.getRGB(GE),GE.a=1,s=!0;else if(!0===i.isNode){const o=this.get(e),l=i;GE.copy(r._clearColor);let u=o.backgroundMesh;if(void 0===u){const h=X_(xm(l).mul(Cw),{getUV:()=>Nw.mul(yy),getTextureLevel:()=>Rw});let d=tb;d=d.setZ(d.w);const p=new Qb;function f(){i.removeEventListener("dispose",f),u.material.dispose(),u.geometry.dispose()}p.name="Background.material",p.side=1,p.depthTest=!1,p.depthWrite=!1,p.allowOverride=!1,p.fog=!1,p.lights=!1,p.vertexNode=d,p.colorNode=h,o.backgroundMeshNode=h,o.backgroundMesh=u=new di(new Ms(1,32,32),p),u.frustumCulled=!1,u.name="Background.mesh",u.onBeforeRender=function(e,t,n){this.matrixWorld.copyPosition(n.matrixWorld)},i.addEventListener("dispose",f)}const c=l.getCacheKey();o.backgroundCacheKey!==c&&(o.backgroundMeshNode.node=xm(l).mul(Cw),o.backgroundMeshNode.needsUpdate=!0,u.material.needsUpdate=!0,o.backgroundCacheKey=c),t.unshift(u,u.geometry,u.material,0,0,null,null)}else console.error("THREE.Renderer: Unsupported background configuration.",i);const a=r.xr.getEnvironmentBlendMode();if("additive"===a?GE.set(0,0,0,1):"alpha-blend"===a&&GE.set(0,0,0,0),!0===r.autoClear||!0===s){const m=n.clearColorValue;m.r=GE.r,m.g=GE.g,m.b=GE.b,m.a=GE.a,!0!==r.backend.isWebGLBackend&&!0!==r.alpha||(m.r*=m.a,m.g*=m.a,m.b*=m.a),n.depthClearValue=r._clearDepth,n.stencilClearValue=r._clearStencil,n.clearColor=!0===r.autoClearColor,n.clearDepth=!0===r.autoClearDepth,n.clearStencil=!0===r.autoClearStencil}else n.clearColor=!1,n.clearDepth=!1,n.clearStencil=!1}}let jE=0;class WE{constructor(e="",t=[],n=0,r=[]){this.name=e,this.bindings=t,this.index=n,this.bindingsReference=r,this.id=jE++}}class XE{constructor(e,t,n,r,i,s,a,o,l,u=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=n,this.transforms=u,this.nodeAttributes=r,this.bindings=i,this.updateNodes=s,this.updateBeforeNodes=a,this.updateAfterNodes=o,this.observer=l,this.usedTimes=0}createBindings(){const e=[];for(const t of this.bindings){if(!0!==t.bindings[0].groupNode.shared){const n=new WE(t.name,[],t.index,t);e.push(n);for(const e of t.bindings)n.bindings.push(e.clone())}else e.push(t)}return e}}class qE{constructor(e,t,n=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=n}}class $E{constructor(e,t,n){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=n.getSelf()}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 YE{constructor(e,t,n=!1,r=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=n,this.count=r}}class KE extends YE{constructor(e,t,n=null,r=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=n,this.interpolationSampling=r}}class QE{constructor(e,t,n=""){this.name=e,this.type=t,this.code=n,Object.defineProperty(this,"isNodeCode",{value:!0})}}let ZE=0;class JE{constructor(e=null){this.id=ZE++,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 eA{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class tA{constructor(e,t){this.name=e,this.value=t,this.boundary=0,this.itemSize=0,this.offset=0}setValue(e){this.value=e}getValue(){return this.value}}class nA extends tA{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class rA extends tA{constructor(e,t=new Dt){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class iA extends tA{constructor(e,t=new Ut){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class sA extends tA{constructor(e,t=new an){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class aA extends tA{constructor(e,t=new Nr){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class oA extends tA{constructor(e,t=new _a){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}}class lA extends tA{constructor(e,t=new Bt){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class uA extends tA{constructor(e,t=new Bn){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class cA extends nA{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class hA extends rA{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class dA extends iA{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class pA extends sA{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class fA extends aA{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class mA extends oA{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class gA extends lA{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class _A extends uA{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}const vA=new WeakMap,yA=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),xA=e=>/e/g.test(e)?String(e).replace(/\+/g,""):(e=Number(e))+(e%1?"":".0");class bA{constructor(e,t,n){this.object=e,this.material=e&&e.material||null,this.geometry=e&&e.geometry||null,this.renderer=t,this.parser=n,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.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=yw(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new JE,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null,this.subBuildLayers=[],this.currentStack=null,this.subBuildFn=null}getBindGroupsCache(){let e=vA.get(this.renderer);return void 0===e&&(e=new LM,vA.set(this.renderer,e)),e}createRenderTarget(e,t,n){return new on(e,t,n)}createCubeRenderTarget(e,t){return new sT(e,t)}includes(e){return this.nodes.includes(e)}getOutputStructName(){}_getBindGroup(e,t){const n=this.getBindGroupsCache(),r=[];let i,s=!0;for(const e of t)r.push(e),s=s&&!0!==e.groupNode.shared;return s?(i=n.get(r),void 0===i&&(i=new WE(e,r,this.bindingsIndexes[e].group,r),n.set(r,i))):i=new WE(e,r,this.bindingsIndexes[e].group,r),i}getBindGroupArray(e,t){const n=this.bindings[t];let r=n[e];return void 0===r&&(void 0===this.bindingsIndexes[e]&&(this.bindingsIndexes[e]={binding:0,group:Object.keys(this.bindingsIndexes).length}),n[e]=r=[]),r}getBindings(){let e=this.bindGroups;if(null===e){const t={},n=this.bindings;for(const e of sf)for(const r in n[e]){const i=n[e][r];(t[r]||(t[r]=[])).push(...i)}e=[];for(const n in t){const r=t[n],i=this._getBindGroup(n,r);e.push(i)}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 n=e[t];this.bindingsIndexes[n.name].group=t,n.index=t}}setHashNode(e,t){this.hashNodes[t]=e}addNode(e){!1===this.nodes.includes(e)&&(this.nodes.push(e),this.setHashNode(e,e.getHash(this)))}addSequentialNode(e){!1===this.sequentialNodes.includes(e)&&this.sequentialNodes.push(e)}buildUpdateNodes(){for(const e of this.nodes){e.getUpdateType()!==Kp&&this.updateNodes.push(e.getSelf())}for(const e of this.sequentialNodes){const t=e.getUpdateBeforeType(),n=e.getUpdateAfterType();t!==Kp&&this.updateBeforeNodes.push(e.getSelf()),n!==Kp&&this.updateAfterNodes.push(e.getSelf())}}get currentNode(){return this.chaining[this.chaining.length-1]}isFilteredTexture(e){return e.magFilter===J||e.magFilter===ee||e.magFilter===Z||e.magFilter===te||e.minFilter===J||e.minFilter===ee||e.minFilter===Z||e.minFilter===te}addChain(e){this.chaining.push(e)}removeChain(e){if(this.chaining.pop()!==e)throw new Error("NodeBuilder: Invalid node chaining!")}getMethod(e){return e}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}getSharedContext(){return this.context,this.context}setCache(e){this.cache=e}getCache(){return this.cache}getCacheFromNode(e,t=!0){const n=this.getDataFromNode(e);return void 0===n.cache&&(n.cache=new JE(t?this.getCache():null)),n.cache}isAvailable(){return!1}getVertexIndex(){console.warn("Abstract function.")}getInstanceIndex(){console.warn("Abstract function.")}getDrawIndex(){console.warn("Abstract function.")}getFrontFacing(){console.warn("Abstract function.")}getFragCoord(){console.warn("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(){console.warn("Abstract function.")}generateTextureLod(){console.warn("Abstract function.")}generateArrayDeclaration(e,t){return this.getType(e)+"[ "+t+" ]"}generateArray(e,t,n=null){let r=this.generateArrayDeclaration(e,t)+"( ";for(let i=0;i<t;i++){const s=n?n[i]:null;r+=null!==s?s.build(this,e):this.generateConst(e),i<t-1&&(r+=", ")}return r+=" )",r}generateStruct(e,t,n=null){const r=[];for(const e of t){const{name:t,type:i}=e;n&&n[t]&&n[t].isNode?r.push(n[t].build(this,i)):r.push(this.generateConst(i))}return e+"( "+r.join(", ")+" )"}generateConst(e,t=null){if(null===t&&("float"===e||"int"===e||"uint"===e?t=0:"bool"===e?t=!1:"color"===e?t=new Nr:"vec2"===e?t=new Dt:"vec3"===e?t=new Ut:"vec4"===e&&(t=new an)),"float"===e)return xA(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")}( ${xA(t.r)}, ${xA(t.g)}, ${xA(t.b)} )`;const n=this.getTypeLength(e),r=this.getComponentType(e),i=e=>this.generateConst(r,e);if(2===n)return`${this.getType(e)}( ${i(t.x)}, ${i(t.y)} )`;if(3===n)return`${this.getType(e)}( ${i(t.x)}, ${i(t.y)}, ${i(t.z)} )`;if(4===n&&"mat2"!==e)return`${this.getType(e)}( ${i(t.x)}, ${i(t.y)}, ${i(t.z)}, ${i(t.w)} )`;if(n>=4&&t&&(t.isMatrix2||t.isMatrix3||t.isMatrix4))return`${this.getType(e)}( ${t.elements.map(i).join(", ")} )`;if(n>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 n=this.attributes;for(const t of n)if(t.name===e)return t;const r=new qE(e,t);return this.registerDeclaration(r),n.push(r),r}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===ae)return"int";if(t===oe)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 n=function(e){return jp.get(e)}(e);const r="float"===t?"":t[0];return!0===/mat2/.test(t)&&(n=n.replace("vec","mat")),r+n}getTypeFromArray(e){return yA.get(e.constructor)}isInteger(e){return/int|uint|(i|u)vec/.test(e)}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);const n=t.array,r=e.itemSize,i=e.normalized;let s;return e instanceof Wr||!0===i||(s=this.getTypeFromArray(n)),this.getTypeFromLength(r,s)}getTypeLength(e){const t=this.getVectorType(e),n=/vec([2-4])/.exec(t);return null!==n?Number(n[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")}addStack(){return this.stack=yw(this.stack),this.stacks.push(im()||this.stack),rm(this.stack),this.stack}removeStack(){const e=this.stack;return this.stack=e.parent,rm(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,n=null){let r=(n=null===n?e.isGlobal(this)?this.globalCache:this.cache:n).getData(e);void 0===r&&(r={},n.setData(e,r)),void 0===r[t]&&(r[t]={});let i=r[t];const s=r.any?r.any.subBuilds:null,a=this.getClosestSubBuild(s);return a&&(void 0===i.subBuildsCache&&(i.subBuildsCache={}),i=i.subBuildsCache[a]||(i.subBuildsCache[a]={}),i.subBuilds=s),i}getNodeProperties(e,t="any"){const n=this.getDataFromNode(e,t);return n.properties||(n.properties={outputNode:null})}getBufferAttributeFromNode(e,t){const n=this.getDataFromNode(e);let r=n.bufferAttribute;if(void 0===r){const i=this.uniforms.index++;r=new qE("nodeAttribute"+i,t,e),this.bufferAttributes.push(r),n.bufferAttribute=r}return r}getStructTypeFromNode(e,t,n=null,r=this.shaderStage){const i=this.getDataFromNode(e,r,this.globalCache);let s=i.structType;if(void 0===s){const e=this.structs.index++;null===n&&(n="StructType"+e),s=new eA(n,t),this.structs[r].push(s),i.structType=s}return s}getOutputStructTypeFromNode(e,t){const n=this.getStructTypeFromNode(e,t,"OutputType","fragment");return n.output=!0,n}getUniformFromNode(e,t,n=this.shaderStage,r=null){const i=this.getDataFromNode(e,n,this.globalCache);let s=i.uniform;if(void 0===s){const a=this.uniforms.index++;s=new $E(r||"nodeUniform"+a,t,e),this.uniforms[n].push(s),this.registerDeclaration(s),i.uniform=s}return s}getArrayCount(e){let t=null;return e.isArrayNode?t=e.count:e.isVarNode&&e.node.isArrayNode&&(t=e.node.count),t}getVarFromNode(e,t=null,n=e.getNodeType(this),r=this.shaderStage,i=!1){const s=this.getDataFromNode(e,r),a=this.getSubBuildProperty("variable",s.subBuilds);let o=s[a];if(void 0===o){const l=i?"_const":"_var",u=this.vars[r]||(this.vars[r]=[]),c=this.vars[l]||(this.vars[l]=0);null===t&&(t=(i?"nodeConst":"nodeVar")+c,this.vars[l]++),"variable"!==a&&(t=this.getSubBuildProperty(t,s.subBuilds));const h=this.getArrayCount(e);o=new YE(t,n,i,h),i||u.push(o),this.registerDeclaration(o),s[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,n=e.getNodeType(this),r=null,i=null){const s=this.getDataFromNode(e,"any"),a=this.getSubBuildProperty("varying",s.subBuilds);let o=s[a];if(void 0===o){const e=this.varyings,l=e.length;null===t&&(t="nodeVarying"+l),"varying"!==a&&(t=this.getSubBuildProperty(t,s.subBuilds)),o=new KE(t,n,r,i),e.push(o),this.registerDeclaration(o),s[a]=o}return o}registerDeclaration(e){const t=this.shaderStage,n=this.declarations[t]||(this.declarations[t]={}),r=this.getPropertyName(e);let i=1,s=r;for(;void 0!==n[s];)s=r+"_"+i++;i>1&&(e.name=s,console.warn(`THREE.TSL: Declaration name '${r}' of '${e.type}' already in use. Renamed to '${s}'.`)),n[s]=e}getCodeFromNode(e,t,n=this.shaderStage){const r=this.getDataFromNode(e);let i=r.code;if(void 0===i){const e=this.codes[n]||(this.codes[n]=[]),s=e.length;i=new QE("nodeCode"+s,t),e.push(i),r.code=i}return i}addFlowCodeHierarchy(e,t){const{flowCodes:n,flowCodeBlock:r}=this.getDataFromNode(e);let i=!0,s=t;for(;s;){if(!0===r.get(s)){i=!1;break}s=this.getDataFromNode(s).parentNodeBlock}if(i)for(const e of n)this.addLineFlowCode(e)}addLineFlowCodeBlock(e,t,n){const r=this.getDataFromNode(e),i=r.flowCodes||(r.flowCodes=[]),s=r.flowCodeBlock||(r.flowCodeBlock=new WeakMap);i.push(t),s.set(n,!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),n=this.flowChildNode(e,t);return this.flowsData.set(e,n),n}addInclude(e){null!==this.currentFunctionNode&&this.currentFunctionNode.includes.push(e)}buildFunctionNode(e){const t=new Yw,n=this.currentFunctionNode;return this.currentFunctionNode=t,t.code=this.buildFunctionCode(e),this.currentFunctionNode=n,t}flowShaderNode(e){const t=e.layout,n={[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)n[e.name]=new _w(e.type,e.name);e.layout=null;const r=e.call(n),i=this.flowStagesNode(r,t.type);return e.layout=t,i}flowStagesNode(e,t=null){const n=this.flow,r=this.vars,i=this.declarations,s=this.cache,a=this.buildStage,o=this.stack,l={code:""};this.flow=l,this.vars={},this.declarations={},this.cache=new JE,this.stack=yw();for(const n of rf)this.setBuildStage(n),l.result=e.build(this,t);return l.vars=this.getVars(this.shaderStage),this.flow=n,this.vars=r,this.declarations=i,this.cache=s,this.stack=o,this.setBuildStage(a),l}getFunctionOperator(){return null}buildFunctionCode(){console.warn("Abstract function.")}flowChildNode(e,t=null){const n=this.flow,r={code:""};return this.flow=r,r.result=e.build(this,t),this.flow=n,r}flowNodeFromShaderStage(e,t,n=null,r=null){const i=this.tab,s=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 u=null;if("generate"===this.buildStage){const i=this.flowChildNode(t,n);null!==r&&(i.code+=`${this.tab+r} = ${i.result};\n`),this.flowCode[e]=this.flowCode[e]+i.code,u=i}else u=t.build(this);return this.setShaderStage(a),this.cache=s,this.tab=i,this.context=o,u}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){console.warn("Abstract function.")}getVaryings(){console.warn("Abstract function.")}getVar(e,t,n=null){return`${null!==n?this.generateArrayDeclaration(e,n):this.getType(e)} ${t}`}getVars(e){let t="";const n=this.vars[e];if(void 0!==n)for(const e of n)t+=`${this.getVar(e.type,e.name)}; `;return t}getUniforms(){console.warn("Abstract function.")}getCodes(e){const t=this.codes[e];let n="";if(void 0!==t)for(const e of t)n+=e.code+"\n";return n}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(){console.warn("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 n=this.subBuildLayers;for(let e=t.length-1;e>=0;e--){const r=t[e];if(n.includes(r))return r}return null}getSubBuildOutput(e){return this.getSubBuildProperty("outputNode",e)}getSubBuildProperty(e="",t=null){let n,r;return n=null!==t?this.getClosestSubBuild(t):this.subBuildFn,r=n?e?n+"_"+e:n:e,r}build(){const{object:e,material:t,renderer:n}=this;if(null!==t){let e=n.library.fromMaterial(t);null===e&&(console.error(`NodeMaterial: Material "${t.type}" is not compatible.`),e=new Qb),e.build(this)}else this.addFlow("compute",e);for(const e of rf){this.setBuildStage(e),this.context.vertex&&this.context.vertex.isNode&&this.flowNodeFromShaderStage("vertex",this.context.vertex);for(const t of sf){this.setShaderStage(t);const n=this.flowNodes[t];for(const t of n)"generate"===e?this.flowNode(t):t.build(this)}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}getNodeUniform(e,t){if("float"===t||"int"===t||"uint"===t)return new cA(e);if("vec2"===t||"ivec2"===t||"uvec2"===t)return new hA(e);if("vec3"===t||"ivec3"===t||"uvec3"===t)return new dA(e);if("vec4"===t||"ivec4"===t||"uvec4"===t)return new pA(e);if("color"===t)return new fA(e);if("mat2"===t)return new mA(e);if("mat3"===t)return new gA(e);if("mat4"===t)return new _A(e);throw new Error(`Uniform "${t}" not declared.`)}format(e,t,n){if((t=this.getVectorType(t))===(n=this.getVectorType(n))||null===n||this.isReference(n))return e;const r=this.getTypeLength(t),i=this.getTypeLength(n);return 16===r&&9===i?`${this.getType(n)}( ${e}[ 0 ].xyz, ${e}[ 1 ].xyz, ${e}[ 2 ].xyz )`:9===r&&4===i?`${this.getType(n)}( ${e}[ 0 ].xy, ${e}[ 1 ].xy )`:r>4||i>4||0===i?e:r===i?`${this.getType(n)}( ${e} )`:r>i?(e="bool"===n?`all( ${e} )`:`${e}.${"xyz".slice(0,i)}`,this.format(e,this.getTypeFromLength(i,this.getComponentType(t)),n)):4===i&&r>1?`${this.getType(n)}( ${this.format(e,t,"vec3")}, 1.0 )`:2===r?`${this.getType(n)}( ${this.format(e,t,"vec2")}, 0.0 )`:(1===r&&i>1&&t!==this.getComponentType(n)&&(e=`${this.getType(this.getComponentType(n))}( ${e} )`),`${this.getType(n)}( ${e} )`)}getSignature(){return`// Three.js r${s} - Node System\n`}*[Symbol.iterator](){}}class TA{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 n=e.get(t);return void 0===n&&(n={renderMap:new WeakMap,frameMap:new WeakMap},e.set(t,n)),n}updateBeforeNode(e){const t=e.getUpdateBeforeType(),n=e.updateReference(this);if(t===Qp){const{frameMap:t}=this._getMaps(this.updateBeforeMap,n);t.get(n)!==this.frameId&&!1!==e.updateBefore(this)&&t.set(n,this.frameId)}else if(t===Zp){const{renderMap:t}=this._getMaps(this.updateBeforeMap,n);t.get(n)!==this.renderId&&!1!==e.updateBefore(this)&&t.set(n,this.renderId)}else t===Jp&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),n=e.updateReference(this);if(t===Qp){const{frameMap:t}=this._getMaps(this.updateAfterMap,n);t.get(n)!==this.frameId&&!1!==e.updateAfter(this)&&t.set(n,this.frameId)}else if(t===Zp){const{renderMap:t}=this._getMaps(this.updateAfterMap,n);t.get(n)!==this.renderId&&!1!==e.updateAfter(this)&&t.set(n,this.renderId)}else t===Jp&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),n=e.updateReference(this);if(t===Qp){const{frameMap:t}=this._getMaps(this.updateMap,n);t.get(n)!==this.frameId&&!1!==e.update(this)&&t.set(n,this.frameId)}else if(t===Zp){const{renderMap:t}=this._getMaps(this.updateMap,n);t.get(n)!==this.renderId&&!1!==e.update(this)&&t.set(n,this.renderId)}else t===Jp&&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 SA{constructor(e,t,n=null,r="",i=!1){this.type=e,this.name=t,this.count=n,this.qualifier=r,this.isConst=i}}SA.isNodeFunctionInput=!0;class MA extends BE{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:aE(this.light),lightColor:e}}}const wA=new Bn,EA=new Bn;let AA=null;class RA extends BE{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=cg(new Ut).setGroup(og),this.halfWidth=cg(new Ut).setGroup(og),this.updateType=Zp}update(e){super.update(e);const{light:t}=this,n=e.camera.matrixWorldInverse;EA.identity(),wA.copy(t.matrixWorld),wA.premultiply(n),EA.extractRotation(wA),this.halfWidth.value.set(.5*t.width,0,0),this.halfHeight.value.set(0,.5*t.height,0),this.halfWidth.value.applyMatrix4(EA),this.halfHeight.value.applyMatrix4(EA)}setupDirectRectArea(e){let t,n;e.isAvailable("float32Filterable")?(t=Uv(AA.LTC_FLOAT_1),n=Uv(AA.LTC_FLOAT_2)):(t=Uv(AA.LTC_HALF_1),n=Uv(AA.LTC_HALF_2));const{colorNode:r,light:i}=this;return{lightColor:r,lightPosition:sE(i),halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:n}}static setLTC(e){AA=e}}class CA extends BE{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=cg(0).setGroup(og),this.penumbraCosNode=cg(0).setGroup(og),this.cutoffDistanceNode=cg(0).setGroup(og),this.decayExponentNode=cg(0).setGroup(og),this.colorNode=cg(this.color).setGroup(og)}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:n,penumbraCosNode:r}=this;return z_(n,r,t)}getLightCoord(e){const t=e.getNodeProperties(this);let n=t.projectionUV;return void 0===n&&(n=function(e,t=ly){const n=rE(e).mul(t);return n.xyz.div(n.w)}(this.light,e.context.positionWorld),t.projectionUV=n),n}setupDirect(e){const{colorNode:t,cutoffDistanceNode:n,decayExponentNode:r,light:i}=this,s=this.getLightVector(e),a=s.normalize(),o=a.dot(aE(i)),l=this.getSpotAttenuation(e,o),u=s.length(),c=kE({lightDistance:u,cutoffDistance:n,decayExponent:r});let h,d,p=t.mul(l).mul(c);if(i.colorNode?(d=this.getLightCoord(e),h=i.colorNode(d)):i.map&&(d=this.getLightCoord(e),h=Uv(i.map,d.xy).onRenderUpdate(()=>i.map)),h){p=d.mul(2).sub(1).abs().lessThan(1).all().select(p.mul(h),p)}return{lightColor:p,lightDirection:a}}}class NA extends CA{static get type(){return"IESSpotLightNode"}getSpotAttenuation(e,t){const n=this.light.iesMap;let r=null;if(n&&!0===n.isTexture){const e=t.acos().mul(1/Math.PI);r=Uv(n,dm(e,0),0).r}else r=super.getSpotAttenuation(t);return r}}const PA=nm(([e,t])=>{const n=e.abs().sub(t);return d_(S_(n,0)).add(T_(S_(n.x,n.y),0))});class LA extends CA{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=this.penumbraCosNode,n=this.getLightCoord(e),r=n.xyz.div(n.w),i=PA(r.xy.sub(dm(.5)),dm(.5)),s=yg(-1,_g(1,l_(t)).sub(1));return B_(i.mul(-2).mul(s))}}class DA extends BE{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class IA extends BE{static get type(){return"HemisphereLightNode"}constructor(e=null){super(e),this.lightPositionNode=iE(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=cg(new Nr).setGroup(og)}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:n,lightDirectionNode:r}=this,i=by.dot(r).mul(.5).add(.5),s=O_(n,t,i);e.context.irradiance.addAssign(s)}}class UA extends BE{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let e=0;e<9;e++)t.push(new Ut);this.lightProbe=Vv(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=VE(by,this.lightProbe);e.context.irradiance.addAssign(t)}}class OA{parseFunction(){console.warn("Abstract function.")}}class FA{constructor(e,t,n="",r=""){this.type=e,this.inputs=t,this.name=n,this.precision=r}getCode(){console.warn("Abstract function.")}}FA.isNodeFunction=!0;const BA=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,kA=/[a-z_0-9]+/gi,zA="#pragma main";class VA extends FA{constructor(e){const{type:t,inputs:n,name:r,precision:i,inputsCode:s,blockCode:a,headerCode:o}=(e=>{const t=(e=e.trim()).indexOf(zA),n=-1!==t?e.slice(t+12):e,r=n.match(BA);if(null!==r&&5===r.length){const i=r[4],s=[];let a=null;for(;null!==(a=kA.exec(i));)s.push(a);const o=[];let l=0;for(;l<s.length;){const e="const"===s[l][0];!0===e&&l++;let t=s[l][0];"in"===t||"out"===t||"inout"===t?l++:t="";const n=s[l++][0];let r=Number.parseInt(s[l][0]);!1===Number.isNaN(r)?l++:r=null;const i=s[l++][0];o.push(new SA(n,i,r,t,e))}const u=n.substring(r[0].length),c=void 0!==r[3]?r[3]:"";return{type:r[2],inputs:o,name:c,precision:void 0!==r[1]?r[1]:"",inputsCode:i,blockCode:u,headerCode:-1!==t?e.slice(0,t):""}}throw new Error("FunctionNode: Function is not a GLSL code.")})(e);super(t,n,r,i),this.inputsCode=s,this.blockCode=a,this.headerCode=o}getCode(e=this.name){let t;const n=this.blockCode;if(""!==n){const{type:r,inputsCode:i,headerCode:s,precision:a}=this;let o=`${r} ${e} ( ${i.trim()} )`;""!==a&&(o=`${a} ${o}`),t=s+o+n}else t="";return t}}class GA extends OA{parseFunction(e){return new VA(e)}}const HA=new WeakMap,jA=[],WA=[];class XA extends FM{constructor(e,t){super(),this.renderer=e,this.backend=t,this.nodeFrame=new TA,this.nodeBuilderCache=new Map,this.callHashCache=new LM,this.groupsData=new LM,this.cacheLib={}}updateGroup(e){const t=e.groupNode,n=t.name;if(n===lg.name)return!0;if(n===og.name){const t=this.get(e),n=this.nodeFrame.renderId;return t.renderId!==n&&(t.renderId=n,!0)}if(n===ag.name){const t=this.get(e),n=this.nodeFrame.frameId;return t.frameId!==n&&(t.frameId=n,!0)}jA[0]=t,jA[1]=e;let r=this.groupsData.get(jA);return void 0===r&&this.groupsData.set(jA,r={}),jA.length=0,r.version!==t.version&&(r.version=t.version,!0)}getForRenderCacheKey(e){return e.initialCacheKey}getForRender(e){const t=this.get(e);let n=t.nodeBuilderState;if(void 0===n){const{nodeBuilderCache:r}=this,i=this.getForRenderCacheKey(e);if(n=r.get(i),void 0===n){const t=this.backend.createNodeBuilder(e.object,this.renderer);t.scene=e.scene,t.material=e.material,t.camera=e.camera,t.context.material=e.material,t.lightsNode=e.lightsNode,t.environmentNode=this.getEnvironmentNode(e.scene),t.fogNode=this.getFogNode(e.scene),t.clippingContext=e.clippingContext,this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview&&t.enableMultiview(),t.build(),n=this._createNodeBuilderState(t),r.set(i,n)}n.usedTimes++,t.nodeBuilderState=n}return n}delete(e){if(e.isRenderObject){const t=this.get(e).nodeBuilderState;t.usedTimes--,0===t.usedTimes&&this.nodeBuilderCache.delete(this.getForRenderCacheKey(e))}return super.delete(e)}getForCompute(e){const t=this.get(e);let n=t.nodeBuilderState;if(void 0===n){const r=this.backend.createNodeBuilder(e,this.renderer);r.build(),n=this._createNodeBuilderState(r),t.nodeBuilderState=n}return n}_createNodeBuilderState(e){return new XE(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 n=this.get(e);n.environmentNode&&(t=n.environmentNode)}return t}getBackgroundNode(e){this.updateBackground(e);let t=null;if(e.backgroundNode&&e.backgroundNode.isNode)t=e.backgroundNode;else{const n=this.get(e);n.backgroundNode&&(t=n.backgroundNode)}return t}getFogNode(e){return this.updateFog(e),e.fogNode||this.get(e).fogNode||null}getCacheKey(e,t){jA[0]=e,jA[1]=t;const n=this.renderer.info.calls,r=this.callHashCache.get(jA)||{};if(r.callId!==n){const i=this.getEnvironmentNode(e),s=this.getFogNode(e);t&&WA.push(t.getCacheKey(!0)),i&&WA.push(i.getCacheKey()),s&&WA.push(s.getCacheKey()),WA.push(this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview?1:0),WA.push(this.renderer.shadowMap.enabled?1:0),r.callId=n,r.cacheKey=zp(WA),this.callHashCache.set(jA,r),WA.length=0}return jA.length=0,r.cacheKey}get isToneMappingState(){return!this.renderer.getRenderTarget()}updateBackground(e){const t=this.get(e),n=e.background;if(n){const r=0===e.backgroundBlurriness&&t.backgroundBlurriness>0||e.backgroundBlurriness>0&&0===t.backgroundBlurriness;if(t.background!==n||r){const i=this.getCacheNode("background",n,()=>{if(!0===n.isCubeTexture||n.mapping===j||n.mapping===W||n.mapping===X){if(e.backgroundBlurriness>0||n.mapping===X)return aM(n);{let e;return e=!0===n.isCubeTexture?Fy(n):Uv(n),cT(e)}}if(!0===n.isTexture)return Uv(n,Rb.flipY()).setUpdateMatrix(!0);!0!==n.isColor&&console.error("WebGPUNodes: Unsupported background configuration.",n)},r);t.backgroundNode=i,t.background=n,t.backgroundBlurriness=e.backgroundBlurriness}}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}getCacheNode(e,t,n,r=!1){const i=this.cacheLib[e]||(this.cacheLib[e]=new WeakMap);let s=i.get(t);return(void 0===s||r)&&(s=n(),i.set(t,s)),s}updateFog(e){const t=this.get(e),n=e.fog;if(n){if(t.fog!==n){const e=this.getCacheNode("fog",n,()=>{if(n.isFogExp2){const e=zy("color","color",n).setGroup(og),t=zy("density","float",n).setGroup(og);return Jw(e,Zw(t))}if(n.isFog){const e=zy("color","color",n).setGroup(og),t=zy("near","float",n).setGroup(og),r=zy("far","float",n).setGroup(og);return Jw(e,Qw(t,r))}console.error("THREE.Renderer: Unsupported fog configuration.",n)});t.fogNode=e,t.fog=n}}else delete t.fogNode,delete t.fog}updateEnvironment(e){const t=this.get(e),n=e.environment;if(n){if(t.environment!==n){const e=this.getCacheNode("environment",n,()=>!0===n.isCubeTexture?Fy(n):!0===n.isTexture?Uv(n):void console.error("Nodes: Unsupported environment configuration.",n));t.environmentNode=e,t.environment=n}}else t.environmentNode&&(delete t.environmentNode,delete t.environment)}getNodeFrame(e=this.renderer,t=null,n=null,r=null,i=null){const s=this.nodeFrame;return s.renderer=e,s.scene=t,s.object=n,s.camera=r,s.material=i,s}getNodeFrameForRender(e){return this.getNodeFrame(e.renderer,e.scene,e.object,e.camera,e.material)}getOutputCacheKey(){const e=this.renderer;return e.toneMapping+","+e.currentColorSpace+","+e.xr.isPresenting}hasOutputChange(e){return HA.get(e)!==this.getOutputCacheKey()}getOutputNode(e){const t=this.renderer,n=this.getOutputCacheKey(),r=e.isArrayTexture?Dw(e,gm(Rb,Gv("gl_ViewID_OVR"))).renderOutput(t.toneMapping,t.currentColorSpace):Uv(e,Rb).renderOutput(t.toneMapping,t.currentColorSpace);return HA.set(e,n),r}updateBefore(e){const t=e.getNodeBuilderState();for(const n of t.updateBeforeNodes)this.getNodeFrameForRender(e).updateBeforeNode(n)}updateAfter(e){const t=e.getNodeBuilderState();for(const n of t.updateAfterNodes)this.getNodeFrameForRender(e).updateAfterNode(n)}updateForCompute(e){const t=this.getNodeFrame(),n=this.getForCompute(e);for(const e of n.updateNodes)t.updateNode(e)}updateForRender(e){const t=this.getNodeFrameForRender(e),n=e.getNodeBuilderState();for(const e of n.updateNodes)t.updateNode(e)}needsRefresh(e){const t=this.getNodeFrameForRender(e);return e.getMonitor().needsRefresh(e,t)}dispose(){super.dispose(),this.nodeFrame=new TA,this.nodeBuilderCache=new Map,this.cacheLib={}}}const qA=new Gi;class $A{constructor(e=null){this.version=0,this.clipIntersection=null,this.cacheKey="",this.shadowPass=!1,this.viewNormalMatrix=new Bt,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,n){const r=e.length;for(let i=0;i<r;i++){qA.copy(e[i]).applyMatrix4(this.viewMatrix,this.viewNormalMatrix);const r=t[n+i],s=qA.normal;r.x=-s.x,r.y=-s.y,r.z=-s.z,r.w=qA.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 n=!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 r=t.clippingPlanes,i=r.length;let s,a;if(this.clipIntersection?(s=this.intersectionPlanes,a=e.intersectionPlanes.length):(s=this.unionPlanes,a=e.unionPlanes.length),s.length!==a+i){s.length=a+i;for(let e=0;e<i;e++)s[a+e]=new an;n=!0}this.projectPlanes(r,s,a),n&&(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 $A(this),this.clippingGroupContexts.set(e,t)),t.update(this,e),t}get unionClippingCount(){return this.unionPlanes.length}}class YA{constructor(e,t){this.bundleGroup=e,this.camera=t}}const KA=[];class QA{constructor(){this.bundles=new LM}get(e,t){const n=this.bundles;KA[0]=e,KA[1]=t;let r=n.get(KA);return void 0===r&&(r=new YA(e,t),n.set(KA,r)),KA.length=0,r}dispose(){this.bundles=new LM}}class ZA{constructor(){this.lightNodes=new WeakMap,this.materialNodes=new Map,this.toneMappingNodes=new Map}fromMaterial(e){if(e.isNodeMaterial)return e;let t=null;const n=this.getMaterialNodeClass(e.type);if(null!==n){t=new n;for(const n in e)t[n]=e[n]}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,n){if(n.has(t))console.warn(`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.`);n.set(t,e)}}addClass(e,t,n){if(n.has(t))console.warn(`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.`);n.set(t,e)}}}const JA=new cE,eR=[];class tR extends LM{constructor(){super()}createNode(e=[]){return(new cE).setLights(e)}getNode(e,t){if(e.isQuadMesh)return JA;eR[0]=e,eR[1]=t;let n=this.get(eR);return void 0===n&&(n=this.createNode(),this.set(eR,n)),eR.length=0,n}}class nR extends on{constructor(e=1,t=1,n={}){super(e,t,n),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 rR=new Ut,iR=new Ut;class sR extends bt{constructor(e,t=!1){super(),this.enabled=!1,this.isPresenting=!1,this.cameraAutoUpdate=!0,this._renderer=e,this._cameraL=new Mi,this._cameraL.viewport=new an,this._cameraR=new Mi,this._cameraR.viewport=new an,this._cameras=[this._cameraL,this._cameraR],this._cameraXR=new ua,this._currentDepthNear=null,this._currentDepthFar=null,this._controllers=[],this._controllerInputSources=[],this._xrRenderTarget=null,this._layers=[],this._supportsLayers=!1,this._frameBufferTargets=null,this._createXRLayer=cR.bind(this),this._gl=null,this._currentAnimationContext=null,this._currentAnimationLoop=null,this._currentPixelRatio=null,this._currentSize=new Dt,this._onSessionEvent=oR.bind(this),this._onSessionEnd=lR.bind(this),this._onInputSourcesChange=uR.bind(this),this._onAnimationFrame=hR.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._useLayers="undefined"!=typeof XRWebGLBinding&&"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&&console.warn("THREE.XRManager: Cannot change framebuffer scale while presenting.")}getReferenceSpaceType(){return this._referenceSpaceType}setReferenceSpaceType(e){this._referenceSpaceType=e,!0===this.isPresenting&&console.warn("THREE.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}getFrame(){return this._xrFrame}useMultiview(){return this._useMultiview}createQuadLayer(e,t,n,r,i,s,a,o={}){const l=new Ss(e,t),u=new nR(i,s,{format:ge,type:ne,depthTexture:new os(i,s,o.stencil?de:oe,void 0,void 0,void 0,void 0,void 0,void 0,o.stencil?ve:_e),stencilBuffer:o.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});u._autoAllocateDepthBuffer=!0;const c=new Ir({color:16777215,side:0});c.map=u.texture,c.map.offset.y=1,c.map.repeat.y=-1;const h=new di(l,c);h.position.copy(n),h.quaternion.copy(r);const d={type:"quad",width:e,height:t,translation:n,quaternion:r,pixelwidth:i,pixelheight:s,plane:h,material:c,rendercall:a,renderTarget:u};if(this._layers.push(d),null!==this._session){d.plane.material=new Ir({color:16777215,side:0}),d.plane.material.blending=5,d.plane.material.blendEquation=g,d.plane.material.blendSrc=y,d.plane.material.blendDst=y,d.xrlayer=this._createXRLayer(d);const e=this._session.renderState.layers;e.unshift(d.xrlayer),this._session.updateRenderState({layers:e})}else u.isXRRenderTarget=!1;return h}createCylinderLayer(e,t,n,r,i,s,a,o,l={}){const u=new ls(e,e,e*t/n,64,64,!0,Math.PI-t/2,t),c=new nR(s,a,{format:ge,type:ne,depthTexture:new os(s,a,l.stencil?de:oe,void 0,void 0,void 0,void 0,void 0,void 0,l.stencil?ve:_e),stencilBuffer:l.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});c._autoAllocateDepthBuffer=!0;const h=new Ir({color:16777215,side:1});h.map=c.texture,h.map.offset.y=1,h.map.repeat.y=-1;const d=new di(u,h);d.position.copy(r),d.quaternion.copy(i);const p={type:"cylinder",radius:e,centralAngle:t,aspectratio:n,translation:r,quaternion:i,pixelwidth:s,pixelheight:a,plane:d,material:h,rendercall:o,renderTarget:c};if(this._layers.push(p),null!==this._session){p.plane.material=new Ir({color:16777215,side:1}),p.plane.material.blending=5,p.plane.material.blendEquation=g,p.plane.material.blendSrc=y,p.plane.material.blendDst=y,p.xrlayer=this._createXRLayer(p);const e=this._session.renderState.layers;e.unshift(p.xrlayer),this._session.updateRenderState({layers:e})}else c.isXRRenderTarget=!1;return d}renderLayers(){const e=new Ut,t=new It,n=this._renderer,r=this.isPresenting,i=n.getOutputRenderTarget(),s=n._frameBufferTarget;this.isPresenting=!1;const a=new Dt;n.getSize(a);const o=n._quad;for(const r of this._layers)if(r.renderTarget.isXRRenderTarget=null!==this._session,r.renderTarget._hasExternalTextures=r.renderTarget.isXRRenderTarget,r.renderTarget.isXRRenderTarget&&this._supportsLayers){r.xrlayer.transform=new XRRigidTransform(r.plane.getWorldPosition(e),r.plane.getWorldQuaternion(t));const i=this._glBinding.getSubImage(r.xrlayer,this._xrFrame);n.backend.setXRRenderTargetTextures(r.renderTarget,i.colorTexture,void 0),n._setXRLayerSize(r.renderTarget.width,r.renderTarget.height),n.setOutputRenderTarget(r.renderTarget),n.setRenderTarget(null),n._frameBufferTarget=null,this._frameBufferTargets||(this._frameBufferTargets=new WeakMap);const{frameBufferTarget:s,quad:a}=this._frameBufferTargets.get(r.renderTarget)||{frameBufferTarget:null,quad:null};s?(n._frameBufferTarget=s,n._quad=a):(n._quad=new Mw(new Qb),this._frameBufferTargets.set(r.renderTarget,{frameBufferTarget:n._getFrameBufferTarget(),quad:n._quad})),r.rendercall(),n._frameBufferTarget=null}else n.setRenderTarget(r.renderTarget),r.rendercall();n.setRenderTarget(null),n.setOutputRenderTarget(i),n._frameBufferTarget=s,n._setXRLayerSize(a.x,a.y),n._quad=o,this.isPresenting=r}getSession(){return this._session}async setSession(e){const t=this._renderer,n=t.backend;this._gl=t.getContext();const r=this._gl,i=r.getContextAttributes();if(this._session=e,null!==e){if(!0===n.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 n.makeXRCompatible(),this._currentPixelRatio=t.getPixelRatio(),t.getSize(this._currentSize),this._currentAnimationContext=t._animation.getContext(),this._currentAnimationLoop=t._animation.getAnimationLoop(),t._animation.stop(),!0===this._useLayers){let n=null,s=null,a=null;t.depth&&(a=t.stencil?r.DEPTH24_STENCIL8:r.DEPTH_COMPONENT24,n=t.stencil?ve:_e,s=t.stencil?de:oe);const o={colorFormat:r.RGBA8,depthFormat:a,scaleFactor:this._framebufferScaleFactor,clearOnAccess:!1};this._useMultiviewIfPossible&&t.hasFeature("OVR_multiview2")&&(o.textureType="texture-array",this._useMultiview=!0);const l=new XRWebGLBinding(e,r),u=l.createProjectionLayer(o),c=[u];this._glBinding=l,this._glProjLayer=u,t.setPixelRatio(1),t._setXRLayerSize(u.textureWidth,u.textureHeight);const h=this._useMultiview?2:1,d=new os(u.textureWidth,u.textureHeight,s,void 0,void 0,void 0,void 0,void 0,void 0,n,h);if(this._xrRenderTarget=new nR(u.textureWidth,u.textureHeight,{format:ge,type:ne,colorSpace:t.outputColorSpace,depthTexture:d,stencilBuffer:t.stencil,samples:i.antialias?4:0,resolveDepthBuffer:!1===u.ignoreDepthValues,resolveStencilBuffer:!1===u.ignoreDepthValues,depth:this._useMultiview?2:1,multiview:this._useMultiview}),this._xrRenderTarget._hasExternalTextures=!0,this._xrRenderTarget.depth=this._useMultiview?2:1,this._supportsLayers=e.enabledFeatures.includes("layers"),this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType()),this._supportsLayers)for(const e of this._layers)e.plane.material=new Ir({color:16777215,side:"cylinder"===e.type?1:0}),e.plane.material.blending=5,e.plane.material.blendEquation=g,e.plane.material.blendSrc=y,e.plane.material.blendDst=y,e.xrlayer=this._createXRLayer(e),c.unshift(e.xrlayer);e.updateRenderState({layers:c})}else{const n={antialias:t.samples>0,alpha:!0,depth:t.depth,stencil:t.stencil,framebufferScaleFactor:this.getFramebufferScaleFactor()},i=new XRWebGLLayer(e,r,n);this._glBaseLayer=i,e.updateRenderState({baseLayer:i}),t.setPixelRatio(1),t._setXRLayerSize(i.framebufferWidth,i.framebufferHeight),this._xrRenderTarget=new nR(i.framebufferWidth,i.framebufferHeight,{format:ge,type:ne,colorSpace:t.outputColorSpace,stencilBuffer:t.stencil,resolveDepthBuffer:!1===i.ignoreDepthValues,resolveStencilBuffer:!1===i.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 n=e.near,r=e.far,i=this._cameraXR,s=this._cameraL,a=this._cameraR;i.near=a.near=s.near=n,i.far=a.far=s.far=r,i.isMultiViewCamera=this._useMultiview,this._currentDepthNear===i.near&&this._currentDepthFar===i.far||(t.updateRenderState({depthNear:i.near,depthFar:i.far}),this._currentDepthNear=i.near,this._currentDepthFar=i.far),s.layers.mask=2|e.layers.mask,a.layers.mask=4|e.layers.mask,i.layers.mask=s.layers.mask|a.layers.mask;const o=e.parent,l=i.cameras;aR(i,o);for(let e=0;e<l.length;e++)aR(l[e],o);2===l.length?function(e,t,n){rR.setFromMatrixPosition(t.matrixWorld),iR.setFromMatrixPosition(n.matrixWorld);const r=rR.distanceTo(iR),i=t.projectionMatrix.elements,s=n.projectionMatrix.elements,a=i[14]/(i[10]-1),o=i[14]/(i[10]+1),l=(i[9]+1)/i[5],u=(i[9]-1)/i[5],c=(i[8]-1)/i[0],h=(s[8]+1)/s[0],d=a*c,p=a*h,f=r/(-c+h),m=f*-c;if(t.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.translateX(m),e.translateZ(f),e.matrixWorld.compose(e.position,e.quaternion,e.scale),e.matrixWorldInverse.copy(e.matrixWorld).invert(),-1===i[10])e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse);else{const t=a+f,n=o+f,i=d-m,s=p+(r-m),c=l*o/n*t,h=u*o/n*t;e.projectionMatrix.makePerspective(i,s,c,h,t,n),e.projectionMatrixInverse.copy(e.projectionMatrix).invert()}}(i,s,a):i.projectionMatrix.copy(s.projectionMatrix),function(e,t,n){null===n?e.matrix.copy(t.matrixWorld):(e.matrix.copy(n.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*wt*Math.atan(1/e.projectionMatrix.elements[5]),e.zoom=1)}(e,i,o)}_getController(e){let t=this._controllers[e];return void 0===t&&(t=new Pi,this._controllers[e]=t),t}}function aR(e,t){null===t?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}function oR(e){const t=this._controllerInputSources.indexOf(e.inputSource);if(-1===t)return;const n=this._controllers[t];if(void 0!==n){const t=this.getReferenceSpace();n.update(e.inputSource,e.frame,t),n.dispatchEvent({type:e.type,data:e.inputSource})}}function lR(){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,!0===this._supportsLayers)for(const e of this._layers)e.renderTarget=new nR(e.pixelwidth,e.pixelheight,{format:ge,type:ne,depthTexture:new os(e.pixelwidth,e.pixelheight,e.stencilBuffer?de:oe,void 0,void 0,void 0,void 0,void 0,void 0,e.stencilBuffer?ve:_e),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 uR(e){const t=this._controllers,n=this._controllerInputSources;for(let r=0;r<e.removed.length;r++){const i=e.removed[r],s=n.indexOf(i);s>=0&&(n[s]=null,t[s].disconnect(i))}for(let r=0;r<e.added.length;r++){const i=e.added[r];let s=n.indexOf(i);if(-1===s){for(let e=0;e<t.length;e++){if(e>=n.length){n.push(i),s=e;break}if(null===n[e]){n[e]=i,s=e;break}}if(-1===s)break}const a=t[s];a&&a.connect(i)}}function cR(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 hR(e,t){if(void 0===t)return;const n=this._cameraXR,r=this._renderer,i=r.backend,s=this._glBaseLayer,a=this.getReferenceSpace(),o=t.getViewerPose(a);if(this._xrFrame=t,null!==o){const e=o.views;null!==this._glBaseLayer&&i.setXRTarget(s.framebuffer);let t=!1;e.length!==n.cameras.length&&(n.cameras.length=0,t=!0);for(let r=0;r<e.length;r++){const a=e[r];let o;if(!0===this._useLayers){const e=this._glBinding.getViewSubImage(this._glProjLayer,a);o=e.viewport,0===r&&i.setXRRenderTargetTextures(this._xrRenderTarget,e.colorTexture,this._glProjLayer.ignoreDepthValues&&!this._useMultiview?void 0:e.depthStencilTexture)}else o=s.getViewport(a);let l=this._cameras[r];void 0===l&&(l=new Mi,l.layers.enable(r),l.viewport=new an,this._cameras[r]=l),l.matrix.fromArray(a.transform.matrix),l.matrix.decompose(l.position,l.quaternion,l.scale),l.projectionMatrix.fromArray(a.projectionMatrix),l.projectionMatrixInverse.copy(l.projectionMatrix).invert(),l.viewport.set(o.x,o.y,o.width,o.height),0===r&&(n.matrix.copy(l.matrix),n.matrix.decompose(n.position,n.quaternion,n.scale)),!0===t&&n.cameras.push(l)}r.setOutputRenderTarget(this._xrRenderTarget)}for(let e=0;e<this._controllers.length;e++){const n=this._controllerInputSources[e],r=this._controllers[e];null!==n&&void 0!==r&&r.update(n,t,a)}this._currentAnimationLoop&&this._currentAnimationLoop(e,t),t.detectedPlanes&&this.dispatchEvent({type:"planesdetected",data:t}),this._xrFrame=null}const dR=new Li,pR=new Dt,fR=new an,mR=new Xi,gR=new Yi,_R=new Bn,vR=new an;class yR{constructor(e,t={}){this.isRenderer=!0;const{logarithmicDepthBuffer:n=!1,alpha:r=!0,depth:i=!0,stencil:s=!1,antialias:a=!1,samples:o=0,getFallback:l=null,colorBufferType:u=ue,multiview:c=!1}=t;this.domElement=e.getDomElement(),this.backend=e,this.samples=o||!0===a?4:0,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.alpha=r,this.logarithmicDepthBuffer=n,this.outputColorSpace=rt,this.toneMapping=0,this.toneMappingExposure=1,this.sortObjects=!0,this.depth=i,this.stencil=s,this.info=new qM,this.overrideNodes={modelViewMatrix:null,modelNormalViewMatrix:null},this.library=new ZA,this.lighting=new tR,this._getFallback=l,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new an(0,0,this._width,this._height),this._scissor=new an(0,0,this._width,this._height),this._scissorTest=!1,this._attributes=null,this._geometries=null,this._nodes=null,this._animation=null,this._bindings=null,this._objects=null,this._pipelines=null,this._bundles=null,this._renderLists=null,this._renderContexts=null,this._textures=null,this._background=null,this._quad=new Mw(new Qb),this._quad.material.name="Renderer_output",this._currentRenderContext=null,this._opaqueSort=null,this._transparentSort=null,this._frameBufferTarget=null;const h=!0===this.alpha?0:1;this._clearColor=new gw(0,0,0,h),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._colorBufferType=u,this._initialized=!1,this._initPromise=null,this._compilationPromises=null,this.transparent=!0,this.opaque=!0,this.shadowMap={enabled:!1,type:1},this.xr=new sR(this,c),this.debug={checkShaderErrors:!0,onShaderError:null,getShaderAsync:async(e,t,n)=>{await this.compileAsync(e,t);const r=this._renderLists.get(e,t),i=this._renderContexts.get(e,t,this._renderTarget),s=e.overrideMaterial||n.material,a=this._objects.get(n,s,e,t,r.lightsNode,i,i.clippingContext),{fragmentShader:o,vertexShader:l}=a.getNodeBuilderState();return{fragmentShader:o,vertexShader:l}}}}async init(){if(this._initialized)throw new Error("Renderer: Backend has already been initialized.");return null!==this._initPromise||(this._initPromise=new Promise(async(e,t)=>{let n=this.backend;try{await n.init(this)}catch(e){if(null===this._getFallback)return void t(e);try{this.backend=n=this._getFallback(e),await n.init(this)}catch(e){return void t(e)}}this._nodes=new XA(this,n),this._animation=new PM(this._nodes,this.info),this._attributes=new HM(n),this._background=new HE(this,this._nodes),this._geometries=new XM(this._attributes,this.info),this._textures=new mw(this,n,this.info),this._pipelines=new JM(n,this._nodes),this._bindings=new ew(n,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new OM(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new aw(this.lighting),this._bundles=new QA,this._renderContexts=new pw,this._animation.start(),this._initialized=!0,e(this)})),this._initPromise}get coordinateSystem(){return this.backend.coordinateSystem}async compileAsync(e,t,n=null){if(!0===this._isDeviceLost)return;!1===this._initialized&&await this.init();const r=this._nodes.nodeFrame,i=r.renderId,s=this._currentRenderContext,a=this._currentRenderObjectFunction,o=this._compilationPromises,l=!0===e.isScene?e:dR;null===n&&(n=e);const u=this._renderTarget,c=this._renderContexts.get(n,t,u),h=this._activeMipmapLevel,d=[];this._currentRenderContext=c,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=d,r.renderId++,r.update(),c.depth=this.depth,c.stencil=this.stencil,c.clippingContext||(c.clippingContext=new $A),c.clippingContext.updateGlobal(l,t),l.onBeforeRender(this,e,t,u);const p=this._renderLists.get(e,t);if(p.begin(),this._projectObject(e,t,0,p,c.clippingContext),n!==e&&n.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&p.pushLight(e)}),p.finish(),null!==u){this._textures.updateRenderTarget(u,h);const e=this._textures.get(u);c.textures=e.textures,c.depthTexture=e.depthTexture}else c.textures=null,c.depthTexture=null;this._background.update(l,p,c);const f=p.opaque,m=p.transparent,g=p.transparentDoublePass,_=p.lightsNode;!0===this.opaque&&f.length>0&&this._renderObjects(f,t,l,_),!0===this.transparent&&m.length>0&&this._renderTransparents(m,g,t,l,_),r.renderId=i,this._currentRenderContext=s,this._currentRenderObjectFunction=a,this._compilationPromises=o,this._handleObjectFunction=this._renderObjectDirect,await Promise.all(d)}async renderAsync(e,t){!1===this._initialized&&await this.init(),this._renderScene(e,t)}async waitForGPU(){await this.backend.waitForGPU()}set highPrecision(e){!0===e?(this.overrideNodes.modelViewMatrix=ry,this.overrideNodes.modelNormalViewMatrix=iy):this.highPrecision&&(this.overrideNodes.modelViewMatrix=null,this.overrideNodes.modelNormalViewMatrix=null)}get highPrecision(){return this.overrideNodes.modelViewMatrix===ry&&this.overrideNodes.modelNormalViewMatrix===iy}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getColorBufferType(){return this._colorBufferType}_onDeviceLost(e){let t=`THREE.WebGPURenderer: ${e.api} Device Lost:\n\nMessage: ${e.message}`;e.reason&&(t+=`\nReason: ${e.reason}`),console.error(t),this._isDeviceLost=!0}_renderBundle(e,t,n){const{bundleGroup:r,camera:i,renderList:s}=e,a=this._currentRenderContext,o=this._bundles.get(r,i),l=this.backend.get(o);void 0===l.renderContexts&&(l.renderContexts=new Set);const u=r.version!==l.version,c=!1===l.renderContexts.has(a)||u;if(l.renderContexts.add(a),c){this.backend.beginBundle(a),(void 0===l.renderObjects||u)&&(l.renderObjects=[]),this._currentRenderBundle=o;const{transparentDoublePass:e,transparent:c,opaque:h}=s;!0===this.opaque&&h.length>0&&this._renderObjects(h,i,t,n),!0===this.transparent&&c.length>0&&this._renderTransparents(c,e,i,t,n),this._currentRenderBundle=null,this.backend.finishBundle(a,o),l.version=r.version}else{const{renderObjects:e}=l;for(let t=0,n=e.length;t<n;t++){const n=e[t];this._nodes.needsRefresh(n)&&(this._nodes.updateBefore(n),this._nodes.updateForRender(n),this._bindings.updateForRender(n),this._nodes.updateAfter(n))}}this.backend.addBundle(a,o)}render(e,t){if(!1===this._initialized)return console.warn("THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead."),this.renderAsync(e,t);this._renderScene(e,t)}_getFrameBufferTarget(){const{currentToneMapping:e,currentColorSpace:t}=this;if(!1===(0!==e)&&!1===(t!==it))return null;const{width:n,height:r}=this.getDrawingBufferSize(pR),{depth:i,stencil:s}=this;let a=this._frameBufferTarget;null===a&&(a=new on(n,r,{depthBuffer:i,stencilBuffer:s,type:this._colorBufferType,format:ge,colorSpace:it,generateMipmaps:!1,minFilter:J,magFilter:J,samples:this.samples}),a.isPostProcessingRenderTarget=!0,this._frameBufferTarget=a);const o=this.getOutputRenderTarget();return a.depthBuffer=i,a.stencilBuffer=s,null!==o?a.setSize(o.width,o.height,o.depth):a.setSize(n,r,1),a.viewport.copy(this._viewport),a.scissor.copy(this._scissor),a.viewport.multiplyScalar(this._pixelRatio),a.scissor.multiplyScalar(this._pixelRatio),a.scissorTest=this._scissorTest,a.multiview=null!==o&&o.multiview,a.resolveDepthBuffer=null===o||o.resolveDepthBuffer,a._autoAllocateDepthBuffer=null!==o&&o._autoAllocateDepthBuffer,a}_renderScene(e,t,n=!0){if(!0===this._isDeviceLost)return;const r=n?this._getFrameBufferTarget():null,i=this._nodes.nodeFrame,s=i.renderId,a=this._currentRenderContext,o=this._currentRenderObjectFunction,l=!0===e.isScene?e:dR,u=this._renderTarget||this._outputRenderTarget,c=this._activeCubeFace,h=this._activeMipmapLevel;let d;null!==r?(d=r,this.setRenderTarget(d)):d=u;const p=this._renderContexts.get(e,t,d);this._currentRenderContext=p,this._currentRenderObjectFunction=this._renderObjectFunction||this.renderObject,this.info.calls++,this.info.render.calls++,this.info.render.frameCalls++,i.renderId=this.info.calls;const f=this.coordinateSystem,m=this.xr;if(t.coordinateSystem!==f&&!1===m.isPresenting&&(t.coordinateSystem=f,t.updateProjectionMatrix(),t.isArrayCamera))for(const e of t.cameras)e.coordinateSystem=f,e.updateProjectionMatrix();!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&!0===t.matrixWorldAutoUpdate&&t.updateMatrixWorld(),!0===m.enabled&&!0===m.isPresenting&&(!0===m.cameraAutoUpdate&&m.updateCamera(t),t=m.getCamera());let g=this._viewport,_=this._scissor,v=this._pixelRatio;null!==d&&(g=d.viewport,_=d.scissor,v=1),this.getDrawingBufferSize(pR),fR.set(0,0,pR.width,pR.height);const y=void 0===g.minDepth?0:g.minDepth,x=void 0===g.maxDepth?1:g.maxDepth;p.viewportValue.copy(g).multiplyScalar(v).floor(),p.viewportValue.width>>=h,p.viewportValue.height>>=h,p.viewportValue.minDepth=y,p.viewportValue.maxDepth=x,p.viewport=!1===p.viewportValue.equals(fR),p.scissorValue.copy(_).multiplyScalar(v).floor(),p.scissor=this._scissorTest&&!1===p.scissorValue.equals(fR),p.scissorValue.width>>=h,p.scissorValue.height>>=h,p.clippingContext||(p.clippingContext=new $A),p.clippingContext.updateGlobal(l,t),l.onBeforeRender(this,e,t,d);const b=t.isArrayCamera?gR:mR;t.isArrayCamera||(_R.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),b.setFromProjectionMatrix(_R,f));const T=this._renderLists.get(e,t);if(T.begin(),this._projectObject(e,t,0,T,p.clippingContext),T.finish(),!0===this.sortObjects&&T.sort(this._opaqueSort,this._transparentSort),null!==d){this._textures.updateRenderTarget(d,h);const e=this._textures.get(d);p.textures=e.textures,p.depthTexture=e.depthTexture,p.width=e.width,p.height=e.height,p.renderTarget=d,p.depth=d.depthBuffer,p.stencil=d.stencilBuffer}else p.textures=null,p.depthTexture=null,p.width=this.domElement.width,p.height=this.domElement.height,p.depth=this.depth,p.stencil=this.stencil;p.width>>=h,p.height>>=h,p.activeCubeFace=c,p.activeMipmapLevel=h,p.occlusionQueryCount=T.occlusionQueryCount,this._background.update(l,T,p),p.camera=t,this.backend.beginRender(p);const{bundles:S,lightsNode:M,transparentDoublePass:w,transparent:E,opaque:A}=T;return S.length>0&&this._renderBundles(S,l,M),!0===this.opaque&&A.length>0&&this._renderObjects(A,t,l,M),!0===this.transparent&&E.length>0&&this._renderTransparents(E,w,t,l,M),this.backend.finishRender(p),i.renderId=s,this._currentRenderContext=a,this._currentRenderObjectFunction=o,null!==r&&(this.setRenderTarget(u,c,h),this._renderOutput(d)),l.onAfterRender(this,e,t,d),p}_setXRLayerSize(e,t){this._width=e,this._height=t,this.setViewport(0,0,e,t)}_renderOutput(e){const t=this._quad;this._nodes.hasOutputChange(e.texture)&&(t.material.fragmentNode=this._nodes.getOutputNode(e.texture),t.material.needsUpdate=!0);const n=this.autoClear,r=this.xr.enabled;this.autoClear=!1,this.xr.enabled=!1,this._renderScene(t,t.camera,!1),this.autoClear=n,this.xr.enabled=r}getMaxAnisotropy(){return this.backend.getMaxAnisotropy()}getActiveCubeFace(){return this._activeCubeFace}getActiveMipmapLevel(){return this._activeMipmapLevel}async setAnimationLoop(e){!1===this._initialized&&await this.init(),this._animation.setAnimationLoop(e)}async getArrayBufferAsync(e){return await this.backend.getArrayBufferAsync(e)}getContext(){return this.backend.getContext()}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,n){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this._pixelRatio=n,this.domElement.width=Math.floor(e*n),this.domElement.height=Math.floor(t*n),this.setViewport(0,0,e,t),this._initialized&&this.backend.updateSize())}setSize(e,t,n=!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===n&&(this.domElement.style.width=e+"px",this.domElement.style.height=t+"px"),this.setViewport(0,0,e,t),this._initialized&&this.backend.updateSize())}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}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,n,r){const i=this._scissor;e.isVector4?i.copy(e):i.set(e,t,n,r)}getScissorTest(){return this._scissorTest}setScissorTest(e){this._scissorTest=e,this.backend.setScissorTest(e)}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,n,r,i=0,s=1){const a=this._viewport;e.isVector4?a.copy(e):a.set(e,t,n,r),a.minDepth=i,a.maxDepth=s}getClearColor(e){return e.copy(this._clearColor)}setClearColor(e,t=1){this._clearColor.set(e),this._clearColor.a=t}getClearAlpha(){return this._clearColor.a}setClearAlpha(e){this._clearColor.a=e}getClearDepth(){return this._clearDepth}setClearDepth(e){this._clearDepth=e}getClearStencil(){return this._clearStencil}setClearStencil(e){this._clearStencil=e}isOccluded(e){const t=this._currentRenderContext;return t&&this.backend.isOccluded(t,e)}clear(e=!0,t=!0,n=!0){if(!1===this._initialized)return console.warn("THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead."),this.clearAsync(e,t,n);const r=this._renderTarget||this._getFrameBufferTarget();let i=null;if(null!==r){this._textures.updateRenderTarget(r);const e=this._textures.get(r);i=this._renderContexts.getForClear(r),i.textures=e.textures,i.depthTexture=e.depthTexture,i.width=e.width,i.height=e.height,i.renderTarget=r,i.depth=r.depthBuffer,i.stencil=r.stencilBuffer,i.clearColorValue=this.backend.getClearColor(),i.activeCubeFace=this.getActiveCubeFace(),i.activeMipmapLevel=this.getActiveMipmapLevel()}this.backend.clear(e,t,n,i),null!==r&&null===this._renderTarget&&this._renderOutput(r)}clearColor(){return this.clear(!0,!1,!1)}clearDepth(){return this.clear(!1,!0,!1)}clearStencil(){return this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,n=!0){!1===this._initialized&&await this.init(),this.clear(e,t,n)}async clearColorAsync(){this.clearAsync(!0,!1,!1)}async clearDepthAsync(){this.clearAsync(!1,!0,!1)}async clearStencilAsync(){this.clearAsync(!1,!1,!0)}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:0}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:it}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||null===this._renderTarget}dispose(){this.info.dispose(),this.backend.dispose(),this._animation.dispose(),this._objects.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose(),this._textures.dispose(),null!==this._frameBufferTarget&&this._frameBufferTarget.dispose(),Object.values(this.backend.timestampQueryPool).forEach(e=>{null!==e&&e.dispose()}),this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,n=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=n}getRenderTarget(){return this._renderTarget}setOutputRenderTarget(e){this._outputRenderTarget=e}getOutputRenderTarget(){return this._outputRenderTarget}_resetXRState(){this.backend.setXRTarget(null),this.setOutputRenderTarget(null),this.setRenderTarget(null),this._frameBufferTarget.dispose(),this._frameBufferTarget=null}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}compute(e){if(!0===this._isDeviceLost)return;if(!1===this._initialized)return console.warn("THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead."),this.computeAsync(e);const t=this._nodes.nodeFrame,n=t.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,t.renderId=this.info.calls;const r=this.backend,i=this._pipelines,s=this._bindings,a=this._nodes,o=Array.isArray(e)?e:[e];if(void 0===o[0]||!0!==o[0].isComputeNode)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");r.beginCompute(e);for(const t of o){if(!1===i.has(t)){const e=()=>{t.removeEventListener("dispose",e),i.delete(t),s.delete(t),a.delete(t)};t.addEventListener("dispose",e);const n=t.onInitFunction;null!==n&&n.call(t,{renderer:this})}a.updateForCompute(t),s.updateForCompute(t);const n=s.getForCompute(t),o=i.getForCompute(t,n);r.compute(e,t,n,o)}r.finishCompute(e),t.renderId=n}async computeAsync(e){!1===this._initialized&&await this.init(),this.compute(e)}async hasFeatureAsync(e){return!1===this._initialized&&await this.init(),this.backend.hasFeature(e)}async resolveTimestampsAsync(e="render"){return!1===this._initialized&&await this.init(),this.backend.resolveTimestampsAsync(e)}hasFeature(e){return!1===this._initialized?(console.warn("THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead."),!1):this.backend.hasFeature(e)}hasInitialized(){return this._initialized}async initTextureAsync(e){!1===this._initialized&&await this.init(),this._textures.updateTexture(e)}initTexture(e){!1===this._initialized&&console.warn("THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead."),this._textures.updateTexture(e)}copyFramebufferToTexture(e,t=null){if(null!==t)if(t.isVector2)t=vR.set(t.x,t.y,e.image.width,e.image.height).floor();else{if(!t.isVector4)return void console.error("THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.");t=vR.copy(t).floor()}else t=vR.set(0,0,e.image.width,e.image.height);let n,r=this._currentRenderContext;null!==r?n=r.renderTarget:(n=this._renderTarget||this._getFrameBufferTarget(),null!==n&&(this._textures.updateRenderTarget(n),r=this._textures.get(n))),this._textures.updateTexture(e,{renderTarget:n}),this.backend.copyFramebufferToTexture(e,r,t)}copyTextureToTexture(e,t,n=null,r=null,i=0,s=0){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,n,r,i,s)}async readRenderTargetPixelsAsync(e,t,n,r,i,s=0,a=0){return this.backend.copyTextureToBuffer(e.textures[s],t,n,r,i,a)}_projectObject(e,t,n,r,i){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)n=e.renderOrder,e.isClippingGroup&&e.enabled&&(i=i.getGroupContext(e));else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)r.pushLight(e);else if(e.isSprite){const s=t.isArrayCamera?gR:mR;if(!e.frustumCulled||s.intersectsSprite(e,t)){!0===this.sortObjects&&vR.setFromMatrixPosition(e.matrixWorld).applyMatrix4(_R);const{geometry:t,material:s}=e;s.visible&&r.push(e,t,s,n,vR.z,null,i)}}else if(e.isLineLoop)console.error("THREE.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 s=t.isArrayCamera?gR:mR;if(!e.frustumCulled||s.intersectsObject(e,t)){const{geometry:t,material:s}=e;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),vR.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(_R)),Array.isArray(s)){const a=t.groups;for(let o=0,l=a.length;o<l;o++){const l=a[o],u=s[l.materialIndex];u&&u.visible&&r.push(e,t,u,n,vR.z,l,i)}}else s.visible&&r.push(e,t,s,n,vR.z,null,i)}}if(!0===e.isBundleGroup&&void 0!==this.backend.beginBundle){const n=r;(r=this._renderLists.get(e,t)).begin(),n.pushBundle({bundleGroup:e,camera:t,renderList:r}),r.finish()}const s=e.children;for(let e=0,a=s.length;e<a;e++)this._projectObject(s[e],t,n,r,i)}_renderBundles(e,t,n){for(const r of e)this._renderBundle(r,t,n)}_renderTransparents(e,t,n,r,i){if(t.length>0){for(const{material:e}of t)e.side=1;this._renderObjects(t,n,r,i,"backSide");for(const{material:e}of t)e.side=0;this._renderObjects(e,n,r,i);for(const{material:e}of t)e.side=2}else this._renderObjects(e,n,r,i)}_renderObjects(e,t,n,r,i=null){for(let s=0,a=e.length;s<a;s++){const{object:a,geometry:o,material:l,group:u,clippingContext:c}=e[s];this._currentRenderObjectFunction(a,n,t,o,l,u,r,c,i)}}renderObject(e,t,n,r,i,s,a,o=null,l=null){let u,c,h;if(e.onBeforeRender(this,t,n,r,i,s),!0===i.allowOverride&&null!==t.overrideMaterial){const e=t.overrideMaterial;i.positionNode&&i.positionNode.isNode&&(u=e.positionNode,e.positionNode=i.positionNode),e.alphaTest=i.alphaTest,e.alphaMap=i.alphaMap,e.transparent=i.transparent||i.transmission>0,e.isShadowPassMaterial&&(e.side=null===i.shadowSide?i.side:i.shadowSide,i.depthNode&&i.depthNode.isNode&&(h=e.depthNode,e.depthNode=i.depthNode),i.castShadowNode&&i.castShadowNode.isNode&&(c=e.colorNode,e.colorNode=i.castShadowNode),i.castShadowPositionNode&&i.castShadowPositionNode.isNode&&(u=e.positionNode,e.positionNode=i.castShadowPositionNode)),i=e}!0===i.transparent&&2===i.side&&!1===i.forceSinglePass?(i.side=1,this._handleObjectFunction(e,i,t,n,a,s,o,"backSide"),i.side=0,this._handleObjectFunction(e,i,t,n,a,s,o,l),i.side=2):this._handleObjectFunction(e,i,t,n,a,s,o,l),void 0!==u&&(t.overrideMaterial.positionNode=u),void 0!==h&&(t.overrideMaterial.depthNode=h),void 0!==c&&(t.overrideMaterial.colorNode=c),e.onAfterRender(this,t,n,r,i,s)}_renderObjectDirect(e,t,n,r,i,s,a,o){const l=this._objects.get(e,t,n,r,i,this._currentRenderContext,a,o);l.drawRange=e.geometry.drawRange,l.group=s;const u=this._nodes.needsRefresh(l);if(u&&(this._nodes.updateBefore(l),this._geometries.updateForRender(l),this._nodes.updateForRender(l),this._bindings.updateForRender(l)),this._pipelines.updateForRender(l),null!==this._currentRenderBundle){this.backend.get(this._currentRenderBundle).renderObjects.push(l),l.bundle=this._currentRenderBundle.bundleGroup}this.backend.draw(l,this.info),u&&this._nodes.updateAfter(l)}_createObjectPipeline(e,t,n,r,i,s,a,o){const l=this._objects.get(e,t,n,r,i,this._currentRenderContext,a,o);l.drawRange=e.geometry.drawRange,l.group=s,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)}get compile(){return this.compileAsync}}class xR{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}clone(){return Object.assign(new this.constructor,this)}}class bR extends xR{constructor(e,t=null){super(e),this.isBuffer=!0,this.bytesPerElement=Float32Array.BYTES_PER_ELEMENT,this._buffer=t}get byteLength(){return(e=this._buffer.byteLength)+(GM-e%GM)%GM;var e}get buffer(){return this._buffer}update(){return!0}}class TR extends bR{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let SR=0;class MR extends TR{constructor(e,t){super("UniformBuffer_"+SR++,e?e.value:null),this.nodeUniform=e,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class wR extends TR{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[]}addUniform(e){return this.uniforms.push(e),this}removeUniform(e){const t=this.uniforms.indexOf(e);return-1!==t&&this.uniforms.splice(t,1),this}get values(){return null===this._values&&(this._values=Array.from(this.buffer)),this._values}get buffer(){let e=this._buffer;if(null===e){const t=this.byteLength;e=new Float32Array(new ArrayBuffer(t)),this._buffer=e}return e}get byteLength(){const e=this.bytesPerElement;let t=0;for(let n=0,r=this.uniforms.length;n<r;n++){const r=this.uniforms[n],i=r.boundary,s=r.itemSize*e,a=t%GM,o=a%i,l=a+o;t+=o,0!==l&&GM-l<s&&(t+=GM-l),r.offset=t/e,t+=s}return Math.ceil(t/GM)*GM}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 console.error("THREE.WebGPUUniformsGroup: Unsupported uniform type.",e)}updateNumber(e){let t=!1;const n=this.values,r=e.getValue(),i=e.offset,s=e.getType();if(n[i]!==r){this._getBufferForType(s)[i]=n[i]=r,t=!0}return t}updateVector2(e){let t=!1;const n=this.values,r=e.getValue(),i=e.offset,s=e.getType();if(n[i+0]!==r.x||n[i+1]!==r.y){const e=this._getBufferForType(s);e[i+0]=n[i+0]=r.x,e[i+1]=n[i+1]=r.y,t=!0}return t}updateVector3(e){let t=!1;const n=this.values,r=e.getValue(),i=e.offset,s=e.getType();if(n[i+0]!==r.x||n[i+1]!==r.y||n[i+2]!==r.z){const e=this._getBufferForType(s);e[i+0]=n[i+0]=r.x,e[i+1]=n[i+1]=r.y,e[i+2]=n[i+2]=r.z,t=!0}return t}updateVector4(e){let t=!1;const n=this.values,r=e.getValue(),i=e.offset,s=e.getType();if(n[i+0]!==r.x||n[i+1]!==r.y||n[i+2]!==r.z||n[i+4]!==r.w){const e=this._getBufferForType(s);e[i+0]=n[i+0]=r.x,e[i+1]=n[i+1]=r.y,e[i+2]=n[i+2]=r.z,e[i+3]=n[i+3]=r.w,t=!0}return t}updateColor(e){let t=!1;const n=this.values,r=e.getValue(),i=e.offset;if(n[i+0]!==r.r||n[i+1]!==r.g||n[i+2]!==r.b){const e=this.buffer;e[i+0]=n[i+0]=r.r,e[i+1]=n[i+1]=r.g,e[i+2]=n[i+2]=r.b,t=!0}return t}updateMatrix3(e){let t=!1;const n=this.values,r=e.getValue().elements,i=e.offset;if(n[i+0]!==r[0]||n[i+1]!==r[1]||n[i+2]!==r[2]||n[i+4]!==r[3]||n[i+5]!==r[4]||n[i+6]!==r[5]||n[i+8]!==r[6]||n[i+9]!==r[7]||n[i+10]!==r[8]){const e=this.buffer;e[i+0]=n[i+0]=r[0],e[i+1]=n[i+1]=r[1],e[i+2]=n[i+2]=r[2],e[i+4]=n[i+4]=r[3],e[i+5]=n[i+5]=r[4],e[i+6]=n[i+6]=r[5],e[i+8]=n[i+8]=r[6],e[i+9]=n[i+9]=r[7],e[i+10]=n[i+10]=r[8],t=!0}return t}updateMatrix4(e){let t=!1;const n=this.values,r=e.getValue().elements,i=e.offset;if(!1===function(e,t,n){for(let r=0,i=t.length;r<i;r++)if(e[n+r]!==t[r])return!1;return!0}(n,r,i)){this.buffer.set(r,i),function(e,t,n){for(let r=0,i=t.length;r<i;r++)e[n+r]=t[r]}(n,r,i),t=!0}return t}_getBufferForType(e){return"int"===e||"ivec2"===e||"ivec3"===e||"ivec4"===e?new Int32Array(this.buffer.buffer):"uint"===e||"uvec2"===e||"uvec3"===e||"uvec4"===e?new Uint32Array(this.buffer.buffer):this.buffer}}let ER=0;class AR extends wR{constructor(e,t){super(e),this.id=ER++,this.groupNode=t,this.isNodeUniformsGroup=!0}}let RR=0;class CR extends xR{constructor(e,t){super(e),this.id=RR++,this.texture=t,this.version=t?t.version:0,this.store=!1,this.generation=null,this.isSampledTexture=!0}needsBindingsUpdate(e){const{texture:t}=this;return e!==this.generation?(this.generation=e,!0):t.isVideoTexture}update(){const{texture:e,version:t}=this;return t!==e.version&&(this.version=e.version,!0)}}class NR extends CR{constructor(e,t,n,r=null){super(e,t?t.value:null),this.textureNode=t,this.groupNode=n,this.access=r}needsBindingsUpdate(e){return this.textureNode.value!==this.texture||super.needsBindingsUpdate(e)}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class PR extends NR{constructor(e,t,n,r=null){super(e,t,n,r),this.isSampledCubeTexture=!0}}class LR extends NR{constructor(e,t,n,r=null){super(e,t,n,r),this.isSampledTexture3D=!0}}const DR={textureDimensions:"textureSize",equals:"equal"},IR={low:"lowp",medium:"mediump",high:"highp"},UR={swizzleAssign:!0,storageBuffer:!1},OR={perspective:"smooth",linear:"noperspective"},FR={centroid:"centroid"},BR="\nprecision highp float;\nprecision highp int;\nprecision highp sampler2D;\nprecision highp sampler3D;\nprecision highp samplerCube;\nprecision highp sampler2DArray;\n\nprecision highp usampler2D;\nprecision highp usampler3D;\nprecision highp usamplerCube;\nprecision highp usampler2DArray;\n\nprecision highp isampler2D;\nprecision highp isampler3D;\nprecision highp isamplerCube;\nprecision highp isampler2DArray;\n\nprecision lowp sampler2DShadow;\nprecision lowp sampler2DArrayShadow;\nprecision lowp samplerCubeShadow;\n";class kR extends bA{constructor(e,t){super(e,t,new GA),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]}}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==nt}getMethod(e){return DR[e]||e}getOutputStructName(){return""}buildFunctionCode(e){const t=e.layout,n=this.flowShaderNode(e),r=[];for(const e of t.inputs)r.push(this.getType(e.type)+" "+e.name);return`${this.getType(t.type)} ${t.name}( ${r.join(", ")} ) {\n\n\t${n.vars}\n\n${n.code}\n\treturn ${n.result};\n\n}`}setupPBO(e){const t=e.value;if(void 0===t.pbo){const e=t.array,n=t.count*t.itemSize,{itemSize:r}=t,i=t.array.constructor.name.toLowerCase().includes("int");let s=i?xe:ye;2===r?s=i?Te:be:3===r?s=i?1032:me:4===r&&(s=i?Se:ge);const a={Float32Array:le,Uint8Array:ne,Uint16Array:se,Uint32Array:oe,Int8Array:re,Int16Array:ie,Int32Array:ae,Uint8ClampedArray:ne},o=Math.pow(2,Math.ceil(Math.log2(Math.sqrt(n/r))));let l=Math.ceil(n/r/o);o*l*r<n&&l++;const u=o*l*r,c=new e.constructor(u);c.set(e,0),t.array=c;const h=new Fi(t.array,o,l,s,a[t.array.constructor.name]||le);h.needsUpdate=!0,h.isPBOTexture=!0;const d=new Dv(h,null,null);d.setPrecision("high"),t.pboNode=d,t.pbo=d.value,this.getUniformFromNode(t.pboNode,"texture",this.shaderStage,this.context.label)}}getPropertyName(e,t=this.shaderStage){return e.isNodeUniform&&!0!==e.node.isTextureNode&&!0!==e.node.isBufferNode?t.charAt(0)+"_"+e.name:super.getPropertyName(e,t)}generatePBO(e){const{node:t,indexNode:n}=e,r=t.value;if(this.renderer.backend.has(r)){this.renderer.backend.get(r).pbo=r.pbo}const i=this.getUniformFromNode(r.pboNode,"texture",this.shaderStage,this.context.label),s=this.getPropertyName(i);this.increaseUsage(n);const a=n.build(this,"uint"),o=this.getDataFromNode(e);let l=o.propertyName;if(void 0===l){const n=this.getVarFromNode(e);l=this.getPropertyName(n);const i=this.getDataFromNode(t);let u=i.propertySizeName;void 0===u&&(u=l+"Size",this.getVarFromNode(t,u,"uint"),this.addLineFlowCode(`${u} = uint( textureSize( ${s}, 0 ).x )`,e),i.propertySizeName=u);const{itemSize:c}=r,h="."+af.join("").slice(0,c),d=`ivec2(${a} % ${u}, ${a} / ${u})`,p=this.generateTextureLoad(null,s,d,null,"0");let f="vec4";r.pbo.type===oe?f="uvec4":r.pbo.type===ae&&(f="ivec4"),this.addLineFlowCode(`${l} = ${f}(${p})${h}`,e),o.propertyName=l}return l}generateTextureLoad(e,t,n,r,i="0"){return r?`texelFetch( ${t}, ivec3( ${n}, ${r} ), ${i} )`:`texelFetch( ${t}, ${n}, ${i} )`}generateTexture(e,t,n,r){return e.isDepthTexture?(r&&(n=`vec4( ${n}, ${r} )`),`texture( ${t}, ${n} ).x`):(r&&(n=`vec3( ${n}, ${r} )`),`texture( ${t}, ${n} )`)}generateTextureLevel(e,t,n,r){return`textureLod( ${t}, ${n}, ${r} )`}generateTextureBias(e,t,n,r){return`texture( ${t}, ${n}, ${r} )`}generateTextureGrad(e,t,n,r){return`textureGrad( ${t}, ${n}, ${r[0]}, ${r[1]} )`}generateTextureCompare(e,t,n,r,i,s=this.shaderStage){if("fragment"===s)return i?`texture( ${t}, vec4( ${n}, ${i}, ${r} ) )`:`texture( ${t}, vec3( ${n}, ${r} ) )`;console.error(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${s} shader.`)}getVars(e){const t=[],n=this.vars[e];if(void 0!==n)for(const e of n)t.push(`${this.getVar(e.type,e.name,e.count)};`);return t.join("\n\t")}getUniforms(e){const t=this.uniforms[e],n=[],r={};for(const i of t){let t=null,s=!1;if("texture"===i.type||"texture3D"===i.type){const e=i.node.value;let n="";!0!==e.isDataTexture&&!0!==e.isData3DTexture||(e.type===oe?n="u":e.type===ae&&(n="i")),t="texture3D"===i.type&&!1===e.isArrayTexture?`${n}sampler3D ${i.name};`:e.compareFunction?!0===e.isArrayTexture?`sampler2DArrayShadow ${i.name};`:`sampler2DShadow ${i.name};`:!0===e.isArrayTexture||!0===e.isDataArrayTexture||!0===e.isCompressedArrayTexture?`${n}sampler2DArray ${i.name};`:`${n}sampler2D ${i.name};`}else if("cubeTexture"===i.type)t=`samplerCube ${i.name};`;else if("buffer"===i.type){const e=i.node,n=this.getType(e.bufferType),r=e.bufferCount,s=r>0?r:"";t=`${e.name} {\n\t${n} ${i.name}[${s}];\n};\n`}else{t=`${this.getVectorType(i.type)} ${this.getPropertyName(i,e)};`,s=!0}const a=i.node.precision;if(null!==a&&(t=IR[a]+" "+t),s){t="\t"+t;const e=i.groupNode.name;(r[e]||(r[e]=[])).push(t)}else t="uniform "+t,n.push(t)}let i="";for(const t in r){const n=r[t];i+=this._getGLSLUniformStruct(e+"_"+t,n.join("\n"))+"\n"}return i+=n.join("\n"),i}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==ae){let n=e;e.isInterleavedBufferAttribute&&(n=e.data);const r=n.array;!1==(r instanceof Uint32Array||r instanceof Int32Array)&&(t=t.slice(1))}return t}getAttributes(e){let t="";if("vertex"===e||"compute"===e){const e=this.getAttributesArray();let n=0;for(const r of e)t+=`layout( location = ${n++} ) in ${r.type} ${r.name};\n`}return t}getStructMembers(e){const t=[];for(const n of e.members)t.push(`\t${n.type} ${n.name};`);return t.join("\n")}getStructs(e){const t=[],n=this.structs[e],r=[];for(const e of n)if(e.output)for(const t of e.members)r.push(`layout( location = ${t.index} ) out ${t.type} ${t.name};`);else{let n="struct "+e.name+" {\n";n+=this.getStructMembers(e),n+="\n};\n",t.push(n)}return 0===r.length&&r.push("layout( location = 0 ) out vec4 fragColor;"),"\n"+r.join("\n")+"\n\n"+t.join("\n")}getVaryings(e){let t="";const n=this.varyings;if("vertex"===e||"compute"===e)for(const r of n){"compute"===e&&(r.needsInterpolation=!0);const n=this.getType(r.type);if(r.needsInterpolation)if(r.interpolationType){t+=`${OR[r.interpolationType]||r.interpolationType} ${FR[r.interpolationSampling]||""} out ${n} ${r.name};\n`}else{t+=`${n.includes("int")||n.includes("uv")||n.includes("iv")?"flat ":""}out ${n} ${r.name};\n`}else t+=`${n} ${r.name};\n`}else if("fragment"===e)for(const e of n)if(e.needsInterpolation){const n=this.getType(e.type);if(e.interpolationType){t+=`${OR[e.interpolationType]||e.interpolationType} ${FR[e.interpolationSampling]||""} in ${n} ${e.name};\n`}else{t+=`${n.includes("int")||n.includes("uv")||n.includes("iv")?"flat ":""}in ${n} ${e.name};\n`}}for(const n of this.builtins[e])t+=`${n};\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`}getDrawIndex(){return this.renderer.backend.extensions.has("WEBGL_multi_draw")?"uint( gl_DrawID )":null}getFrontFacing(){return"gl_FrontFacing"}getFragCoord(){return"gl_FragCoord.xy"}getFragDepth(){return"gl_FragDepth"}enableExtension(e,t,n=this.shaderStage){const r=this.extensions[n]||(this.extensions[n]=new Map);!1===r.has(e)&&r.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 n=this.extensions[e];if(void 0!==n)for(const{name:e,behavior:r}of n.values())t.push(`#extension ${e} : ${r}`);return t.join("\n")}getClipDistance(){return"gl_ClipDistance"}isAvailable(e){let t=UR[e];if(void 0===t){let n;switch(t=!1,e){case"float32Filterable":n="OES_texture_float_linear";break;case"clipDistance":n="WEBGL_clip_cull_distance"}if(void 0!==n){const e=this.renderer.backend.extensions;e.has(n)&&(e.get(n),t=!0)}UR[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 n=0;n<e.length;n++){const r=e[n],i=this.getPropertyName(r.attributeNode);i&&(t+=`${r.varyingName} = ${i};\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${BR}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\n\n// attributes\n${e.attributes}\n\n// codes\n${e.codes}\n\nvoid main() {\n\n\t// vars\n\t${e.vars}\n\n\t// transforms\n\t${e.transforms}\n\n\t// flow\n\t${e.flow}\n\n\tgl_PointSize = 1.0;\n\n}\n`}_getGLSLFragmentCode(e){return`#version 300 es\n\n${this.getSignature()}\n\n// extensions\n${e.extensions}\n\n// precision\n${BR}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\n\n// codes\n${e.codes}\n\n// structs\n${e.structs}\n\nvoid main() {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){let n="// code\n\n";n+=this.flowCode[t];const r=this.flowNodes[t],i=r[r.length-1];for(const e of r){const r=this.getFlowData(e),s=e.name;s&&(n.length>0&&(n+="\n"),n+=`\t// flow -> ${s}\n\t`),n+=`${r.code}\n\t`,e===i&&"compute"!==t&&(n+="// result\n\t","vertex"===t?(n+="gl_Position = ",n+=`${r.result};`):"fragment"===t&&(e.outputNode.isOutputStructNode||(n+="fragColor = ",n+=`${r.result};`)))}const s=e[t];s.extensions=this.getExtensions(t),s.uniforms=this.getUniforms(t),s.attributes=this.getAttributes(t),s.varyings=this.getVaryings(t),s.vars=this.getVars(t),s.structs=this.getStructs(t),s.codes=this.getCodes(t),s.transforms=this.getTransforms(t),s.flow=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,n,r=null){const i=super.getUniformFromNode(e,t,n,r),s=this.getDataFromNode(e,n,this.globalCache);let a=s.uniformGPU;if(void 0===a){const r=e.groupNode,o=r.name,l=this.getBindGroupArray(o,n);if("texture"===t)a=new NR(i.name,i.node,r),l.push(a);else if("cubeTexture"===t)a=new PR(i.name,i.node,r),l.push(a);else if("texture3D"===t)a=new LR(i.name,i.node,r),l.push(a);else if("buffer"===t){e.name=`NodeBuffer_${e.id}`,i.name=`buffer${e.id}`;const t=new MR(e,r);t.name=e.name,l.push(t),a=t}else{const e=this.uniformGroups[n]||(this.uniformGroups[n]={});let s=e[o];void 0===s&&(s=new AR(n+"_"+o,r),e[o]=s,l.push(s)),a=this.getNodeUniform(i,t),s.addUniform(a)}s.uniformGPU=a}return i}}let zR=null,VR=null;class GR{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={render:null,compute: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(){}createSampler(){}destroySampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}isOccluded(){}async resolveTimestampsAsync(e="render"){if(!this.trackTimestamp)return void jt("WebGPURenderer: Timestamp tracking is disabled.");const t=this.timestampQueryPool[e];if(!t)return void jt(`WebGPURenderer: No timestamp query pool for type '${e}' found.`);const n=await t.resolveQueriesAsync();return this.renderer.info[e].timestamp=n,n}async waitForGPU(){}async getArrayBufferAsync(){}async hasFeatureAsync(){}hasFeature(){}getMaxAnisotropy(){}getDrawingBufferSize(){return zR=zR||new Dt,this.renderer.getDrawingBufferSize(zR)}setScissorTest(){}getClearColor(){const e=this.renderer;return VR=VR||new gw,e.getClearColor(VR),VR.getRGB(VR),VR}getDomElement(){let e=this.domElement;return null===e&&(e=void 0!==this.parameters.canvas?this.parameters.canvas:Gt(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${s} webgpu`),this.domElement=e),e}set(e,t){this.data.set(e,t)}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}has(e){return this.data.has(e)}delete(e){this.data.delete(e)}dispose(){}}let HR,jR,WR=0;class XR{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 qR{constructor(e){this.backend=e}createAttribute(e,t){const n=this.backend,{gl:r}=n,i=e.array,s=e.usage||r.STATIC_DRAW,a=e.isInterleavedBufferAttribute?e.data:e,o=n.get(a);let l,u=o.bufferGPU;if(void 0===u&&(u=this._createBuffer(r,t,i,s),o.bufferGPU=u,o.bufferType=t,o.version=a.version),i instanceof Float32Array)l=r.FLOAT;else if("undefined"!=typeof Float16Array&&i instanceof Float16Array)l=r.HALF_FLOAT;else if(i instanceof Uint16Array)l=e.isFloat16BufferAttribute?r.HALF_FLOAT:r.UNSIGNED_SHORT;else if(i instanceof Int16Array)l=r.SHORT;else if(i instanceof Uint32Array)l=r.UNSIGNED_INT;else if(i instanceof Int32Array)l=r.INT;else if(i instanceof Int8Array)l=r.BYTE;else if(i instanceof Uint8Array)l=r.UNSIGNED_BYTE;else{if(!(i instanceof Uint8ClampedArray))throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+i);l=r.UNSIGNED_BYTE}let c={bufferGPU:u,bufferType:t,type:l,byteLength:i.byteLength,bytesPerElement:i.BYTES_PER_ELEMENT,version:e.version,pbo:e.pbo,isInteger:l===r.INT||l===r.UNSIGNED_INT||e.gpuType===ae,id:WR++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(r,t,i,s);c=new XR(c,e)}n.set(e,c)}updateAttribute(e){const t=this.backend,{gl:n}=t,r=e.array,i=e.isInterleavedBufferAttribute?e.data:e,s=t.get(i),a=s.bufferType,o=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(n.bindBuffer(a,s.bufferGPU),0===o.length)n.bufferSubData(a,0,r);else{for(let e=0,t=o.length;e<t;e++){const t=o[e];n.bufferSubData(a,t.start*r.BYTES_PER_ELEMENT,r,t.start,t.count)}i.clearUpdateRanges()}n.bindBuffer(a,null),s.version=i.version}destroyAttribute(e){const t=this.backend,{gl:n}=t;e.isInterleavedBufferAttribute&&t.delete(e.data);const r=t.get(e);n.deleteBuffer(r.bufferGPU),t.delete(e)}async getArrayBufferAsync(e){const t=this.backend,{gl:n}=t,r=e.isInterleavedBufferAttribute?e.data:e,{bufferGPU:i}=t.get(r),s=e.array,a=s.byteLength;n.bindBuffer(n.COPY_READ_BUFFER,i);const o=n.createBuffer();n.bindBuffer(n.COPY_WRITE_BUFFER,o),n.bufferData(n.COPY_WRITE_BUFFER,a,n.STREAM_READ),n.copyBufferSubData(n.COPY_READ_BUFFER,n.COPY_WRITE_BUFFER,0,0,a),await t.utils._clientWaitAsync();const l=new e.array.constructor(s.length);return n.bindBuffer(n.COPY_WRITE_BUFFER,o),n.getBufferSubData(n.COPY_WRITE_BUFFER,0,l),n.deleteBuffer(o),n.bindBuffer(n.COPY_READ_BUFFER,null),n.bindBuffer(n.COPY_WRITE_BUFFER,null),l.buffer}_createBuffer(e,t,n,r){const i=e.createBuffer();return e.bindBuffer(t,i),e.bufferData(t,n,r),e.bindBuffer(t,null),i}}class $R{constructor(e){this.backend=e,this.gl=this.backend.gl,this.enabled={},this.currentFlipSided=null,this.currentCullFace=null,this.currentProgram=null,this.currentBlendingEnabled=!1,this.currentBlending=null,this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentPremultipledAlpha=null,this.currentPolygonOffsetFactor=null,this.currentPolygonOffsetUnits=null,this.currentColorMask=null,this.currentDepthFunc=null,this.currentDepthMask=null,this.currentStencilFunc=null,this.currentStencilRef=null,this.currentStencilFuncMask=null,this.currentStencilFail=null,this.currentStencilZFail=null,this.currentStencilZPass=null,this.currentStencilMask=null,this.currentLineWidth=null,this.currentClippingPlanes=0,this.currentVAO=null,this.currentIndex=null,this.currentBoundFramebuffers={},this.currentDrawbuffers=new WeakMap,this.maxTextures=this.gl.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.currentTextureSlot=null,this.currentBoundTextures={},this.currentBoundBufferBases={},this._init()}_init(){const e=this.gl;HR={[g]:e.FUNC_ADD,[_]:e.FUNC_SUBTRACT,[v]:e.FUNC_REVERSE_SUBTRACT},jR={[y]:e.ZERO,[x]:e.ONE,[b]:e.SRC_COLOR,[S]:e.SRC_ALPHA,[C]:e.SRC_ALPHA_SATURATE,[A]:e.DST_COLOR,[w]:e.DST_ALPHA,[T]:e.ONE_MINUS_SRC_COLOR,[M]:e.ONE_MINUS_SRC_ALPHA,[R]:e.ONE_MINUS_DST_COLOR,[E]:e.ONE_MINUS_DST_ALPHA};const t=e.getParameter(e.SCISSOR_BOX),n=e.getParameter(e.VIEWPORT);this.currentScissor=(new an).fromArray(t),this.currentViewport=(new an).fromArray(n),this._tempVec4=new an}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:n}=this;e!==t&&(n.lineWidth(e),this.currentLineWidth=e)}setBlending(e,t,n,r,i,s,a,o){const{gl:l}=this;if(0!==e){if(!1===this.currentBlendingEnabled&&(this.enable(l.BLEND),this.currentBlendingEnabled=!0),5===e)i=i||t,s=s||n,a=a||r,t===this.currentBlendEquation&&i===this.currentBlendEquationAlpha||(l.blendEquationSeparate(HR[t],HR[i]),this.currentBlendEquation=t,this.currentBlendEquationAlpha=i),n===this.currentBlendSrc&&r===this.currentBlendDst&&s===this.currentBlendSrcAlpha&&a===this.currentBlendDstAlpha||(l.blendFuncSeparate(jR[n],jR[r],jR[s],jR[a]),this.currentBlendSrc=n,this.currentBlendDst=r,this.currentBlendSrcAlpha=s,this.currentBlendDstAlpha=a),this.currentBlending=e,this.currentPremultipledAlpha=!1;else if(e!==this.currentBlending||o!==this.currentPremultipledAlpha){if(this.currentBlendEquation===g&&this.currentBlendEquationAlpha===g||(l.blendEquation(l.FUNC_ADD),this.currentBlendEquation=g,this.currentBlendEquationAlpha=g),o)switch(e){case 1:l.blendFuncSeparate(l.ONE,l.ONE_MINUS_SRC_ALPHA,l.ONE,l.ONE_MINUS_SRC_ALPHA);break;case 2:l.blendFunc(l.ONE,l.ONE);break;case 3:l.blendFuncSeparate(l.ZERO,l.ONE_MINUS_SRC_COLOR,l.ZERO,l.ONE);break;case 4:l.blendFuncSeparate(l.DST_COLOR,l.ONE_MINUS_SRC_ALPHA,l.ZERO,l.ONE);break;default:console.error("THREE.WebGLState: Invalid blending: ",e)}else switch(e){case 1:l.blendFuncSeparate(l.SRC_ALPHA,l.ONE_MINUS_SRC_ALPHA,l.ONE,l.ONE_MINUS_SRC_ALPHA);break;case 2:l.blendFuncSeparate(l.SRC_ALPHA,l.ONE,l.ONE,l.ONE);break;case 3:console.error("THREE.WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case 4:console.error("THREE.WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:console.error("THREE.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(l.BLEND),this.currentBlendingEnabled=!1)}setColorMask(e){this.currentColorMask!==e&&(this.gl.colorMask(e,e,e,e),this.currentColorMask=e)}setDepthTest(e){const{gl:t}=this;e?this.enable(t.DEPTH_TEST):this.disable(t.DEPTH_TEST)}setDepthMask(e){this.currentDepthMask!==e&&(this.gl.depthMask(e),this.currentDepthMask=e)}setDepthFunc(e){if(this.currentDepthFunc!==e){const{gl:t}=this;switch(e){case 0:t.depthFunc(t.NEVER);break;case 1:t.depthFunc(t.ALWAYS);break;case 2:t.depthFunc(t.LESS);break;case 3:default:t.depthFunc(t.LEQUAL);break;case 4:t.depthFunc(t.EQUAL);break;case 5:t.depthFunc(t.GEQUAL);break;case 6:t.depthFunc(t.GREATER);break;case 7:t.depthFunc(t.NOTEQUAL)}this.currentDepthFunc=e}}scissor(e,t,n,r){const i=this._tempVec4.set(e,t,n,r);if(!1===this.currentScissor.equals(i)){const{gl:e}=this;e.scissor(i.x,i.y,i.z,i.w),this.currentScissor.copy(i)}}viewport(e,t,n,r){const i=this._tempVec4.set(e,t,n,r);if(!1===this.currentViewport.equals(i)){const{gl:e}=this;e.viewport(i.x,i.y,i.z,i.w),this.currentViewport.copy(i)}}setScissorTest(e){const t=this.gl;e?t.enable(t.SCISSOR_TEST):t.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,n){this.currentStencilFunc===e&&this.currentStencilRef===t&&this.currentStencilFuncMask===n||(this.gl.stencilFunc(e,t,n),this.currentStencilFunc=e,this.currentStencilRef=t,this.currentStencilFuncMask=n)}setStencilOp(e,t,n){this.currentStencilFail===e&&this.currentStencilZFail===t&&this.currentStencilZPass===n||(this.gl.stencilOp(e,t,n),this.currentStencilFail=e,this.currentStencilZFail=t,this.currentStencilZPass=n)}setMaterial(e,t,n){const{gl:r}=this;2===e.side?this.disable(r.CULL_FACE):this.enable(r.CULL_FACE);let i=1===e.side;t&&(i=!i),this.setFlipSided(i),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 s=e.stencilWrite;if(this.setStencilTest(s),s&&(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.samples>1?this.enable(r.SAMPLE_ALPHA_TO_COVERAGE):this.disable(r.SAMPLE_ALPHA_TO_COVERAGE),n>0&&this.currentClippingPlanes!==n){const e=12288;for(let t=0;t<8;t++)t<n?this.enable(e+t):this.disable(e+t)}}setPolygonOffset(e,t,n){const{gl:r}=this;e?(this.enable(r.POLYGON_OFFSET_FILL),this.currentPolygonOffsetFactor===t&&this.currentPolygonOffsetUnits===n||(r.polygonOffset(t,n),this.currentPolygonOffsetFactor=t,this.currentPolygonOffsetUnits=n)):this.disable(r.POLYGON_OFFSET_FILL)}useProgram(e){return this.currentProgram!==e&&(this.gl.useProgram(e),this.currentProgram=e,!0)}setVertexState(e,t=null){const n=this.gl;return(this.currentVAO!==e||this.currentIndex!==t)&&(n.bindVertexArray(e),null!==t&&n.bindBuffer(n.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:n,currentBoundFramebuffers:r}=this;return r[e]!==t&&(n.bindFramebuffer(e,t),r[e]=t,e===n.DRAW_FRAMEBUFFER&&(r[n.FRAMEBUFFER]=t),e===n.FRAMEBUFFER&&(r[n.DRAW_FRAMEBUFFER]=t),!0)}drawBuffers(e,t){const{gl:n}=this;let r=[],i=!1;if(null!==e.textures){r=this.currentDrawbuffers.get(t),void 0===r&&(r=[],this.currentDrawbuffers.set(t,r));const s=e.textures;if(r.length!==s.length||r[0]!==n.COLOR_ATTACHMENT0){for(let e=0,t=s.length;e<t;e++)r[e]=n.COLOR_ATTACHMENT0+e;r.length=s.length,i=!0}}else r[0]!==n.BACK&&(r[0]=n.BACK,i=!0);i&&n.drawBuffers(r)}activeTexture(e){const{gl:t,currentTextureSlot:n,maxTextures:r}=this;void 0===e&&(e=t.TEXTURE0+r-1),n!==e&&(t.activeTexture(e),this.currentTextureSlot=e)}bindTexture(e,t,n){const{gl:r,currentTextureSlot:i,currentBoundTextures:s,maxTextures:a}=this;void 0===n&&(n=null===i?r.TEXTURE0+a-1:i);let o=s[n];void 0===o&&(o={type:void 0,texture:void 0},s[n]=o),o.type===e&&o.texture===t||(i!==n&&(r.activeTexture(n),this.currentTextureSlot=n),r.bindTexture(e,t),o.type=e,o.texture=t)}bindBufferBase(e,t,n){const{gl:r}=this,i=`${e}-${t}`;return this.currentBoundBufferBases[i]!==n&&(r.bindBufferBase(e,t,n),this.currentBoundBufferBases[i]=n,!0)}unbindTexture(){const{gl:e,currentTextureSlot:t,currentBoundTextures:n}=this,r=n[t];void 0!==r&&void 0!==r.type&&(e.bindTexture(r.type,null),r.type=void 0,r.texture=void 0)}}class YR{constructor(e){this.backend=e,this.gl=this.backend.gl,this.extensions=e.extensions}convert(e,t=""){const{gl:n,extensions:r}=this;let i;const s=$t.getTransfer(t);if(e===ne)return n.UNSIGNED_BYTE;if(e===ce)return n.UNSIGNED_SHORT_4_4_4_4;if(e===he)return n.UNSIGNED_SHORT_5_5_5_1;if(e===pe)return n.UNSIGNED_INT_5_9_9_9_REV;if(e===re)return n.BYTE;if(e===ie)return n.SHORT;if(e===se)return n.UNSIGNED_SHORT;if(e===ae)return n.INT;if(e===oe)return n.UNSIGNED_INT;if(e===le)return n.FLOAT;if(e===ue)return n.HALF_FLOAT;if(e===fe)return n.ALPHA;if(e===me)return n.RGB;if(e===ge)return n.RGBA;if(e===_e)return n.DEPTH_COMPONENT;if(e===ve)return n.DEPTH_STENCIL;if(e===ye)return n.RED;if(e===xe)return n.RED_INTEGER;if(e===be)return n.RG;if(e===Te)return n.RG_INTEGER;if(e===Se)return n.RGBA_INTEGER;if(e===Me||e===we||e===Ee||e===Ae)if(s===at){if(i=r.get("WEBGL_compressed_texture_s3tc_srgb"),null===i)return null;if(e===Me)return i.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(e===we)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(e===Ee)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(e===Ae)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(i=r.get("WEBGL_compressed_texture_s3tc"),null===i)return null;if(e===Me)return i.COMPRESSED_RGB_S3TC_DXT1_EXT;if(e===we)return i.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(e===Ee)return i.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(e===Ae)return i.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(e===Re||e===Ce||e===Ne||e===Pe){if(i=r.get("WEBGL_compressed_texture_pvrtc"),null===i)return null;if(e===Re)return i.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(e===Ce)return i.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(e===Ne)return i.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(e===Pe)return i.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(e===Le||e===De||e===Ie){if(i=r.get("WEBGL_compressed_texture_etc"),null===i)return null;if(e===Le||e===De)return s===at?i.COMPRESSED_SRGB8_ETC2:i.COMPRESSED_RGB8_ETC2;if(e===Ie)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:i.COMPRESSED_RGBA8_ETC2_EAC}if(e===Ue||e===Oe||e===Fe||e===Be||e===ke||e===ze||e===Ve||e===Ge||e===He||e===je||e===We||e===Xe||e===qe||e===$e){if(i=r.get("WEBGL_compressed_texture_astc"),null===i)return null;if(e===Ue)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:i.COMPRESSED_RGBA_ASTC_4x4_KHR;if(e===Oe)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:i.COMPRESSED_RGBA_ASTC_5x4_KHR;if(e===Fe)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:i.COMPRESSED_RGBA_ASTC_5x5_KHR;if(e===Be)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:i.COMPRESSED_RGBA_ASTC_6x5_KHR;if(e===ke)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:i.COMPRESSED_RGBA_ASTC_6x6_KHR;if(e===ze)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:i.COMPRESSED_RGBA_ASTC_8x5_KHR;if(e===Ve)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:i.COMPRESSED_RGBA_ASTC_8x6_KHR;if(e===Ge)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:i.COMPRESSED_RGBA_ASTC_8x8_KHR;if(e===He)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:i.COMPRESSED_RGBA_ASTC_10x5_KHR;if(e===je)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:i.COMPRESSED_RGBA_ASTC_10x6_KHR;if(e===We)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:i.COMPRESSED_RGBA_ASTC_10x8_KHR;if(e===Xe)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:i.COMPRESSED_RGBA_ASTC_10x10_KHR;if(e===qe)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:i.COMPRESSED_RGBA_ASTC_12x10_KHR;if(e===$e)return s===at?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:i.COMPRESSED_RGBA_ASTC_12x12_KHR}if(e===Ye){if(i=r.get("EXT_texture_compression_bptc"),null===i)return null;if(e===Ye)return s===at?i.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:i.COMPRESSED_RGBA_BPTC_UNORM_EXT}if(e===Ze||e===Je||e===et||e===tt){if(i=r.get("EXT_texture_compression_rgtc"),null===i)return null;if(e===Ye)return i.COMPRESSED_RED_RGTC1_EXT;if(e===Je)return i.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(e===et)return i.COMPRESSED_RED_GREEN_RGTC2_EXT;if(e===tt)return i.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}return e===de?n.UNSIGNED_INT_24_8:void 0!==n[e]?n[e]:null}_clientWaitAsync(){const{gl:e}=this,t=e.fenceSync(e.SYNC_GPU_COMMANDS_COMPLETE,0);return e.flush(),new Promise((n,r)=>{!function i(){const s=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(s===e.WAIT_FAILED)return e.deleteSync(t),void r();s!==e.TIMEOUT_EXPIRED?(e.deleteSync(t),n()):requestAnimationFrame(i)}()})}}let KR,QR,ZR,JR=!1;class eC{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},!1===JR&&(this._init(),JR=!0)}_init(){const e=this.gl;KR={[q]:e.REPEAT,[$]:e.CLAMP_TO_EDGE,[Y]:e.MIRRORED_REPEAT},QR={[K]:e.NEAREST,[Q]:e.NEAREST_MIPMAP_NEAREST,[Z]:e.NEAREST_MIPMAP_LINEAR,[J]:e.LINEAR,[ee]:e.LINEAR_MIPMAP_NEAREST,[te]:e.LINEAR_MIPMAP_LINEAR},ZR={[lt]:e.NEVER,[mt]:e.ALWAYS,[ut]:e.LESS,[ht]:e.LEQUAL,[ct]:e.EQUAL,[ft]:e.GEQUAL,[dt]:e.GREATER,[pt]:e.NOTEQUAL}}getGLTextureType(e){const{gl:t}=this;let n;return n=!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,n}getInternalFormat(e,t,n,r,i=!1){const{gl:s,extensions:a}=this;if(null!==e){if(void 0!==s[e])return s[e];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+e+"'")}let o=t;if(t===s.RED&&(n===s.FLOAT&&(o=s.R32F),n===s.HALF_FLOAT&&(o=s.R16F),n===s.UNSIGNED_BYTE&&(o=s.R8),n===s.UNSIGNED_SHORT&&(o=s.R16),n===s.UNSIGNED_INT&&(o=s.R32UI),n===s.BYTE&&(o=s.R8I),n===s.SHORT&&(o=s.R16I),n===s.INT&&(o=s.R32I)),t===s.RED_INTEGER&&(n===s.UNSIGNED_BYTE&&(o=s.R8UI),n===s.UNSIGNED_SHORT&&(o=s.R16UI),n===s.UNSIGNED_INT&&(o=s.R32UI),n===s.BYTE&&(o=s.R8I),n===s.SHORT&&(o=s.R16I),n===s.INT&&(o=s.R32I)),t===s.RG&&(n===s.FLOAT&&(o=s.RG32F),n===s.HALF_FLOAT&&(o=s.RG16F),n===s.UNSIGNED_BYTE&&(o=s.RG8),n===s.UNSIGNED_SHORT&&(o=s.RG16),n===s.UNSIGNED_INT&&(o=s.RG32UI),n===s.BYTE&&(o=s.RG8I),n===s.SHORT&&(o=s.RG16I),n===s.INT&&(o=s.RG32I)),t===s.RG_INTEGER&&(n===s.UNSIGNED_BYTE&&(o=s.RG8UI),n===s.UNSIGNED_SHORT&&(o=s.RG16UI),n===s.UNSIGNED_INT&&(o=s.RG32UI),n===s.BYTE&&(o=s.RG8I),n===s.SHORT&&(o=s.RG16I),n===s.INT&&(o=s.RG32I)),t===s.RGB){const e=i?st:$t.getTransfer(r);n===s.FLOAT&&(o=s.RGB32F),n===s.HALF_FLOAT&&(o=s.RGB16F),n===s.UNSIGNED_BYTE&&(o=s.RGB8),n===s.UNSIGNED_SHORT&&(o=s.RGB16),n===s.UNSIGNED_INT&&(o=s.RGB32UI),n===s.BYTE&&(o=s.RGB8I),n===s.SHORT&&(o=s.RGB16I),n===s.INT&&(o=s.RGB32I),n===s.UNSIGNED_BYTE&&(o=e===at?s.SRGB8:s.RGB8),n===s.UNSIGNED_SHORT_5_6_5&&(o=s.RGB565),n===s.UNSIGNED_SHORT_5_5_5_1&&(o=s.RGB5_A1),n===s.UNSIGNED_SHORT_4_4_4_4&&(o=s.RGB4),n===s.UNSIGNED_INT_5_9_9_9_REV&&(o=s.RGB9_E5)}if(t===s.RGB_INTEGER&&(n===s.UNSIGNED_BYTE&&(o=s.RGB8UI),n===s.UNSIGNED_SHORT&&(o=s.RGB16UI),n===s.UNSIGNED_INT&&(o=s.RGB32UI),n===s.BYTE&&(o=s.RGB8I),n===s.SHORT&&(o=s.RGB16I),n===s.INT&&(o=s.RGB32I)),t===s.RGBA){const e=i?st:$t.getTransfer(r);n===s.FLOAT&&(o=s.RGBA32F),n===s.HALF_FLOAT&&(o=s.RGBA16F),n===s.UNSIGNED_BYTE&&(o=s.RGBA8),n===s.UNSIGNED_SHORT&&(o=s.RGBA16),n===s.UNSIGNED_INT&&(o=s.RGBA32UI),n===s.BYTE&&(o=s.RGBA8I),n===s.SHORT&&(o=s.RGBA16I),n===s.INT&&(o=s.RGBA32I),n===s.UNSIGNED_BYTE&&(o=e===at?s.SRGB8_ALPHA8:s.RGBA8),n===s.UNSIGNED_SHORT_4_4_4_4&&(o=s.RGBA4),n===s.UNSIGNED_SHORT_5_5_5_1&&(o=s.RGB5_A1)}return t===s.RGBA_INTEGER&&(n===s.UNSIGNED_BYTE&&(o=s.RGBA8UI),n===s.UNSIGNED_SHORT&&(o=s.RGBA16UI),n===s.UNSIGNED_INT&&(o=s.RGBA32UI),n===s.BYTE&&(o=s.RGBA8I),n===s.SHORT&&(o=s.RGBA16I),n===s.INT&&(o=s.RGBA32I)),t===s.DEPTH_COMPONENT&&(n===s.UNSIGNED_SHORT&&(o=s.DEPTH_COMPONENT16),n===s.UNSIGNED_INT&&(o=s.DEPTH_COMPONENT24),n===s.FLOAT&&(o=s.DEPTH_COMPONENT32F)),t===s.DEPTH_STENCIL&&n===s.UNSIGNED_INT_24_8&&(o=s.DEPTH24_STENCIL8),o!==s.R16F&&o!==s.R32F&&o!==s.RG16F&&o!==s.RG32F&&o!==s.RGBA16F&&o!==s.RGBA32F||a.get("EXT_color_buffer_float"),o}setTextureParameters(e,t){const{gl:n,extensions:r,backend:i}=this,s=$t.getPrimaries($t.workingColorSpace),a=t.colorSpace===nt?null:$t.getPrimaries(t.colorSpace),o=t.colorSpace===nt||s===a?n.NONE:n.BROWSER_DEFAULT_WEBGL;n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,t.flipY),n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),n.pixelStorei(n.UNPACK_ALIGNMENT,t.unpackAlignment),n.pixelStorei(n.UNPACK_COLORSPACE_CONVERSION_WEBGL,o),n.texParameteri(e,n.TEXTURE_WRAP_S,KR[t.wrapS]),n.texParameteri(e,n.TEXTURE_WRAP_T,KR[t.wrapT]),e!==n.TEXTURE_3D&&e!==n.TEXTURE_2D_ARRAY||t.isArrayTexture||n.texParameteri(e,n.TEXTURE_WRAP_R,KR[t.wrapR]),n.texParameteri(e,n.TEXTURE_MAG_FILTER,QR[t.magFilter]);const l=void 0!==t.mipmaps&&t.mipmaps.length>0,u=t.minFilter===J&&l?te:t.minFilter;if(n.texParameteri(e,n.TEXTURE_MIN_FILTER,QR[u]),t.compareFunction&&(n.texParameteri(e,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE),n.texParameteri(e,n.TEXTURE_COMPARE_FUNC,ZR[t.compareFunction])),!0===r.has("EXT_texture_filter_anisotropic")){if(t.magFilter===K)return;if(t.minFilter!==Z&&t.minFilter!==te)return;if(t.type===le&&!1===r.has("OES_texture_float_linear"))return;if(t.anisotropy>1){const s=r.get("EXT_texture_filter_anisotropic");n.texParameterf(e,s.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,i.getMaxAnisotropy()))}}}createDefaultTexture(e){const{gl:t,backend:n,defaultTextures:r}=this,i=this.getGLTextureType(e);let s=r[i];void 0===s&&(s=t.createTexture(),n.state.bindTexture(i,s),t.texParameteri(i,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(i,t.TEXTURE_MAG_FILTER,t.NEAREST),r[i]=s),n.set(e,{textureGPU:s,glTextureType:i,isDefault:!0})}createTexture(e,t){const{gl:n,backend:r}=this,{levels:i,width:s,height:a,depth:o}=t,l=r.utils.convert(e.format,e.colorSpace),u=r.utils.convert(e.type),c=this.getInternalFormat(e.internalFormat,l,u,e.colorSpace,e.isVideoTexture),h=n.createTexture(),d=this.getGLTextureType(e);r.state.bindTexture(d,h),this.setTextureParameters(d,e),e.isArrayTexture||e.isDataArrayTexture||e.isCompressedArrayTexture?n.texStorage3D(n.TEXTURE_2D_ARRAY,i,c,s,a,o):e.isData3DTexture?n.texStorage3D(n.TEXTURE_3D,i,c,s,a,o):e.isVideoTexture||n.texStorage2D(d,i,c,s,a),r.set(e,{textureGPU:h,glTextureType:d,glFormat:l,glType:u,glInternalFormat:c})}copyBufferToTexture(e,t){const{gl:n,backend:r}=this,{textureGPU:i,glTextureType:s,glFormat:a,glType:o}=r.get(t),{width:l,height:u}=t.source.data;n.bindBuffer(n.PIXEL_UNPACK_BUFFER,e),r.state.bindTexture(s,i),n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!1),n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),n.texSubImage2D(s,0,0,0,l,u,a,o,0),n.bindBuffer(n.PIXEL_UNPACK_BUFFER,null),r.state.unbindTexture()}updateTexture(e,t){const{gl:n}=this,{width:r,height:i}=t,{textureGPU:s,glTextureType:a,glFormat:o,glType:l,glInternalFormat:u}=this.backend.get(e);if(!e.isRenderTargetTexture&&void 0!==s)if(this.backend.state.bindTexture(a,s),this.setTextureParameters(a,e),e.isCompressedTexture){const r=e.mipmaps,i=t.image;for(let t=0;t<r.length;t++){const s=r[t];e.isCompressedArrayTexture?e.format!==n.RGBA?null!==o?n.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,t,0,0,0,s.width,s.height,i.depth,o,s.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):n.texSubImage3D(n.TEXTURE_2D_ARRAY,t,0,0,0,s.width,s.height,i.depth,o,l,s.data):null!==o?n.compressedTexSubImage2D(n.TEXTURE_2D,t,0,0,s.width,s.height,o,s.data):console.warn("Unsupported compressed texture format")}}else if(e.isCubeTexture){const e=t.images;for(let t=0;t<6;t++){const s=tC(e[t]);n.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,r,i,o,l,s)}}else if(e.isDataArrayTexture||e.isArrayTexture){const e=t.image;n.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,0,e.width,e.height,e.depth,o,l,e.data)}else if(e.isData3DTexture){const e=t.image;n.texSubImage3D(n.TEXTURE_3D,0,0,0,0,e.width,e.height,e.depth,o,l,e.data)}else if(e.isVideoTexture)e.update(),n.texImage2D(a,0,u,o,l,t.image);else{const e=tC(t.image);n.texSubImage2D(a,0,0,0,r,i,o,l,e)}}generateMipmaps(e){const{gl:t,backend:n}=this,{textureGPU:r,glTextureType:i}=n.get(e);n.state.bindTexture(i,r),t.generateMipmap(i)}deallocateRenderBuffers(e){const{gl:t,backend:n}=this;if(e){const r=n.get(e);if(r.renderBufferStorageSetup=void 0,r.framebuffers){for(const e in r.framebuffers)t.deleteFramebuffer(r.framebuffers[e]);delete r.framebuffers}if(r.depthRenderbuffer&&(t.deleteRenderbuffer(r.depthRenderbuffer),delete r.depthRenderbuffer),r.stencilRenderbuffer&&(t.deleteRenderbuffer(r.stencilRenderbuffer),delete r.stencilRenderbuffer),r.msaaFrameBuffer&&(t.deleteFramebuffer(r.msaaFrameBuffer),delete r.msaaFrameBuffer),r.msaaRenderbuffers){for(let e=0;e<r.msaaRenderbuffers.length;e++)t.deleteRenderbuffer(r.msaaRenderbuffers[e]);delete r.msaaRenderbuffers}}}destroyTexture(e){const{gl:t,backend:n}=this,{textureGPU:r,renderTarget:i}=n.get(e);this.deallocateRenderBuffers(i),t.deleteTexture(r),n.delete(e)}copyTextureToTexture(e,t,n=null,r=null,i=0,s=0){const{gl:a,backend:o}=this,{state:l}=this.backend,{textureGPU:u,glTextureType:c,glType:h,glFormat:d}=o.get(t);let p,f,m,g,_,v,y,x,b;l.bindTexture(c,u);const T=e.isCompressedTexture?e.mipmaps[s]:e.image;if(null!==n)p=n.max.x-n.min.x,f=n.max.y-n.min.y,m=n.isBox3?n.max.z-n.min.z:1,g=n.min.x,_=n.min.y,v=n.isBox3?n.min.z:0;else{const t=Math.pow(2,-i);p=Math.floor(T.width*t),f=Math.floor(T.height*t),m=e.isDataArrayTexture||e.isArrayTexture?T.depth:e.isData3DTexture?Math.floor(T.depth*t):1,g=0,_=0,v=0}null!==r?(y=r.x,x=r.y,b=r.z):(y=0,x=0,b=0),a.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,t.flipY),a.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),a.pixelStorei(a.UNPACK_ALIGNMENT,t.unpackAlignment);const S=a.getParameter(a.UNPACK_ROW_LENGTH),M=a.getParameter(a.UNPACK_IMAGE_HEIGHT),w=a.getParameter(a.UNPACK_SKIP_PIXELS),E=a.getParameter(a.UNPACK_SKIP_ROWS),A=a.getParameter(a.UNPACK_SKIP_IMAGES);a.pixelStorei(a.UNPACK_ROW_LENGTH,T.width),a.pixelStorei(a.UNPACK_IMAGE_HEIGHT,T.height),a.pixelStorei(a.UNPACK_SKIP_PIXELS,g),a.pixelStorei(a.UNPACK_SKIP_ROWS,_),a.pixelStorei(a.UNPACK_SKIP_IMAGES,v);const R=t.isDataArrayTexture||t.isData3DTexture||t.isArrayTexture;if(e.isRenderTargetTexture||e.isDepthTexture){const n=o.get(e),r=o.get(t),i=o.get(n.renderTarget),s=o.get(r.renderTarget),u=i.framebuffers[n.cacheKey],c=s.framebuffers[r.cacheKey];l.bindFramebuffer(a.READ_FRAMEBUFFER,u),l.bindFramebuffer(a.DRAW_FRAMEBUFFER,c);let h=a.COLOR_BUFFER_BIT;e.isDepthTexture&&(h=a.DEPTH_BUFFER_BIT),a.blitFramebuffer(g,_,p,f,y,x,p,f,h,a.NEAREST),l.bindFramebuffer(a.READ_FRAMEBUFFER,null),l.bindFramebuffer(a.DRAW_FRAMEBUFFER,null)}else R?e.isDataTexture||e.isData3DTexture?a.texSubImage3D(c,s,y,x,b,p,f,m,d,h,T.data):t.isCompressedArrayTexture?a.compressedTexSubImage3D(c,s,y,x,b,p,f,m,d,T.data):a.texSubImage3D(c,s,y,x,b,p,f,m,d,h,T):e.isDataTexture?a.texSubImage2D(c,s,y,x,p,f,d,h,T.data):e.isCompressedTexture?a.compressedTexSubImage2D(c,s,y,x,T.width,T.height,d,T.data):a.texSubImage2D(c,s,y,x,p,f,d,h,T);a.pixelStorei(a.UNPACK_ROW_LENGTH,S),a.pixelStorei(a.UNPACK_IMAGE_HEIGHT,M),a.pixelStorei(a.UNPACK_SKIP_PIXELS,w),a.pixelStorei(a.UNPACK_SKIP_ROWS,E),a.pixelStorei(a.UNPACK_SKIP_IMAGES,A),0===s&&t.generateMipmaps&&a.generateMipmap(c),l.unbindTexture()}copyFramebufferToTexture(e,t,n){const{gl:r}=this,{state:i}=this.backend,{textureGPU:s}=this.backend.get(e),{x:a,y:o,z:l,w:u}=n,c=!0===e.isDepthTexture||t.renderTarget&&t.renderTarget.samples>0,h=t.renderTarget?t.renderTarget.height:this.backend.getDrawingBufferSize().y;if(c){const n=0!==a||0!==o;let c,d;if(!0===e.isDepthTexture?(c=r.DEPTH_BUFFER_BIT,d=r.DEPTH_ATTACHMENT,t.stencil&&(c|=r.STENCIL_BUFFER_BIT)):(c=r.COLOR_BUFFER_BIT,d=r.COLOR_ATTACHMENT0),n){const e=this.backend.get(t.renderTarget),n=e.framebuffers[t.getCacheKey()],d=e.msaaFrameBuffer;i.bindFramebuffer(r.DRAW_FRAMEBUFFER,n),i.bindFramebuffer(r.READ_FRAMEBUFFER,d);const p=h-o-u;r.blitFramebuffer(a,p,a+l,p+u,a,p,a+l,p+u,c,r.NEAREST),i.bindFramebuffer(r.READ_FRAMEBUFFER,n),i.bindTexture(r.TEXTURE_2D,s),r.copyTexSubImage2D(r.TEXTURE_2D,0,0,0,a,p,l,u),i.unbindTexture()}else{const e=r.createFramebuffer();i.bindFramebuffer(r.DRAW_FRAMEBUFFER,e),r.framebufferTexture2D(r.DRAW_FRAMEBUFFER,d,r.TEXTURE_2D,s,0),r.blitFramebuffer(0,0,l,u,0,0,l,u,c,r.NEAREST),r.deleteFramebuffer(e)}}else i.bindTexture(r.TEXTURE_2D,s),r.copyTexSubImage2D(r.TEXTURE_2D,0,0,0,a,h-u-o,l,u),i.unbindTexture();e.generateMipmaps&&this.generateMipmaps(e),this.backend._setFramebuffer(t)}setupRenderBufferStorage(e,t,n,r=!1){const{gl:i}=this,s=t.renderTarget,{depthTexture:a,depthBuffer:o,stencilBuffer:l,width:u,height:c}=s;if(i.bindRenderbuffer(i.RENDERBUFFER,e),o&&!l){let t=i.DEPTH_COMPONENT24;if(!0===r){this.extensions.get("WEBGL_multisampled_render_to_texture").renderbufferStorageMultisampleEXT(i.RENDERBUFFER,s.samples,t,u,c)}else n>0?(a&&a.isDepthTexture&&a.type===i.FLOAT&&(t=i.DEPTH_COMPONENT32F),i.renderbufferStorageMultisample(i.RENDERBUFFER,n,t,u,c)):i.renderbufferStorage(i.RENDERBUFFER,t,u,c);i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,e)}else o&&l&&(n>0?i.renderbufferStorageMultisample(i.RENDERBUFFER,n,i.DEPTH24_STENCIL8,u,c):i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH_STENCIL,u,c),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_STENCIL_ATTACHMENT,i.RENDERBUFFER,e));i.bindRenderbuffer(i.RENDERBUFFER,null)}async copyTextureToBuffer(e,t,n,r,i,s){const{backend:a,gl:o}=this,{textureGPU:l,glFormat:u,glType:c}=this.backend.get(e),h=o.createFramebuffer();o.bindFramebuffer(o.READ_FRAMEBUFFER,h);const d=e.isCubeTexture?o.TEXTURE_CUBE_MAP_POSITIVE_X+s:o.TEXTURE_2D;o.framebufferTexture2D(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,d,l,0);const p=this._getTypedArrayType(c),f=r*i*this._getBytesPerTexel(c,u),m=o.createBuffer();o.bindBuffer(o.PIXEL_PACK_BUFFER,m),o.bufferData(o.PIXEL_PACK_BUFFER,f,o.STREAM_READ),o.readPixels(t,n,r,i,u,c,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),await a.utils._clientWaitAsync();const g=new p(f/p.BYTES_PER_ELEMENT);return o.bindBuffer(o.PIXEL_PACK_BUFFER,m),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,g),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),o.deleteFramebuffer(h),g}_getTypedArrayType(e){const{gl:t}=this;if(e===t.UNSIGNED_BYTE)return Uint8Array;if(e===t.UNSIGNED_SHORT_4_4_4_4)return Uint16Array;if(e===t.UNSIGNED_SHORT_5_5_5_1)return Uint16Array;if(e===t.UNSIGNED_SHORT_5_6_5)return Uint16Array;if(e===t.UNSIGNED_SHORT)return Uint16Array;if(e===t.UNSIGNED_INT)return Uint32Array;if(e===t.HALF_FLOAT)return Uint16Array;if(e===t.FLOAT)return Float32Array;throw new Error(`Unsupported WebGL type: ${e}`)}_getBytesPerTexel(e,t){const{gl:n}=this;let r=0;return e===n.UNSIGNED_BYTE&&(r=1),e!==n.UNSIGNED_SHORT_4_4_4_4&&e!==n.UNSIGNED_SHORT_5_5_5_1&&e!==n.UNSIGNED_SHORT_5_6_5&&e!==n.UNSIGNED_SHORT&&e!==n.HALF_FLOAT||(r=2),e!==n.UNSIGNED_INT&&e!==n.FLOAT||(r=4),t===n.RGBA?4*r:t===n.RGB?3*r:t===n.ALPHA?r:void 0}}function tC(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 nC{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 rC{constructor(e){this.backend=e,this.maxAnisotropy=null}getMaxAnisotropy(){if(null!==this.maxAnisotropy)return this.maxAnisotropy;const e=this.backend.gl,t=this.backend.extensions;if(!0===t.has("EXT_texture_filter_anisotropic")){const n=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else this.maxAnisotropy=0;return this.maxAnisotropy}}const iC={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",WEBKIT_WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBGL_compressed_texture_s3tc:"texture-compression-bc",EXT_texture_compression_bptc:"texture-compression-bptc",EXT_disjoint_timer_query_webgl2:"timestamp-query",OVR_multiview2:"OVR_multiview2"};class sC{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:n,mode:r,object:i,type:s,info:a,index:o}=this;0!==o?n.drawElements(r,t,s,e):n.drawArrays(r,e,t),a.update(i,t,1)}renderInstances(e,t,n){const{gl:r,mode:i,type:s,index:a,object:o,info:l}=this;0!==n&&(0!==a?r.drawElementsInstanced(i,t,s,e,n):r.drawArraysInstanced(i,e,t,n),l.update(o,t,n))}renderMultiDraw(e,t,n){const{extensions:r,mode:i,object:s,info:a}=this;if(0===n)return;const o=r.get("WEBGL_multi_draw");if(null===o)for(let r=0;r<n;r++)this.render(e[r],t[r]);else{0!==this.index?o.multiDrawElementsWEBGL(i,t,0,this.type,e,0,n):o.multiDrawArraysWEBGL(i,e,0,t,0,n);let r=0;for(let e=0;e<n;e++)r+=t[e];a.update(s,r,1)}}renderMultiDrawInstances(e,t,n,r){const{extensions:i,mode:s,object:a,info:o}=this;if(0===n)return;const l=i.get("WEBGL_multi_draw");if(null===l)for(let i=0;i<n;i++)this.renderInstances(e[i],t[i],r[i]);else{0!==this.index?l.multiDrawElementsInstancedWEBGL(s,t,0,this.type,e,0,r,0,n):l.multiDrawArraysInstancedWEBGL(s,e,0,t,0,r,0,n);let i=0;for(let e=0;e<n;e++)i+=t[e]*r[e];o.update(a,i,1)}}}class aC{constructor(e=256){this.trackTimestamp=!0,this.maxQueries=e,this.currentQueryIndex=0,this.queryOffsets=new Map,this.isDisposed=!1,this.lastValue=0,this.pendingResolve=!1}allocateQueriesForContext(){}async resolveQueriesAsync(){}dispose(){}}class oC extends aC{constructor(e,t,n=2048){if(super(n),this.gl=e,this.type=t,this.ext=e.getExtension("EXT_disjoint_timer_query_webgl2")||e.getExtension("EXT_disjoint_timer_query"),!this.ext)return console.warn("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 jt(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryStates.set(t,"inactive"),this.queryOffsets.set(e.id,t),t}beginQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e.id);if(null==t)return;if(null!==this.activeQuery)return;const n=this.queries[t];if(n)try{"inactive"===this.queryStates.get(t)&&(this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,n),this.activeQuery=t,this.queryStates.set(t,"started"))}catch(e){console.error("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.id);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){console.error("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=[];for(const[t,n]of this.queryStates)if("ended"===n){const n=this.queries[t];e.push(this.resolveQuery(n))}if(0===e.length)return this.lastValue;const t=(await Promise.all(e)).reduce((e,t)=>e+t,0);return this.lastValue=t,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,t}catch(e){return console.error("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 n,r=!1;const i=e=>{r||(r=!0,n&&(clearTimeout(n),n=null),t(e))},s=()=>{if(this.isDisposed)i(this.lastValue);else try{if(this.gl.getParameter(this.ext.GPU_DISJOINT_EXT))return void i(this.lastValue);if(!this.gl.getQueryParameter(e,this.gl.QUERY_RESULT_AVAILABLE))return void(n=setTimeout(s,1));const r=this.gl.getQueryParameter(e,this.gl.QUERY_RESULT);t(Number(r)/1e6)}catch(e){console.error("Error checking query:",e),t(this.lastValue)}};s()})}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}}}const lC=new Dt;class uC extends GR{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,n={antialias:e.samples>0,alpha:!0,depth:e.depth,stencil:e.stencil},r=void 0!==t.context?t.context:e.domElement.getContext("webgl2",n);function i(t){t.preventDefault();const n={api:"WebGL",message:t.statusMessage||"Unknown reason",reason:null,originalEvent:t};e.onDeviceLost(n)}this._onContextLost=i,e.domElement.addEventListener("webglcontextlost",i,!1),this.gl=r,this.extensions=new nC(this),this.capabilities=new rC(this),this.attributeUtils=new qR(this),this.textureUtils=new eC(this),this.bufferRenderer=new sC(this),this.state=new $R(this),this.utils=new YR(this),this.extensions.get("EXT_color_buffer_float"),this.extensions.get("WEBGL_clip_cull_distance"),this.extensions.get("OES_texture_float_linear"),this.extensions.get("EXT_color_buffer_half_float"),this.extensions.get("WEBGL_multisampled_render_to_texture"),this.extensions.get("WEBGL_render_shared_exponent"),this.extensions.get("WEBGL_multi_draw"),this.extensions.get("OVR_multiview2"),this.disjoint=this.extensions.get("EXT_disjoint_timer_query_webgl2"),this.parallel=this.extensions.get("KHR_parallel_shader_compile")}get coordinateSystem(){return yt}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}async waitForGPU(){await this.utils._clientWaitAsync()}async makeXRCompatible(){!0!==this.gl.getContextAttributes().xrCompatible&&await this.gl.makeXRCompatible()}setXRTarget(e){this._xrFramebuffer=e}setXRRenderTargetTextures(e,t,n=null){const r=this.gl;if(this.set(e.texture,{textureGPU:t,glInternalFormat:r.RGBA8}),null!==n){const t=e.stencilBuffer?r.DEPTH24_STENCIL8:r.DEPTH_COMPONENT24;this.set(e.depthTexture,{textureGPU:n,glInternalFormat:t}),!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!0===e._autoAllocateDepthBuffer&&!1===e.multiview&&console.warn("THREE.WebGLBackend: Render-to-texture extension was disabled because an external texture was provided"),e._autoAllocateDepthBuffer=!1}}initTimestampQuery(e){if(!this.disjoint||!this.trackTimestamp)return;const t=e.isComputeNode?"compute":"render";this.timestampQueryPool[t]||(this.timestampQueryPool[t]=new oC(this.gl,t,2048));const n=this.timestampQueryPool[t];null!==n.allocateQueriesForContext(e)&&n.beginQuery(e)}prepareTimestampBuffer(e){if(!this.disjoint||!this.trackTimestamp)return;const t=e.isComputeNode?"compute":"render";this.timestampQueryPool[t].endQuery(e)}getContext(){return this.gl}beginRender(e){const{state:t}=this,n=this.get(e);if(e.viewport)this.updateViewport(e);else{const{width:e,height:n}=this.getDrawingBufferSize(lC);t.viewport(0,0,e,n)}if(e.scissor){const{x:n,y:r,width:i,height:s}=e.scissorValue;t.scissor(n,e.height-s-r,i,s)}this.initTimestampQuery(e),n.previousContext=this._currentContext,this._currentContext=e,this._setFramebuffer(e),this.clear(e.clearColor,e.clearDepth,e.clearStencil,e,!1);const r=e.occlusionQueryCount;r>0&&(n.currentOcclusionQueries=n.occlusionQueries,n.currentOcclusionQueryObjects=n.occlusionQueryObjects,n.lastOcclusionObject=null,n.occlusionQueries=new Array(r),n.occlusionQueryObjects=new Array(r),n.occlusionQueryIndex=0)}finishRender(e){const{gl:t,state:n}=this,r=this.get(e),i=r.previousContext;n.resetVertexState();const s=e.occlusionQueryCount;s>0&&(s>r.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)}this._currentContext=i;const o=e.renderTarget;if(null!==e.textures&&o){const r=this.get(o);if(o.samples>0&&!1===this._useMultisampledExtension(o)){const i=r.framebuffers[e.getCacheKey()];let s=t.COLOR_BUFFER_BIT;o.resolveDepthBuffer&&(o.depthBuffer&&(s|=t.DEPTH_BUFFER_BIT),o.stencilBuffer&&o.resolveStencilBuffer&&(s|=t.STENCIL_BUFFER_BIT));const a=r.msaaFrameBuffer,l=r.msaaRenderbuffers,u=e.textures,c=u.length>1;if(n.bindFramebuffer(t.READ_FRAMEBUFFER,a),n.bindFramebuffer(t.DRAW_FRAMEBUFFER,i),c)for(let e=0;e<u.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 n=0;n<u.length;n++){if(c){const{textureGPU:e}=this.get(u[n]);t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,l[n]),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0)}if(e.scissor){const{x:n,y:r,width:i,height:a}=e.scissorValue,o=e.height-a-r;t.blitFramebuffer(n,o,n+i,o+a,n,o,n+i,o+a,s,t.NEAREST)}else t.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,s,t.NEAREST)}if(c)for(let e=0;e<u.length;e++){const{textureGPU:n}=this.get(u[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,n,0)}!0===this._supportsInvalidateFramebuffer&&t.invalidateFramebuffer(t.READ_FRAMEBUFFER,r.invalidationArray)}else if(!1===o.resolveDepthBuffer&&r.framebuffers){const i=r.framebuffers[e.getCacheKey()];n.bindFramebuffer(t.DRAW_FRAMEBUFFER,i),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,r.depthInvalidationArray)}}if(null!==i)if(this._setFramebuffer(i),i.viewport)this.updateViewport(i);else{const{width:e,height:t}=this.getDrawingBufferSize(lC);n.viewport(0,0,e,t)}this.prepareTimestampBuffer(e)}resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueries:n,currentOcclusionQueryObjects:r}=t;if(n&&r){const e=new WeakSet,{gl:i}=this;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueries=null;const s=()=>{let a=0;for(let t=0;t<n.length;t++){const s=n[t];null!==s&&(i.getQueryParameter(s,i.QUERY_RESULT_AVAILABLE)&&(0===i.getQueryParameter(s,i.QUERY_RESULT)&&e.add(r[t]),n[t]=null,i.deleteQuery(s),a++))}a<n.length?requestAnimationFrame(s):t.occluded=e};s()}}isOccluded(e,t){const n=this.get(e);return n.occluded&&n.occluded.has(t)}updateViewport(e){const{state:t}=this,{x:n,y:r,width:i,height:s}=e.viewportValue;t.viewport(n,e.height-s-r,i,s)}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,n,r=null,i=!0){const{gl:s,renderer:a}=this;if(null===r){r={textures:null,clearColorValue:this.getClearColor()}}let o=0;if(e&&(o|=s.COLOR_BUFFER_BIT),t&&(o|=s.DEPTH_BUFFER_BIT),n&&(o|=s.STENCIL_BUFFER_BIT),0!==o){let l;l=r.clearColorValue?r.clearColorValue:this.getClearColor();const u=a.getClearDepth(),c=a.getClearStencil();if(t&&this.state.setDepthMask(!0),null===r.textures)s.clearColor(l.r,l.g,l.b,l.a),s.clear(o);else{if(i&&this._setFramebuffer(r),e)for(let e=0;e<r.textures.length;e++)0===e?s.clearBufferfv(s.COLOR,e,[l.r,l.g,l.b,l.a]):s.clearBufferfv(s.COLOR,e,[0,0,0,1]);t&&n?s.clearBufferfi(s.DEPTH_STENCIL,0,u,c):t?s.clearBufferfv(s.DEPTH,0,[u]):n&&s.clearBufferiv(s.STENCIL,0,[c])}}}beginCompute(e){const{state:t,gl:n}=this;t.bindFramebuffer(n.FRAMEBUFFER,null),this.initTimestampQuery(e)}compute(e,t,n,r){const{state:i,gl:s}=this;!1===this.discard&&(s.enable(s.RASTERIZER_DISCARD),this.discard=!0);const{programGPU:a,transformBuffers:o,attributes:l}=this.get(r),u=this._getVaoKey(l),c=this.vaoCache[u];void 0===c?this.vaoCache[u]=this._createVao(l):i.setVertexState(c),i.useProgram(a),this._bindUniforms(n);const h=this._getTransformFeedback(o);s.bindTransformFeedback(s.TRANSFORM_FEEDBACK,h),s.beginTransformFeedback(s.POINTS),l[0].isStorageInstancedBufferAttribute?s.drawArraysInstanced(s.POINTS,0,1,t.count):s.drawArrays(s.POINTS,0,t.count),s.endTransformFeedback(),s.bindTransformFeedback(s.TRANSFORM_FEEDBACK,null);for(let e=0;e<o.length;e++){const t=o[e];t.pbo&&this.has(t.pbo)&&this.textureUtils.copyBufferToTexture(t.transformBuffer,t.pbo),t.switchBuffers()}}finishCompute(e){const t=this.gl;this.discard=!1,t.disable(t.RASTERIZER_DISCARD),this.prepareTimestampBuffer(e),this._currentContext&&this._setFramebuffer(this._currentContext)}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.isArrayTexture&&e.camera.isArrayCamera}draw(e){const{object:t,pipeline:n,material:r,context:i,hardwareClippingPlanes:s}=e,{programGPU:a}=this.get(n),{gl:o,state:l}=this,u=this.get(i),c=e.getDrawParameters();if(null===c)return;this._bindUniforms(e.getBindings());const h=t.isMesh&&t.matrixWorld.determinant()<0;l.setMaterial(r,h,s),l.useProgram(a);const d=e.getAttributes(),p=this.get(d);let f=p.vaoGPU;if(void 0===f){const e=this._getVaoKey(d);f=this.vaoCache[e],void 0===f&&(f=this._createVao(d),this.vaoCache[e]=f,p.vaoGPU=f)}const m=e.getIndex(),g=null!==m?this.get(m).bufferGPU:null;l.setVertexState(f,g);const _=u.lastOcclusionObject;if(_!==t&&void 0!==_){if(null!==_&&!0===_.occlusionTest&&(o.endQuery(o.ANY_SAMPLES_PASSED),u.occlusionQueryIndex++),!0===t.occlusionTest){const e=o.createQuery();o.beginQuery(o.ANY_SAMPLES_PASSED,e),u.occlusionQueries[u.occlusionQueryIndex]=e,u.occlusionQueryObjects[u.occlusionQueryIndex]=t}u.lastOcclusionObject=t}const v=this.bufferRenderer;t.isPoints?v.mode=o.POINTS:t.isLineSegments?v.mode=o.LINES:t.isLine?v.mode=o.LINE_STRIP:t.isLineLoop?v.mode=o.LINE_LOOP:!0===r.wireframe?(l.setLineWidth(r.wireframeLinewidth*this.renderer.getPixelRatio()),v.mode=o.LINES):v.mode=o.TRIANGLES;const{vertexCount:y,instanceCount:x}=c;let{firstVertex:b}=c;if(v.object=t,null!==m){b*=m.array.BYTES_PER_ELEMENT;const e=this.get(m);v.index=m.count,v.type=e.type}else v.index=0;const T=()=>{t.isBatchedMesh?null!==t._multiDrawInstances?(jt("THREE.WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),v.renderMultiDrawInstances(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount,t._multiDrawInstances)):this.hasFeature("WEBGL_multi_draw")?v.renderMultiDraw(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount):jt("THREE.WebGLRenderer: WEBGL_multi_draw not supported."):x>1?v.renderInstances(b,y,x):v.render(b,y)};if(!0===e.camera.isArrayCamera&&e.camera.cameras.length>0&&!1===e.camera.isMultiViewCamera){const n=this.get(e.camera),r=e.camera.cameras,i=e.getBindingGroup("cameraIndex").bindings[0];if(void 0===n.indexesGPU||n.indexesGPU.length!==r.length){const e=new Uint32Array([0,0,0,0]),t=[];for(let n=0,i=r.length;n<i;n++){const r=o.createBuffer();e[0]=n,o.bindBuffer(o.UNIFORM_BUFFER,r),o.bufferData(o.UNIFORM_BUFFER,e,o.STATIC_DRAW),t.push(r)}n.indexesGPU=t}const s=this.get(i),a=this.renderer.getPixelRatio(),u=this._currentContext.renderTarget,c=this._isRenderCameraDepthArray(this._currentContext),h=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,n=r.length;e<n;e++)this.renderer._activeCubeFace=e,this._currentContext.activeCubeFace=e,this._setFramebuffer(this._currentContext),this.clear(!1,!0,t,this._currentContext,!1);this.renderer._activeCubeFace=h,this._currentContext.activeCubeFace=h}}for(let i=0,u=r.length;i<u;i++){const u=r[i];if(t.layers.test(u.layers)){c&&(this.renderer._activeCubeFace=i,this._currentContext.activeCubeFace=i,this._setFramebuffer(this._currentContext));const t=u.viewport;if(void 0!==t){const n=t.x*a,r=t.y*a,i=t.width*a,s=t.height*a;l.viewport(Math.floor(n),Math.floor(e.context.height-s-r),Math.floor(i),Math.floor(s))}l.bindBufferBase(o.UNIFORM_BUFFER,s.index,n.indexesGPU[i]),T()}this._currentContext.activeCubeFace=h,this.renderer._activeCubeFace=h}}else T()}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){this.textureUtils.destroyTexture(e)}async copyTextureToBuffer(e,t,n,r,i,s){return this.textureUtils.copyTextureToBuffer(e,t,n,r,i,s)}createSampler(){}destroySampler(){}createNodeBuilder(e,t){return new kR(e,t)}createProgram(e){const t=this.gl,{stage:n,code:r}=e,i="fragment"===n?t.createShader(t.FRAGMENT_SHADER):t.createShader(t.VERTEX_SHADER);t.shaderSource(i,r),t.compileShader(i),this.set(e,{shaderGPU:i})}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){const n=this.gl,r=e.pipeline,{fragmentProgram:i,vertexProgram:s}=r,a=n.createProgram(),o=this.get(i).shaderGPU,l=this.get(s).shaderGPU;if(n.attachShader(a,o),n.attachShader(a,l),n.linkProgram(a),this.set(r,{programGPU:a,fragmentShader:o,vertexShader:l}),null!==t&&this.parallel){const i=new Promise(t=>{const i=this.parallel,s=()=>{n.getProgramParameter(a,i.COMPLETION_STATUS_KHR)?(this._completeCompile(e,r),t()):requestAnimationFrame(s)};s()});return void t.push(i)}this._completeCompile(e,r)}_handleSource(e,t){const n=e.split("\n"),r=[],i=Math.max(t-6,0),s=Math.min(t+6,n.length);for(let e=i;e<s;e++){const i=e+1;r.push(`${i===t?">":" "} ${i}: ${n[e]}`)}return r.join("\n")}_getShaderErrors(e,t,n){const r=e.getShaderParameter(t,e.COMPILE_STATUS),i=e.getShaderInfoLog(t).trim();if(r&&""===i)return"";const s=/ERROR: 0:(\d+)/.exec(i);if(s){const r=parseInt(s[1]);return n.toUpperCase()+"\n\n"+i+"\n\n"+this._handleSource(e.getShaderSource(t),r)}return i}_logProgramError(e,t,n){if(this.renderer.debug.checkShaderErrors){const r=this.gl,i=r.getProgramInfoLog(e).trim();if(!1===r.getProgramParameter(e,r.LINK_STATUS))if("function"==typeof this.renderer.debug.onShaderError)this.renderer.debug.onShaderError(r,e,n,t);else{const s=this._getShaderErrors(r,n,"vertex"),a=this._getShaderErrors(r,t,"fragment");console.error("THREE.WebGLProgram: Shader Error "+r.getError()+" - VALIDATE_STATUS "+r.getProgramParameter(e,r.VALIDATE_STATUS)+"\n\nProgram Info Log: "+i+"\n"+s+"\n"+a)}else""!==i&&console.warn("THREE.WebGLProgram: Program Info Log:",i)}}_completeCompile(e,t){const{state:n,gl:r}=this,i=this.get(t),{programGPU:s,fragmentShader:a,vertexShader:o}=i;!1===r.getProgramParameter(s,r.LINK_STATUS)&&this._logProgramError(s,a,o),n.useProgram(s);const l=e.getBindings();this._setupBindings(l,s),this.set(t,{programGPU:s})}createComputePipeline(e,t){const{state:n,gl:r}=this,i={stage:"fragment",code:"#version 300 es\nprecision highp float;\nvoid main() {}"};this.createProgram(i);const{computeProgram:s}=e,a=r.createProgram(),o=this.get(i).shaderGPU,l=this.get(s).shaderGPU,u=s.transforms,c=[],h=[];for(let e=0;e<u.length;e++){const t=u[e];c.push(t.varyingName),h.push(t.attributeNode)}r.attachShader(a,o),r.attachShader(a,l),r.transformFeedbackVaryings(a,c,r.SEPARATE_ATTRIBS),r.linkProgram(a),!1===r.getProgramParameter(a,r.LINK_STATUS)&&this._logProgramError(a,o,l),n.useProgram(a),this._setupBindings(t,a);const d=s.attributes,p=[],f=[];for(let e=0;e<d.length;e++){const t=d[e].node.attribute;p.push(t),this.has(t)||this.attributeUtils.createAttribute(t,r.ARRAY_BUFFER)}for(let e=0;e<h.length;e++){const t=h[e].attribute;this.has(t)||this.attributeUtils.createAttribute(t,r.ARRAY_BUFFER);const n=this.get(t);f.push(n)}this.set(e,{programGPU:a,transformBuffers:f,attributes:p})}createBindings(e,t){if(!1===this._knownBindings.has(t)){this._knownBindings.add(t);let e=0,n=0;for(const r of t){this.set(r,{textures:n,uniformBuffers:e});for(const t of r.bindings)t.isUniformBuffer&&e++,t.isSampledTexture&&n++}}this.updateBindings(e,t)}updateBindings(e){const{gl:t}=this,n=this.get(e);let r=n.uniformBuffers,i=n.textures;for(const n of e.bindings)if(n.isUniformsGroup||n.isUniformBuffer){const e=n.buffer,i=t.createBuffer();t.bindBuffer(t.UNIFORM_BUFFER,i),t.bufferData(t.UNIFORM_BUFFER,e,t.DYNAMIC_DRAW),this.set(n,{index:r++,bufferGPU:i})}else if(n.isSampledTexture){const{textureGPU:e,glTextureType:t}=this.get(n.texture);this.set(n,{index:i++,textureGPU:e,glTextureType:t})}}updateBinding(e){const t=this.gl;if(e.isUniformsGroup||e.isUniformBuffer){const n=this.get(e).bufferGPU,r=e.buffer;t.bindBuffer(t.UNIFORM_BUFFER,n),t.bufferData(t.UNIFORM_BUFFER,r,t.DYNAMIC_DRAW)}}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(iC).filter(t=>iC[t]===e),n=this.extensions;for(let e=0;e<t.length;e++)if(n.has(t[e]))return!0;return!1}getMaxAnisotropy(){return this.capabilities.getMaxAnisotropy()}copyTextureToTexture(e,t,n=null,r=null,i=0,s=0){this.textureUtils.copyTextureToTexture(e,t,n,r,i,s)}copyFramebufferToTexture(e,t,n){this.textureUtils.copyFramebufferToTexture(e,t,n)}_setFramebuffer(e){const{gl:t,state:n}=this;let r=null;if(null!==e.textures){const i=e.renderTarget,s=this.get(i),{samples:a,depthBuffer:o,stencilBuffer:l}=i,u=!0===i.isWebGLCubeRenderTarget,c=!0===i.isRenderTarget3D,h=i.depth>1,d=!0===i.isXRRenderTarget,p=!0===d&&!0===i._hasExternalTextures;let f=s.msaaFrameBuffer,m=s.depthRenderbuffer;const g=this.extensions.get("WEBGL_multisampled_render_to_texture"),_=this.extensions.get("OVR_multiview2"),v=this._useMultisampledExtension(i),y=uw(e);let x;if(u?(s.cubeFramebuffers||(s.cubeFramebuffers={}),x=s.cubeFramebuffers[y]):d&&!1===p?x=this._xrFramebuffer:(s.framebuffers||(s.framebuffers={}),x=s.framebuffers[y]),void 0===x){x=t.createFramebuffer(),n.bindFramebuffer(t.FRAMEBUFFER,x);const r=e.textures,o=[];if(u){s.cubeFramebuffers[y]=x;const{textureGPU:e}=this.get(r[0]),n=this.renderer._activeCubeFace;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+n,e,0)}else{s.framebuffers[y]=x;for(let n=0;n<r.length;n++){const s=r[n],o=this.get(s);o.renderTarget=e.renderTarget,o.cacheKey=y;const l=t.COLOR_ATTACHMENT0+n;if(i.multiview)_.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,l,o.textureGPU,0,a,0,2);else if(c||h){const e=this.renderer._activeCubeFace;t.framebufferTextureLayer(t.FRAMEBUFFER,l,o.textureGPU,0,e)}else v?g.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,l,t.TEXTURE_2D,o.textureGPU,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,l,t.TEXTURE_2D,o.textureGPU,0)}}const d=l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(!0===i._autoAllocateDepthBuffer){const n=t.createRenderbuffer();this.textureUtils.setupRenderBufferStorage(n,e,0,v),s.xrDepthRenderbuffer=n,o.push(l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT),t.bindRenderbuffer(t.RENDERBUFFER,n),t.framebufferRenderbuffer(t.FRAMEBUFFER,d,t.RENDERBUFFER,n)}else if(null!==e.depthTexture){o.push(l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT);const n=this.get(e.depthTexture);if(n.renderTarget=e.renderTarget,n.cacheKey=y,i.multiview)_.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,d,n.textureGPU,0,a,0,2);else if(p&&v)g.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,d,t.TEXTURE_2D,n.textureGPU,0,a);else if(e.depthTexture.isArrayTexture){const e=this.renderer._activeCubeFace;t.framebufferTextureLayer(t.FRAMEBUFFER,d,n.textureGPU,0,e)}else t.framebufferTexture2D(t.FRAMEBUFFER,d,t.TEXTURE_2D,n.textureGPU,0)}s.depthInvalidationArray=o}else{if(this._isRenderCameraDepthArray(e)){n.bindFramebuffer(t.FRAMEBUFFER,x);const r=this.renderer._activeCubeFace,i=this.get(e.depthTexture),s=l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;t.framebufferTextureLayer(t.FRAMEBUFFER,s,i.textureGPU,0,r)}if((d||v||i.multiview)&&!0!==i._isOpaqueFramebuffer){n.bindFramebuffer(t.FRAMEBUFFER,x);const r=this.get(e.textures[0]);i.multiview?_.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,r.textureGPU,0,a,0,2):v?g.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r.textureGPU,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r.textureGPU,0);const o=l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(!0===i._autoAllocateDepthBuffer){const e=s.xrDepthRenderbuffer;t.bindRenderbuffer(t.RENDERBUFFER,e),t.framebufferRenderbuffer(t.FRAMEBUFFER,o,t.RENDERBUFFER,e)}else{const n=this.get(e.depthTexture);i.multiview?_.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,o,n.textureGPU,0,a,0,2):v?g.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,o,t.TEXTURE_2D,n.textureGPU,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,o,t.TEXTURE_2D,n.textureGPU,0)}}}if(a>0&&!1===v&&!i.multiview){if(void 0===f){const r=[];f=t.createFramebuffer(),n.bindFramebuffer(t.FRAMEBUFFER,f);const i=[],u=e.textures;for(let n=0;n<u.length;n++){i[n]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,i[n]),r.push(t.COLOR_ATTACHMENT0+n);const s=e.textures[n],o=this.get(s);t.renderbufferStorageMultisample(t.RENDERBUFFER,a,o.glInternalFormat,e.width,e.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+n,t.RENDERBUFFER,i[n])}if(t.bindRenderbuffer(t.RENDERBUFFER,null),s.msaaFrameBuffer=f,s.msaaRenderbuffers=i,o&&void 0===m){m=t.createRenderbuffer(),this.textureUtils.setupRenderBufferStorage(m,e,a),s.depthRenderbuffer=m;const n=l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;r.push(n)}s.invalidationArray=r}r=s.msaaFrameBuffer}else r=x;n.drawBuffers(e,x)}n.bindFramebuffer(t.FRAMEBUFFER,r)}_getVaoKey(e){let t="";for(let n=0;n<e.length;n++){t+=":"+this.get(e[n]).id}return t}_createVao(e){const{gl:t}=this,n=t.createVertexArray();t.bindVertexArray(n);for(let n=0;n<e.length;n++){const r=e[n],i=this.get(r);let s,a;t.bindBuffer(t.ARRAY_BUFFER,i.bufferGPU),t.enableVertexAttribArray(n),!0===r.isInterleavedBufferAttribute?(s=r.data.stride*i.bytesPerElement,a=r.offset*i.bytesPerElement):(s=0,a=0),i.isInteger?t.vertexAttribIPointer(n,r.itemSize,i.type,s,a):t.vertexAttribPointer(n,r.itemSize,i.type,r.normalized,s,a),r.isInstancedBufferAttribute&&!r.isInterleavedBufferAttribute?t.vertexAttribDivisor(n,r.meshPerAttribute):r.isInterleavedBufferAttribute&&r.data.isInstancedInterleavedBuffer&&t.vertexAttribDivisor(n,r.data.meshPerAttribute)}return t.bindBuffer(t.ARRAY_BUFFER,null),n}_getTransformFeedback(e){let t="";for(let n=0;n<e.length;n++)t+=":"+e[n].id;let n=this.transformFeedbackCache[t];if(void 0!==n)return n;const{gl:r}=this;n=r.createTransformFeedback(),r.bindTransformFeedback(r.TRANSFORM_FEEDBACK,n);for(let t=0;t<e.length;t++){const n=e[t];r.bindBufferBase(r.TRANSFORM_FEEDBACK_BUFFER,t,n.transformBuffer)}return r.bindTransformFeedback(r.TRANSFORM_FEEDBACK,null),this.transformFeedbackCache[t]=n,n}_setupBindings(e,t){const n=this.gl;for(const r of e)for(const e of r.bindings){const r=this.get(e).index;if(e.isUniformsGroup||e.isUniformBuffer){const i=n.getUniformBlockIndex(t,e.name);n.uniformBlockBinding(t,i,r)}else if(e.isSampledTexture){const i=n.getUniformLocation(t,e.name);n.uniform1i(i,r)}}}_bindUniforms(e){const{gl:t,state:n}=this;for(const r of e)for(const e of r.bindings){const r=this.get(e),i=r.index;e.isUniformsGroup||e.isUniformBuffer?n.bindBufferBase(t.UNIFORM_BUFFER,i,r.bufferGPU):e.isSampledTexture&&n.bindTexture(r.glTextureType,r.textureGPU,t.TEXTURE0+i)}}_useMultisampledExtension(e){return!0===e.multiview||e.samples>0&&!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!1!==e._autoAllocateDepthBuffer}dispose(){const e=this.extensions.get("WEBGL_lose_context");e&&e.loseContext(),this.renderer.domElement.removeEventListener("webglcontextlost",this._onContextLost)}}const cC="point-list",hC="line-list",dC="line-strip",pC="triangle-list",fC="triangle-strip",mC="never",gC="less",_C="equal",vC="less-equal",yC="greater",xC="not-equal",bC="greater-equal",TC="always",SC="store",MC="load",wC="clear",EC="ccw",AC="none",RC="front",CC="back",NC="uint16",PC="uint32",LC="r8unorm",DC="r8snorm",IC="r8uint",UC="r8sint",OC="r16uint",FC="r16sint",BC="r16float",kC="rg8unorm",zC="rg8snorm",VC="rg8uint",GC="rg8sint",HC="r32uint",jC="r32sint",WC="r32float",XC="rg16uint",qC="rg16sint",$C="rg16float",YC="rgba8unorm",KC="rgba8unorm-srgb",QC="rgba8snorm",ZC="rgba8uint",JC="rgba8sint",eN="bgra8unorm",tN="bgra8unorm-srgb",nN="rgb9e5ufloat",rN="rgb10a2unorm",iN="rgb10a2unorm",sN="rg32uint",aN="rg32sint",oN="rg32float",lN="rgba16uint",uN="rgba16sint",cN="rgba16float",hN="rgba32uint",dN="rgba32sint",pN="rgba32float",fN="depth16unorm",mN="depth24plus",gN="depth24plus-stencil8",_N="depth32float",vN="depth32float-stencil8",yN="bc1-rgba-unorm",xN="bc1-rgba-unorm-srgb",bN="bc2-rgba-unorm",TN="bc2-rgba-unorm-srgb",SN="bc3-rgba-unorm",MN="bc3-rgba-unorm-srgb",wN="bc4-r-unorm",EN="bc4-r-snorm",AN="bc5-rg-unorm",RN="bc5-rg-snorm",CN="bc6h-rgb-ufloat",NN="bc6h-rgb-float",PN="bc7-rgba-unorm",LN="bc7-rgba-srgb",DN="etc2-rgb8unorm",IN="etc2-rgb8unorm-srgb",UN="etc2-rgb8a1unorm",ON="etc2-rgb8a1unorm-srgb",FN="etc2-rgba8unorm",BN="etc2-rgba8unorm-srgb",kN="eac-r11unorm",zN="eac-r11snorm",VN="eac-rg11unorm",GN="eac-rg11snorm",HN="astc-4x4-unorm",jN="astc-4x4-unorm-srgb",WN="astc-5x4-unorm",XN="astc-5x4-unorm-srgb",qN="astc-5x5-unorm",$N="astc-5x5-unorm-srgb",YN="astc-6x5-unorm",KN="astc-6x5-unorm-srgb",QN="astc-6x6-unorm",ZN="astc-6x6-unorm-srgb",JN="astc-8x5-unorm",eP="astc-8x5-unorm-srgb",tP="astc-8x6-unorm",nP="astc-8x6-unorm-srgb",rP="astc-8x8-unorm",iP="astc-8x8-unorm-srgb",sP="astc-10x5-unorm",aP="astc-10x5-unorm-srgb",oP="astc-10x6-unorm",lP="astc-10x6-unorm-srgb",uP="astc-10x8-unorm",cP="astc-10x8-unorm-srgb",hP="astc-10x10-unorm",dP="astc-10x10-unorm-srgb",pP="astc-12x10-unorm",fP="astc-12x10-unorm-srgb",mP="astc-12x12-unorm",gP="astc-12x12-unorm-srgb",_P="clamp-to-edge",vP="repeat",yP="mirror-repeat",xP="linear",bP="nearest",TP="zero",SP="one",MP="src",wP="one-minus-src",EP="src-alpha",AP="one-minus-src-alpha",RP="dst",CP="one-minus-dst",NP="dst-alpha",PP="one-minus-dst-alpha",LP="src-alpha-saturated",DP="constant",IP="one-minus-constant",UP="add",OP="subtract",FP="reverse-subtract",BP="min",kP="max",zP=0,VP=15,GP="keep",HP="zero",jP="replace",WP="invert",XP="increment-clamp",qP="decrement-clamp",$P="increment-wrap",YP="decrement-wrap",KP="storage",QP="read-only-storage",ZP="write-only",JP="read-only",eL="read-write",tL="non-filtering",nL="comparison",rL="float",iL="unfilterable-float",sL="depth",aL="sint",oL="uint",lL="2d",uL="3d",cL="2d",hL="2d-array",dL="cube",pL="3d",fL="all",mL="vertex",gL="instance",_L={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"};class vL extends xR{constructor(e,t){super(e),this.texture=t,this.version=t?t.version:0,this.isSampler=!0}}class yL extends vL{constructor(e,t,n){super(e,t?t.value:null),this.textureNode=t,this.groupNode=n}update(){this.texture=this.textureNode.value}}class xL extends bR{constructor(e,t){super(e,t?t.array:null),this.attribute=t,this.isStorageBuffer=!0}}let bL=0;class TL extends xL{constructor(e,t){super("StorageBuffer_"+bL++,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:nf,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class SL extends FM{constructor(e){super(),this.device=e;this.mipmapSampler=e.createSampler({minFilter:xP}),this.flipYSampler=e.createSampler({minFilter:bP}),this.transferPipelines={},this.flipYPipelines={},this.mipmapVertexShaderModule=e.createShaderModule({label:"mipmapVertex",code:"\nstruct VarysStruct {\n\t@builtin( position ) Position: vec4<f32>,\n\t@location( 0 ) vTex : vec2<f32>\n};\n\n@vertex\nfn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {\n\n\tvar Varys : VarysStruct;\n\n\tvar pos = array< vec2<f32>, 4 >(\n\t\tvec2<f32>( -1.0, 1.0 ),\n\t\tvec2<f32>( 1.0, 1.0 ),\n\t\tvec2<f32>( -1.0, -1.0 ),\n\t\tvec2<f32>( 1.0, -1.0 )\n\t);\n\n\tvar tex = array< vec2<f32>, 4 >(\n\t\tvec2<f32>( 0.0, 0.0 ),\n\t\tvec2<f32>( 1.0, 0.0 ),\n\t\tvec2<f32>( 0.0, 1.0 ),\n\t\tvec2<f32>( 1.0, 1.0 )\n\t);\n\n\tVarys.vTex = tex[ vertexIndex ];\n\tVarys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );\n\n\treturn Varys;\n\n}\n"}),this.mipmapFragmentShaderModule=e.createShaderModule({label:"mipmapFragment",code:"\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img : texture_2d<f32>;\n\n@fragment\nfn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {\n\n\treturn textureSample( img, imgSampler, vTex );\n\n}\n"}),this.flipYFragmentShaderModule=e.createShaderModule({label:"flipYFragment",code:"\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img : texture_2d<f32>;\n\n@fragment\nfn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {\n\n\treturn textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );\n\n}\n"})}getTransferPipeline(e){let t=this.transferPipelines[e];return void 0===t&&(t=this.device.createRenderPipeline({label:`mipmap-${e}`,vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.mipmapFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:fC,stripIndexFormat:PC},layout:"auto"}),this.transferPipelines[e]=t),t}getFlipYPipeline(e){let t=this.flipYPipelines[e];return void 0===t&&(t=this.device.createRenderPipeline({label:`flipY-${e}`,vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.flipYFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:fC,stripIndexFormat:PC},layout:"auto"}),this.flipYPipelines[e]=t),t}flipY(e,t,n=0){const r=t.format,{width:i,height:s}=t.size,a=this.getTransferPipeline(r),o=this.getFlipYPipeline(r),l=this.device.createTexture({size:{width:i,height:s,depthOrArrayLayers:1},format:r,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),u=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:cL,baseArrayLayer:n}),c=l.createView({baseMipLevel:0,mipLevelCount:1,dimension:cL,baseArrayLayer:0}),h=this.device.createCommandEncoder({}),d=(e,t,n)=>{const r=e.getBindGroupLayout(0),i=this.device.createBindGroup({layout:r,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:t}]}),s=h.beginRenderPass({colorAttachments:[{view:n,loadOp:wC,storeOp:SC,clearValue:[0,0,0,0]}]});s.setPipeline(e),s.setBindGroup(0,i),s.draw(4,1,0,0),s.end()};d(a,u,c),d(o,c,u),this.device.queue.submit([h.finish()]),l.destroy()}generateMipmaps(e,t,n=0){const r=this.get(e);void 0===r.useCount&&(r.useCount=0,r.layers=[]);const i=r.layers[n]||this._mipmapCreateBundles(e,t,n),s=this.device.createCommandEncoder({});this._mipmapRunBundles(s,i),this.device.queue.submit([s.finish()]),0!==r.useCount&&(r.layers[n]=i),r.useCount++}_mipmapCreateBundles(e,t,n){const r=this.getTransferPipeline(t.format),i=r.getBindGroupLayout(0);let s=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:cL,baseArrayLayer:n});const a=[];for(let o=1;o<t.mipLevelCount;o++){const l=this.device.createBindGroup({layout:i,entries:[{binding:0,resource:this.mipmapSampler},{binding:1,resource:s}]}),u=e.createView({baseMipLevel:o,mipLevelCount:1,dimension:cL,baseArrayLayer:n}),c={colorAttachments:[{view:u,loadOp:wC,storeOp:SC,clearValue:[0,0,0,0]}]},h=this.device.createRenderBundleEncoder({colorFormats:[t.format]});h.setPipeline(r),h.setBindGroup(0,l),h.draw(4,1,0,0),a.push({renderBundles:[h.finish()],passDescriptor:c}),s=u}return a}_mipmapRunBundles(e,t){const n=t.length;for(let r=0;r<n;r++){const n=t[r],i=e.beginRenderPass(n.passDescriptor);i.executeBundles(n.renderBundles),i.end()}}}const ML={[lt]:"never",[ut]:"less",[ct]:"equal",[ht]:"less-equal",[dt]:"greater",[ft]:"greater-equal",[mt]:"always",[pt]:"not-equal"},wL=[0,1,3,2,4,5];class EL{constructor(e){this.backend=e,this._passUtils=null,this.defaultTexture={},this.defaultCubeTexture={},this.defaultVideoFrame=null,this.colorBuffer=null,this.depthTexture=new os,this.depthTexture.name="depthBuffer"}createSampler(e){const t=this.backend,n=t.device,r=t.get(e),i={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};i.magFilter===xP&&i.minFilter===xP&&i.mipmapFilter===xP&&(i.maxAnisotropy=e.anisotropy),e.isDepthTexture&&null!==e.compareFunction&&(i.compare=ML[e.compareFunction]),r.sampler=n.createSampler(i)}createDefaultTexture(e){let t;const n=AL(e);e.isCubeTexture?t=this._getDefaultCubeTextureGPU(n):e.isVideoTexture?this.backend.get(e).externalTexture=this._getDefaultVideoFrame():t=this._getDefaultTextureGPU(n),this.backend.get(e).texture=t}createTexture(e,t={}){const n=this.backend,r=n.get(e);if(r.initialized)throw new Error("WebGPUTextureUtils: Texture already initialized.");void 0===t.needsMipmaps&&(t.needsMipmaps=!1),void 0===t.levels&&(t.levels=1),void 0===t.depth&&(t.depth=1);const{width:i,height:s,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),u=e.internalFormat||t.format||AL(e,n.device);r.format=u;const{samples:c,primarySamples:h,isMSAA:d}=n.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&&(p|=GPUTextureUsage.RENDER_ATTACHMENT);const f={label:e.name,size:{width:i,height:s,depthOrArrayLayers:a},mipLevelCount:o,sampleCount:h,dimension:l,format:u,usage:p};if(e.isVideoTexture){const t=e.source.data,n=new VideoFrame(t);f.size.width=n.displayWidth,f.size.height=n.displayHeight,n.close(),r.externalTexture=t}else{if(void 0===u)return console.warn("WebGPURenderer: Texture format not supported."),void this.createDefaultTexture(e);e.isCubeTexture&&(f.textureBindingViewDimension=dL),r.texture=n.device.createTexture(f)}if(d){const e=Object.assign({},f);e.label=e.label+"-msaa",e.sampleCount=c,r.msaaTexture=n.device.createTexture(e)}r.initialized=!0,r.textureDescriptorGPU=f}destroyTexture(e){const t=this.backend,n=t.get(e);void 0!==n.texture&&n.texture.destroy(),void 0!==n.msaaTexture&&n.msaaTexture.destroy(),t.delete(e)}destroySampler(e){delete this.backend.get(e).sampler}generateMipmaps(e){const t=this.backend.get(e);if(e.isCubeTexture)for(let e=0;e<6;e++)this._generateMipmaps(t.texture,t.textureDescriptorGPU,e);else{const n=e.image.depth||1;for(let e=0;e<n;e++)this._generateMipmaps(t.texture,t.textureDescriptorGPU,e)}}getColorBuffer(){this.colorBuffer&&this.colorBuffer.destroy();const e=this.backend,{width:t,height:n}=e.getDrawingBufferSize();return this.colorBuffer=e.device.createTexture({label:"colorBuffer",size:{width:t,height:n,depthOrArrayLayers:1},sampleCount:e.utils.getSampleCount(e.renderer.samples),format:e.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC}),this.colorBuffer}getDepthBuffer(e=!0,t=!1){const n=this.backend,{width:r,height:i}=n.getDrawingBufferSize(),s=this.depthTexture,a=n.get(s).texture;let o,l;if(t?(o=ve,l=de):e&&(o=_e,l=oe),void 0!==a){if(s.image.width===r&&s.image.height===i&&s.format===o&&s.type===l)return a;this.destroyTexture(s)}return s.name="depthBuffer",s.format=o,s.type=l,s.image.width=r,s.image.height=i,this.createTexture(s,{width:r,height:i}),n.get(s).texture}updateTexture(e,t){const n=this.backend.get(e),{textureDescriptorGPU:r}=n;if(!e.isRenderTargetTexture&&void 0!==r){if(e.isDataTexture)this._copyBufferToTexture(t.image,n.texture,r,0,e.flipY);else if(e.isArrayTexture||e.isDataArrayTexture||e.isData3DTexture)for(let i=0;i<t.image.depth;i++)this._copyBufferToTexture(t.image,n.texture,r,i,e.flipY,i);else if(e.isCompressedTexture||e.isCompressedArrayTexture)this._copyCompressedBufferToTexture(e.mipmaps,n.texture,r);else if(e.isCubeTexture)this._copyCubeMapToTexture(t.images,n.texture,r,e.flipY,e.premultiplyAlpha);else if(e.isVideoTexture){const t=e.source.data;n.externalTexture=t}else this._copyImageToTexture(t.image,n.texture,r,0,e.flipY,e.premultiplyAlpha);n.version=e.version,e.onUpdate&&e.onUpdate(e)}}async copyTextureToBuffer(e,t,n,r,i,s){const a=this.backend.device,o=this.backend.get(e),l=o.texture,u=o.textureDescriptorGPU.format,c=this._getBytesPerTexel(u);let h=r*c;h=256*Math.ceil(h/256);const d=a.createBuffer({size:r*i*c,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),p=a.createCommandEncoder();p.copyTextureToBuffer({texture:l,origin:{x:t,y:n,z:s}},{buffer:d,bytesPerRow:h},{width:r,height:i});const f=this._getTypedArrayType(u);a.queue.submit([p.finish()]),await d.mapAsync(GPUMapMode.READ);return new f(d.getMappedRange())}_getDefaultTextureGPU(e){let t=this.defaultTexture[e];if(void 0===t){const n=new sn;n.minFilter=K,n.magFilter=K,this.createTexture(n,{width:1,height:1,format:e}),this.defaultTexture[e]=t=n}return this.backend.get(t).texture}_getDefaultCubeTextureGPU(e){let t=this.defaultTexture[e];if(void 0===t){const n=new Ai;n.minFilter=K,n.magFilter=K,this.createTexture(n,{width:1,height:1,depth:6}),this.defaultCubeTexture[e]=t=n}return this.backend.get(t).texture}_getDefaultVideoFrame(){let e=this.defaultVideoFrame;if(null===e){const t={timestamp:0,codedWidth:1,codedHeight:1,format:"RGBA"};this.defaultVideoFrame=e=new VideoFrame(new Uint8Array([0,0,0,255]),t)}return e}_copyCubeMapToTexture(e,t,n,r,i){for(let s=0;s<6;s++){const a=e[s],o=!0===r?wL[s]:s;a.isDataTexture?this._copyBufferToTexture(a.image,t,n,o,r):this._copyImageToTexture(a,t,n,o,r,i)}}_copyImageToTexture(e,t,n,r,i,s){this.backend.device.queue.copyExternalImageToTexture({source:e,flipY:i},{texture:t,mipLevel:0,origin:{x:0,y:0,z:r},premultipliedAlpha:s},{width:e.width,height:e.height,depthOrArrayLayers:1})}_getPassUtils(){let e=this._passUtils;return null===e&&(this._passUtils=e=new SL(this.backend.device)),e}_generateMipmaps(e,t,n=0){this._getPassUtils().generateMipmaps(e,t,n)}_flipY(e,t,n=0){this._getPassUtils().flipY(e,t,n)}_copyBufferToTexture(e,t,n,r,i,s=0){const a=this.backend.device,o=e.data,l=this._getBytesPerTexel(n.format),u=e.width*l;a.queue.writeTexture({texture:t,mipLevel:0,origin:{x:0,y:0,z:r}},o,{offset:e.width*e.height*l*s,bytesPerRow:u},{width:e.width,height:e.height,depthOrArrayLayers:1}),!0===i&&this._flipY(t,n,r)}_copyCompressedBufferToTexture(e,t,n){const r=this.backend.device,i=this._getBlockData(n.format),s=n.size.depthOrArrayLayers>1;for(let a=0;a<e.length;a++){const o=e[a],l=o.width,u=o.height,c=s?n.size.depthOrArrayLayers:1,h=Math.ceil(l/i.width)*i.byteLength,d=h*Math.ceil(u/i.height);for(let e=0;e<c;e++)r.queue.writeTexture({texture:t,mipLevel:a,origin:{x:0,y:0,z:e}},o.data,{offset:e*d,bytesPerRow:h,rowsPerImage:Math.ceil(u/i.height)},{width:Math.ceil(l/i.width)*i.width,height:Math.ceil(u/i.height)*i.height,depthOrArrayLayers:1})}}_getBlockData(e){return e===yN||e===xN?{byteLength:8,width:4,height:4}:e===bN||e===TN||e===SN||e===MN?{byteLength:16,width:4,height:4}:e===wN||e===EN?{byteLength:8,width:4,height:4}:e===AN||e===RN||e===CN||e===NN||e===PN||e===LN?{byteLength:16,width:4,height:4}:e===DN||e===IN||e===UN||e===ON?{byteLength:8,width:4,height:4}:e===FN||e===BN?{byteLength:16,width:4,height:4}:e===kN||e===zN?{byteLength:8,width:4,height:4}:e===VN||e===GN||e===HN||e===jN?{byteLength:16,width:4,height:4}:e===WN||e===XN?{byteLength:16,width:5,height:4}:e===qN||e===$N?{byteLength:16,width:5,height:5}:e===YN||e===KN?{byteLength:16,width:6,height:5}:e===QN||e===ZN?{byteLength:16,width:6,height:6}:e===JN||e===eP?{byteLength:16,width:8,height:5}:e===tP||e===nP?{byteLength:16,width:8,height:6}:e===rP||e===iP?{byteLength:16,width:8,height:8}:e===sP||e===aP?{byteLength:16,width:10,height:5}:e===oP||e===lP?{byteLength:16,width:10,height:6}:e===uP||e===cP?{byteLength:16,width:10,height:8}:e===hP||e===dP?{byteLength:16,width:10,height:10}:e===pP||e===fP?{byteLength:16,width:12,height:10}:e===mP||e===gP?{byteLength:16,width:12,height:12}:void 0}_convertAddressMode(e){let t=_P;return e===q?t=vP:e===Y&&(t=yP),t}_convertFilterMode(e){let t=xP;return e!==K&&e!==Q&&e!==Z||(t=bP),t}_getBytesPerTexel(e){return e===LC||e===DC||e===IC||e===UC?1:e===OC||e===FC||e===BC||e===kC||e===zC||e===VC||e===GC?2:e===HC||e===jC||e===WC||e===XC||e===qC||e===$C||e===YC||e===KC||e===QC||e===ZC||e===JC||e===eN||e===tN||e===nN||e===rN||e===iN||e===_N||e===mN||e===gN||e===vN?4:e===sN||e===aN||e===oN||e===lN||e===uN||e===cN?8:e===hN||e===dN||e===pN?16:void 0}_getTypedArrayType(e){return e===IC?Uint8Array:e===UC?Int8Array:e===LC?Uint8Array:e===DC?Int8Array:e===VC?Uint8Array:e===GC?Int8Array:e===kC?Uint8Array:e===zC?Int8Array:e===ZC?Uint8Array:e===JC?Int8Array:e===YC?Uint8Array:e===QC?Int8Array:e===OC?Uint16Array:e===FC?Int16Array:e===XC?Uint16Array:e===qC?Int16Array:e===lN?Uint16Array:e===uN?Int16Array:e===BC||e===$C||e===cN?Uint16Array:e===HC?Uint32Array:e===jC?Int32Array:e===WC?Float32Array:e===sN?Uint32Array:e===aN?Int32Array:e===oN?Float32Array:e===hN?Uint32Array:e===dN?Int32Array:e===pN?Float32Array:e===eN||e===tN?Uint8Array:e===rN||e===nN||e===iN?Uint32Array:e===_N?Float32Array:e===mN||e===gN?Uint32Array:e===vN?Float32Array:void 0}_getDimension(e){let t;return t=e.is3DTexture||e.isData3DTexture?uL:lL,t}}function AL(e,t=null){const n=e.format,r=e.type,i=e.colorSpace,s=$t.getTransfer(i);let a;if(!0===e.isCompressedTexture||!0===e.isCompressedArrayTexture)switch(n){case we:a=s===at?xN:yN;break;case Ee:a=s===at?TN:bN;break;case Ae:a=s===at?MN:SN;break;case De:a=s===at?IN:DN;break;case Ie:a=s===at?BN:FN;break;case Ue:a=s===at?jN:HN;break;case Oe:a=s===at?XN:WN;break;case Fe:a=s===at?$N:qN;break;case Be:a=s===at?KN:YN;break;case ke:a=s===at?ZN:QN;break;case ze:a=s===at?eP:JN;break;case Ve:a=s===at?nP:tP;break;case Ge:a=s===at?iP:rP;break;case He:a=s===at?aP:sP;break;case je:a=s===at?lP:oP;break;case We:a=s===at?cP:uP;break;case Xe:a=s===at?dP:hP;break;case qe:a=s===at?fP:pP;break;case $e:a=s===at?gP:mP;break;case ge:a=s===at?KC:YC;break;default:console.error("WebGPURenderer: Unsupported texture format.",n)}else switch(n){case ge:switch(r){case re:a=QC;break;case ie:a=uN;break;case se:a=lN;break;case oe:a=hN;break;case ae:a=dN;break;case ne:a=s===at?KC:YC;break;case ue:a=cN;break;case le:a=pN;break;default:console.error("WebGPURenderer: Unsupported texture type with RGBAFormat.",r)}break;case me:if(r===pe)a=nN;else console.error("WebGPURenderer: Unsupported texture type with RGBFormat.",r);break;case ye:switch(r){case re:a=DC;break;case ie:a=FC;break;case se:a=OC;break;case oe:a=HC;break;case ae:a=jC;break;case ne:a=LC;break;case ue:a=BC;break;case le:a=WC;break;default:console.error("WebGPURenderer: Unsupported texture type with RedFormat.",r)}break;case be:switch(r){case re:a=zC;break;case ie:a=qC;break;case se:a=XC;break;case oe:a=sN;break;case ae:a=aN;break;case ne:a=kC;break;case ue:a=$C;break;case le:a=oN;break;default:console.error("WebGPURenderer: Unsupported texture type with RGFormat.",r)}break;case _e:switch(r){case se:a=fN;break;case oe:a=mN;break;case le:a=_N;break;default:console.error("WebGPURenderer: Unsupported texture type with DepthFormat.",r)}break;case ve:switch(r){case de:a=gN;break;case le:t&&!1===t.features.has(_L.Depth32FloatStencil8)&&console.error('WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.'),a=vN;break;default:console.error("WebGPURenderer: Unsupported texture type with DepthStencilFormat.",r)}break;case xe:switch(r){case ae:a=jC;break;case oe:a=HC;break;default:console.error("WebGPURenderer: Unsupported texture type with RedIntegerFormat.",r)}break;case Te:switch(r){case ae:a=aN;break;case oe:a=sN;break;default:console.error("WebGPURenderer: Unsupported texture type with RGIntegerFormat.",r)}break;case Se:switch(r){case ae:a=dN;break;case oe:a=hN;break;default:console.error("WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.",r)}break;default:console.error("WebGPURenderer: Unsupported texture format.",n)}return a}const RL=/^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,CL=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,NL={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 PL extends FA{constructor(e){const{type:t,inputs:n,name:r,inputsCode:i,blockCode:s,outputType:a}=(e=>{const t=(e=e.trim()).match(RL);if(null!==t&&4===t.length){const n=t[2],r=[];let i=null;for(;null!==(i=CL.exec(n));)r.push({name:i[1],type:i[2]});const s=[];for(let e=0;e<r.length;e++){const{name:t,type:n}=r[e];let i=n;i.startsWith("ptr")?i="pointer":(i.startsWith("texture")&&(i=n.split("<")[0]),i=NL[i]),s.push(new SA(i,t))}const a=e.substring(t[0].length),o=t[3]||"void",l=void 0!==t[1]?t[1]:"";return{type:NL[o]||o,inputs:s,name:l,inputsCode:n,blockCode:a,outputType:o}}throw new Error("FunctionNode: Function is not a WGSL code.")})(e);super(t,n,r),this.inputsCode=i,this.blockCode=s,this.outputType=a}getCode(e=this.name){const t="void"!==this.outputType?"-> "+this.outputType:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class LL extends OA{parseFunction(e){return new PL(e)}}const DL="undefined"!=typeof self?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},IL={[ef]:"read",[tf]:"write",[nf]:"read_write"},UL={[q]:"repeat",[$]:"clamp",[Y]:"mirror"},OL={vertex:DL?DL.VERTEX:1,fragment:DL?DL.FRAGMENT:2,compute:DL?DL.COMPUTE:4},FL={instance:!0,swizzleAssign:!1,storageBuffer:!0},BL={"^^":"tsl_xor"},kL={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>"},zL={},VL={tsl_xor:new $w("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new $w("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new $w("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new $w("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new $w("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new $w("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new $w("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new $w("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 $w("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 $w("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new $w("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 $w("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),biquadraticTexture:new $w("\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")},GL={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>"};"undefined"!=typeof navigator&&/Windows/g.test(navigator.userAgent)&&(VL.pow_float=new $w("fn tsl_pow_float( a : f32, b : f32 ) -> f32 { return select( -pow( -a, b ), pow( a, b ), a > 0.0 ); }"),VL.pow_vec2=new $w("fn tsl_pow_vec2( a : vec2f, b : vec2f ) -> vec2f { return vec2f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ) ); }",[VL.pow_float]),VL.pow_vec3=new $w("fn tsl_pow_vec3( a : vec3f, b : vec3f ) -> vec3f { return vec3f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ) ); }",[VL.pow_float]),VL.pow_vec4=new $w("fn tsl_pow_vec4( a : vec4f, b : vec4f ) -> vec4f { return vec4f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ), tsl_pow_float( a.w, b.w ) ); }",[VL.pow_float]),GL.pow_float="tsl_pow_float",GL.pow_vec2="tsl_pow_vec2",GL.pow_vec3="tsl_pow_vec3",GL.pow_vec4="tsl_pow_vec4");let HL="";!0!==("undefined"!=typeof navigator&&/Firefox|Deno/g.test(navigator.userAgent))&&(HL+="diagnostic( off, derivative_uniformity );\n");class jL extends bA{constructor(e,t){super(e,t,new LL),this.uniformGroups={},this.builtins={},this.directives={},this.scopedArrays=new Map}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==nt}_generateTextureSample(e,t,n,r,i=this.shaderStage){return"fragment"===i?r?`textureSample( ${t}, ${t}_sampler, ${n}, ${r} )`:`textureSample( ${t}, ${t}_sampler, ${n} )`:this._generateTextureSampleLevel(e,t,n,"0",r)}_generateVideoSample(e,t,n=this.shaderStage){if("fragment"===n)return`textureSampleBaseClampToEdge( ${e}, ${e}_sampler, vec2<f32>( ${t}.x, 1.0 - ${t}.y ) )`;console.error(`WebGPURenderer: THREE.VideoTexture does not support ${n} shader.`)}_generateTextureSampleLevel(e,t,n,r,i){return!1===this.isUnfilterable(e)?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${r} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,n,r):this.generateTextureLod(e,t,n,i,r)}generateWrapFunction(e){const t=`tsl_coord_${UL[e.wrapS]}S_${UL[e.wrapT]}_${e.isData3DTexture?"3d":"2d"}T`;let n=zL[t];if(void 0===n){const r=[],i=e.isData3DTexture?"vec3f":"vec2f";let s=`fn ${t}( coord : ${i} ) -> ${i} {\n\n\treturn ${i}(\n`;const a=(e,t)=>{e===q?(r.push(VL.repeatWrapping_float),s+=`\t\ttsl_repeatWrapping_float( coord.${t} )`):e===$?(r.push(VL.clampWrapping_float),s+=`\t\ttsl_clampWrapping_float( coord.${t} )`):e===Y?(r.push(VL.mirrorWrapping_float),s+=`\t\ttsl_mirrorWrapping_float( coord.${t} )`):(s+=`\t\tcoord.${t}`,console.warn(`WebGPURenderer: Unsupported texture wrap type "${e}" for vertex shader.`))};a(e.wrapS,"x"),s+=",\n",a(e.wrapT,"y"),e.isData3DTexture&&(s+=",\n",a(e.wrapR,"z")),s+="\n\t);\n\n}\n",zL[t]=n=new $w(s,r)}return n.build(this),t}generateArrayDeclaration(e,t){return`array< ${this.getType(e)}, ${t} >`}generateTextureDimension(e,t,n){const r=this.getDataFromNode(e,this.shaderStage,this.globalCache);void 0===r.dimensionsSnippet&&(r.dimensionsSnippet={});let i=r.dimensionsSnippet[n];if(void 0===r.dimensionsSnippet[n]){let s,a;const{primarySamples:o}=this.renderer.backend.utils.getTextureSampleData(e),l=o>1;a=e.isData3DTexture?"vec3<u32>":"vec2<u32>",s=l||e.isVideoTexture||e.isStorageTexture?t:`${t}${n?`, u32( ${n} )`:""}`,i=new q_(new bv(`textureDimensions( ${s} )`,a)),r.dimensionsSnippet[n]=i,(e.isArrayTexture||e.isDataArrayTexture||e.isData3DTexture)&&(r.arrayLayerCount=new q_(new bv(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(r.cubeFaceCount=new q_(new bv("6u","u32")))}return i.build(this)}generateFilteredTexture(e,t,n,r="0u"){this._include("biquadraticTexture");return`tsl_biquadraticTexture( ${t}, ${this.generateWrapFunction(e)}( ${n} ), ${this.generateTextureDimension(e,t,r)}, u32( ${r} ) )`}generateTextureLod(e,t,n,r,i="0u"){const s=this.generateWrapFunction(e),a=this.generateTextureDimension(e,t,i),o=e.isData3DTexture?"vec3":"vec2",l=`${o}<u32>( ${s}( ${n} ) * ${o}<f32>( ${a} ) )`;return this.generateTextureLoad(e,t,l,r,i)}generateTextureLoad(e,t,n,r,i="0u"){let s;return!0===e.isVideoTexture?s=`textureLoad( ${t}, ${n} )`:r?s=`textureLoad( ${t}, ${n}, ${r}, u32( ${i} ) )`:(s=`textureLoad( ${t}, ${n}, u32( ${i} ) )`,this.renderer.backend.compatibilityMode&&e.isDepthTexture&&(s+=".x")),s}generateTextureStore(e,t,n,r,i){let s;return s=r?`textureStore( ${t}, ${n}, ${r}, ${i} )`:`textureStore( ${t}, ${n}, ${i} )`,s}isSampleCompare(e){return!0===e.isDepthTexture&&null!==e.compareFunction}isUnfilterable(e){return"float"!==this.getComponentTypeFromTexture(e)||!this.isAvailable("float32Filterable")&&!0===e.isDataTexture&&e.type===le||!1===this.isSampleCompare(e)&&e.minFilter===K&&e.magFilter===K||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1}generateTexture(e,t,n,r,i=this.shaderStage){let s=null;return s=!0===e.isVideoTexture?this._generateVideoSample(t,n,i):this.isUnfilterable(e)?this.generateTextureLod(e,t,n,r,"0",i):this._generateTextureSample(e,t,n,r,i),s}generateTextureGrad(e,t,n,r,i,s=this.shaderStage){if("fragment"===s)return`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${r[0]}, ${r[1]} )`;console.error(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${s} shader.`)}generateTextureCompare(e,t,n,r,i,s=this.shaderStage){if("fragment"===s)return!0===e.isDepthTexture&&!0===e.isArrayTexture?`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${i}, ${r} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${r} )`;console.error(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${s} shader.`)}generateTextureLevel(e,t,n,r,i,s=this.shaderStage){let a=null;return a=!0===e.isVideoTexture?this._generateVideoSample(t,n,s):this._generateTextureSampleLevel(e,t,n,r,i),a}generateTextureBias(e,t,n,r,i,s=this.shaderStage){if("fragment"===s)return`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${r} )`;console.error(`WebGPURenderer: THREE.TextureNode.biasNode does not support ${s} 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,n=e.type;return"texture"===n||"cubeTexture"===n||"storageTexture"===n||"texture3D"===n?t:"buffer"===n||"storageBuffer"===n||"indirectStorageBuffer"===n?this.isCustomStruct(e)?t:t+".value":e.groupNode.name+"."+t}return super.getPropertyName(e)}getOutputStructName(){return"output"}getFunctionOperator(e){const t=BL[e];return void 0!==t?(this._include(t),t):null}getNodeAccess(e,t){return"compute"!==t?ef:e.access}getStorageAccess(e,t){return IL[this.getNodeAccess(e,t)]}getUniformFromNode(e,t,n,r=null){const i=super.getUniformFromNode(e,t,n,r),s=this.getDataFromNode(e,n,this.globalCache);if(void 0===s.uniformGPU){let a;const o=e.groupNode,l=o.name,u=this.getBindGroupArray(l,n);if("texture"===t||"cubeTexture"===t||"storageTexture"===t||"texture3D"===t){let r=null;const s=this.getNodeAccess(e,n);if("texture"===t||"storageTexture"===t?r=new NR(i.name,i.node,o,s):"cubeTexture"===t?r=new PR(i.name,i.node,o,s):"texture3D"===t&&(r=new LR(i.name,i.node,o,s)),r.store=!0===e.isStorageTextureNode,r.setVisibility(OL[n]),!1===this.isUnfilterable(e.value)&&!1===r.store){const e=new yL(`${i.name}_sampler`,i.node,o);e.setVisibility(OL[n]),u.push(e,r),a=[e,r]}else u.push(r),a=[r]}else if("buffer"===t||"storageBuffer"===t||"indirectStorageBuffer"===t){const s=new("buffer"===t?MR:TL)(e,o);s.setVisibility(OL[n]),u.push(s),a=s,i.name=r||"NodeBuffer_"+i.id}else{const e=this.uniformGroups[n]||(this.uniformGroups[n]={});let r=e[l];void 0===r&&(r=new AR(l,o),r.setVisibility(OL[n]),e[l]=r,u.push(r)),a=this.getNodeUniform(i,t),r.addUniform(a)}s.uniformGPU=a}return i}getBuiltin(e,t,n,r=this.shaderStage){const i=this.builtins[r]||(this.builtins[r]=new Map);return!1===i.has(e)&&i.set(e,{name:e,property:t,type:n}),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,n=this.flowShaderNode(e),r=[];for(const e of t.inputs)r.push(e.name+" : "+this.getType(e.type));let i=`fn ${t.name}( ${r.join(", ")} ) -> ${this.getType(t.type)} {\n${n.vars}\n${n.code}\n`;return n.result&&(i+=`\treturn ${n.result};\n`),i+="\n}\n",i}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=[],n=this.directives[e];if(void 0!==n)for(const e of n)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=[],n=this.builtins[e];if(void 0!==n)for(const{name:e,property:r,type:i}of n.values())t.push(`@builtin( ${e} ) ${r} : ${i}`);return t.join(",\n\t")}getScopedArray(e,t,n,r){return!1===this.scopedArrays.has(e)&&this.scopedArrays.set(e,{name:e,scope:t,bufferType:n,bufferCount:r}),e}getScopedArrays(e){if("compute"!==e)return;const t=[];for(const{name:e,scope:n,bufferType:r,bufferCount:i}of this.scopedArrays.values()){const s=this.getType(r);t.push(`var<${n}> ${e}: array< ${s}, ${i} >;`)}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 n=this.getAttributesArray();for(let e=0,r=n.length;e<r;e++){const r=n[e],i=r.name,s=this.getType(r.type);t.push(`@location( ${e} ) ${i} : ${s}`)}}return t.join(",\n\t")}getStructMembers(e){const t=[];for(const n of e.members){const r=e.output?"@location( "+n.index+" ) ":"";let i=this.getType(n.type);n.atomic&&(i="atomic< "+i+" >"),t.push(`\t${r+n.name} : ${i}`)}return e.output&&t.push(`\t${this.getBuiltins("output")}`),t.join(",\n")}getStructs(e){let t="";const n=this.structs[e];if(n.length>0){const e=[];for(const t of n){let n=`struct ${t.name} {\n`;n+=this.getStructMembers(t),n+="\n};",e.push(n)}t="\n"+e.join("\n\n")+"\n"}return t}getVar(e,t,n=null){let r=`var ${t} : `;return r+=null!==n?this.generateArrayDeclaration(e,n):this.getType(e),r}getVars(e){const t=[],n=this.vars[e];if(void 0!==n)for(const e of n)t.push(`\t${this.getVar(e.type,e.name,e.count)};`);return`\n${t.join("\n")}\n`}getVaryings(e){const t=[];if("vertex"===e&&this.getBuiltin("position","Vertex","vec4<f32>","vertex"),"vertex"===e||"fragment"===e){const n=this.varyings,r=this.vars[e];for(let i=0;i<n.length;i++){const s=n[i];if(s.needsInterpolation){let e=`@location( ${i} )`;if(s.interpolationType){const t=null!==s.interpolationSampling?`, ${s.interpolationSampling} )`:" )";e+=` @interpolate( ${s.interpolationType}${t}`}else/^(int|uint|ivec|uvec)/.test(s.type)&&(e+=` @interpolate( ${this.renderer.backend.compatibilityMode?"flat, either":"flat"} )`);t.push(`${e} ${s.name} : ${this.getType(s.type)}`)}else"vertex"===e&&!1===r.includes(s)&&r.push(s)}}const n=this.getBuiltins(e);n&&t.push(n);const r=t.join(",\n\t");return"vertex"===e?this._getWGSLStruct("VaryingsStruct","\t"+r):r}isCustomStruct(e){const t=e.value,n=e.node,r=(t.isBufferAttribute||t.isInstancedBufferAttribute)&&null!==n.structTypeNode,i=n.value&&n.value.array&&"number"==typeof n.value.itemSize&&n.value.array.length>n.value.itemSize;return r&&!i}getUniforms(e){const t=this.uniforms[e],n=[],r=[],i=[],s={};for(const i of t){const t=i.groupNode.name,a=this.bindingsIndexes[t];if("texture"===i.type||"cubeTexture"===i.type||"storageTexture"===i.type||"texture3D"===i.type){const t=i.node.value;let r;!1===this.isUnfilterable(t)&&!0!==i.node.isStorageTextureNode&&(this.isSampleCompare(t)?n.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var ${i.name}_sampler : sampler_comparison;`):n.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var ${i.name}_sampler : sampler;`));let s="";const{primarySamples:o}=this.renderer.backend.utils.getTextureSampleData(t);if(o>1&&(s="_multisampled"),!0===t.isCubeTexture)r="texture_cube<f32>";else if(!0===t.isDepthTexture)r=this.renderer.backend.compatibilityMode&&null===t.compareFunction?`texture${s}_2d<f32>`:`texture_depth${s}_2d${!0===t.isArrayTexture?"_array":""}`;else if(!0===i.node.isStorageTextureNode){const n=AL(t),s=this.getStorageAccess(i.node,e),a=i.node.value.is3DTexture,o=i.node.value.isArrayTexture;r=`texture_storage_${a?"3d":"2d"+(o?"_array":"")}<${n}, ${s}>`}else if(!0===t.isArrayTexture||!0===t.isDataArrayTexture||!0===t.isCompressedArrayTexture)r="texture_2d_array<f32>";else if(!0===t.is3DTexture||!0===t.isData3DTexture)r="texture_3d<f32>";else if(!0===t.isVideoTexture)r="texture_external";else{r=`texture${s}_2d<${this.getComponentTypeFromTexture(t).charAt(0)}32>`}n.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var ${i.name} : ${r};`)}else if("buffer"===i.type||"storageBuffer"===i.type||"indirectStorageBuffer"===i.type){const t=i.node,n=this.getType(t.getNodeType(this)),s=t.bufferCount,o=s>0&&"buffer"===i.type?", "+s:"",l=t.isStorageBufferNode?`storage, ${this.getStorageAccess(t,e)}`:"uniform";if(this.isCustomStruct(i))r.push(`@binding( ${a.binding++} ) @group( ${a.group} ) var<${l}> ${i.name} : ${n};`);else{const e=`\tvalue : array< ${t.isAtomic?`atomic<${n}>`:`${n}`}${o} >`;r.push(this._getWGSLStructBinding(i.name,e,l,a.binding++,a.group))}}else{const e=this.getType(this.getVectorType(i.type)),t=i.groupNode.name;(s[t]||(s[t]={index:a.binding++,id:a.group,snippets:[]})).snippets.push(`\t${i.name} : ${e}`)}}for(const e in s){const t=s[e];i.push(this._getWGSLStructBinding(e,t.snippets.join(",\n"),"uniform",t.index,t.id))}let a=n.join("\n");return a+=r.join("\n"),a+=i.join("\n"),a}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){this.shaderStage=t;const n=e[t];n.uniforms=this.getUniforms(t),n.attributes=this.getAttributes(t),n.varyings=this.getVaryings(t),n.structs=this.getStructs(t),n.vars=this.getVars(t),n.codes=this.getCodes(t),n.directives=this.getDirectives(t),n.scopedArrays=this.getScopedArrays(t);let r="// code\n\n";r+=this.flowCode[t];const i=this.flowNodes[t],s=i[i.length-1],a=s.outputNode,o=void 0!==a&&!0===a.isOutputStructNode;for(const e of i){const i=this.getFlowData(e),l=e.name;if(l&&(r.length>0&&(r+="\n"),r+=`\t// flow -> ${l}\n`),r+=`${i.code}\n\t`,e===s&&"compute"!==t)if(r+="// result\n\n\t","vertex"===t)r+=`varyings.Vertex = ${i.result};`;else if("fragment"===t)if(o)n.returnType=a.getNodeType(this),n.structs+="var<private> output : "+n.returnType+";",r+=`return ${i.result};`;else{let e="\t@location(0) color: vec4<f32>";const t=this.getBuiltins("output");t&&(e+=",\n\t"+t),n.returnType="OutputStruct",n.structs+=this._getWGSLStruct("OutputStruct",e),n.structs+="\nvar<private> output : OutputStruct;",r+=`output.color = ${i.result};\n\n\treturn output;`}}n.flow=r}this.shaderStage=null,null!==this.material?(this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment)):this.computeShader=this._getWGSLComputeCode(e.compute,(this.object.workgroupSize||[64]).join(", "))}getMethod(e,t=null){let n;return null!==t&&(n=this._getWGSLMethod(e+"_"+t)),void 0===n&&(n=this._getWGSLMethod(e)),n||e}getType(e){return kL[e]||e}isAvailable(e){let t=FL[e];return void 0===t&&("float32Filterable"===e?t=this.renderer.hasFeature("float32-filterable"):"clipDistance"===e&&(t=this.renderer.hasFeature("clip-distances")),FL[e]=t),t}_getWGSLMethod(e){return void 0!==VL[e]&&this._include(e),GL[e]}_include(e){const t=VL[e];return t.build(this),null!==this.currentFunctionNode&&this.currentFunctionNode.includes.push(t),t}_getWGSLVertexCode(e){return`${this.getSignature()}\n// directives\n${e.directives}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\nvar<private> varyings : VaryingsStruct;\n\n// codes\n${e.codes}\n\n@vertex\nfn main( ${e.attributes} ) -> VaryingsStruct {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n\treturn varyings;\n\n}\n`}_getWGSLFragmentCode(e){return`${this.getSignature()}\n// global\n${HL}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@fragment\nfn main( ${e.varyings} ) -> ${e.returnType} {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLComputeCode(e,t){return`${this.getSignature()}\n// directives\n${e.directives}\n\n// system\nvar<private> instanceIndex : u32;\n\n// locals\n${e.scopedArrays}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@compute @workgroup_size( ${t} )\nfn main( ${e.attributes} ) {\n\n\t// system\n\tinstanceIndex = globalId.x + globalId.y * numWorkgroups.x * u32(${t}) + globalId.z * numWorkgroups.x * numWorkgroups.y * u32(${t});\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLStruct(e,t){return`\nstruct ${e} {\n${t}\n};`}_getWGSLStructBinding(e,t,n,r=0,i=0){const s=e+"Struct";return`${this._getWGSLStruct(s,t)}\n@binding( ${r} ) @group( ${i} )\nvar<${n}> ${e} : ${s};`}}class WL{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return null!==e.depthTexture?t=this.getTextureFormatGPU(e.depthTexture):e.depth&&e.stencil?t=gN:e.depth&&(t=mN),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,n=e.getRenderTarget();t=n?n.samples:e.samples}else e.renderTarget&&(t=e.renderTarget.samples);t=t||1;const n=t>1&&null!==e.renderTarget&&!0!==e.isDepthTexture&&!0!==e.isFramebufferTexture;return{samples:t,primarySamples:n?1:t,isMSAA:n}}getCurrentColorFormat(e){let t;return t=null!==e.textures?this.getTextureFormatGPU(e.textures[0]):this.getPreferredCanvasFormat(),t}getCurrentColorSpace(e){return null!==e.textures?e.textures[0].colorSpace:this.backend.renderer.outputColorSpace}getPrimitiveTopology(e,t){return e.isPoints?cC:e.isLineSegments||e.isMesh&&!0===t.wireframe?hC:e.isLine?dC:e.isMesh?pC:void 0}getSampleCount(e){let t=1;return e>1&&(t=Math.pow(2,Math.floor(Math.log2(e))),2===t&&(t=4)),t}getSampleCountRenderContext(e){return null!==e.textures?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.samples)}getPreferredCanvasFormat(){const e=this.backend.parameters.outputType;if(void 0===e)return navigator.gpu.getPreferredCanvasFormat();if(e===ne)return eN;if(e===ue)return cN;throw new Error("Unsupported outputType")}}const XL=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&&XL.set(Float16Array,["float16"]);const qL=new Map([[Wr,["float16"]]]),$L=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class YL{constructor(e){this.backend=e}createAttribute(e,t){const n=this._getBufferAttribute(e),r=this.backend,i=r.get(n);let s=i.buffer;if(void 0===s){const a=r.device;let o=n.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(n.array=o,(n.isStorageBufferAttribute||n.isStorageInstancedBufferAttribute)&&3===n.itemSize){o=new o.constructor(4*n.count);for(let e=0;e<n.count;e++)o.set(n.array.subarray(3*e,3*e+3),4*e);n.itemSize=4,n.array=o,i._force3to4BytesAlignment=!0}const l=o.byteLength,u=l+(4-l%4)%4;s=a.createBuffer({label:n.name,size:u,usage:t,mappedAtCreation:!0}),new o.constructor(s.getMappedRange()).set(o),s.unmap(),i.buffer=s}}updateAttribute(e){const t=this._getBufferAttribute(e),n=this.backend,r=n.device,i=n.get(t),s=n.get(t).buffer;let a=t.array;if(!0===i._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=this._isTypedArray(a),l=t.updateRanges;if(0===l.length)r.queue.writeBuffer(s,0,a,0);else{const e=o?1:a.BYTES_PER_ELEMENT;for(let t=0,n=l.length;t<n;t++){const n=l[t];let u,c;if(!0===i._force3to4BytesAlignment){u=4*Math.floor(n.start/3)*e,c=4*Math.ceil(n.count/3)*e}else u=n.start*e,c=n.count*e;const h=u*(o?a.BYTES_PER_ELEMENT:1);r.queue.writeBuffer(s,h,a,u,c)}t.clearUpdateRanges()}}createShaderVertexBuffers(e){const t=e.getAttributes(),n=new Map;for(let e=0;e<t.length;e++){const r=t[e],i=r.array.BYTES_PER_ELEMENT,s=this._getBufferAttribute(r);let a=n.get(s);if(void 0===a){let e,t;!0===r.isInterleavedBufferAttribute?(e=r.data.stride*i,t=r.data.isInstancedInterleavedBuffer?gL:mL):(e=r.itemSize*i,t=r.isInstancedBufferAttribute?gL:mL),!1!==r.normalized||r.array.constructor!==Int16Array&&r.array.constructor!==Uint16Array||(e=4),a={arrayStride:e,attributes:[],stepMode:t},n.set(s,a)}const o=this._getVertexFormat(r),l=!0===r.isInterleavedBufferAttribute?r.offset*i:0;a.attributes.push({shaderLocation:e,offset:l,format:o})}return Array.from(n.values())}destroyAttribute(e){const t=this.backend;t.get(this._getBufferAttribute(e)).buffer.destroy(),t.delete(e)}async getArrayBufferAsync(e){const t=this.backend,n=t.device,r=t.get(this._getBufferAttribute(e)).buffer,i=r.size,s=n.createBuffer({label:`${e.name}_readback`,size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),a=n.createCommandEncoder({label:`readback_encoder_${e.name}`});a.copyBufferToBuffer(r,0,s,0,i);const o=a.finish();n.queue.submit([o]),await s.mapAsync(GPUMapMode.READ);const l=s.getMappedRange(),u=new e.array.constructor(l.slice(0));return s.unmap(),u.buffer}_getVertexFormat(e){const{itemSize:t,normalized:n}=e,r=e.array.constructor,i=e.constructor;let s;if(1===t)s=$L.get(r);else{const e=(qL.get(i)||XL.get(r))[n?1:0];if(e){const n=r.BYTES_PER_ELEMENT*t,i=4*Math.floor((n+3)/4)/r.BYTES_PER_ELEMENT;if(i%1)throw new Error("THREE.WebGPUAttributeUtils: Bad vertex format item size.");s=`${e}x${i}`}}return s||console.error("THREE.WebGPUAttributeUtils: Vertex format not supported yet."),s}_isTypedArray(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}class KL{constructor(e){this.backend=e,this.bindGroupLayoutCache=new WeakMap}createBindingsLayout(e){const t=this.backend,n=t.device,r=[];let i=0;for(const n of e.bindings){const e={binding:i++,visibility:n.visibility};if(n.isUniformBuffer||n.isStorageBuffer){const t={};n.isStorageBuffer&&(4&n.visibility&&(n.access===nf||n.access===tf)?t.type=KP:t.type=QP),e.buffer=t}else if(n.isSampler){const r={};n.texture.isDepthTexture&&(null!==n.texture.compareFunction?r.type=nL:t.compatibilityMode&&(r.type=tL)),e.sampler=r}else if(n.isSampledTexture&&n.texture.isVideoTexture)e.externalTexture={};else if(n.isSampledTexture&&n.store){const t={};t.format=this.backend.get(n.texture).texture.format;const r=n.access;t.access=r===nf?eL:r===tf?ZP:JP,n.texture.isArrayTexture?t.viewDimension=hL:n.texture.is3DTexture&&(t.viewDimension=pL),e.storageTexture=t}else if(n.isSampledTexture){const r={},{primarySamples:i}=t.utils.getTextureSampleData(n.texture);if(i>1&&(r.multisampled=!0,n.texture.isDepthTexture||(r.sampleType=iL)),n.texture.isDepthTexture)t.compatibilityMode&&null===n.texture.compareFunction?r.sampleType=iL:r.sampleType=sL;else if(n.texture.isDataTexture||n.texture.isDataArrayTexture||n.texture.isData3DTexture){const e=n.texture.type;e===ae?r.sampleType=aL:e===oe?r.sampleType=oL:e===le&&(this.backend.hasFeature("float32-filterable")?r.sampleType=rL:r.sampleType=iL)}n.isSampledCubeTexture?r.viewDimension=dL:n.texture.isArrayTexture||n.texture.isDataArrayTexture||n.texture.isCompressedArrayTexture?r.viewDimension=hL:n.isSampledTexture3D&&(r.viewDimension=pL),e.texture=r}else console.error(`WebGPUBindingUtils: Unsupported binding "${n}".`);r.push(e)}return n.createBindGroupLayout({entries:r})}createBindings(e,t,n,r=0){const{backend:i,bindGroupLayoutCache:s}=this,a=i.get(e);let o,l=s.get(e.bindingsReference);void 0===l&&(l=this.createBindingsLayout(e),s.set(e.bindingsReference,l)),n>0&&(void 0===a.groups&&(a.groups=[],a.versions=[]),a.versions[n]===r&&(o=a.groups[n])),void 0===o&&(o=this.createBindGroup(e,l),n>0&&(a.groups[n]=o,a.versions[n]=r)),a.group=o,a.layout=l}updateBinding(e){const t=this.backend,n=t.device,r=e.buffer,i=t.get(e).buffer;n.queue.writeBuffer(i,0,r,0)}createBindGroupIndex(e,t){const n=this.backend.device,r=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,i=e[0],s=n.createBuffer({label:"bindingCameraIndex_"+i,size:16,usage:r});n.queue.writeBuffer(s,0,e,0);const a=[{binding:0,resource:{buffer:s}}];return n.createBindGroup({label:"bindGroupCameraIndex_"+i,layout:t,entries:a})}createBindGroup(e,t){const n=this.backend,r=n.device;let i=0;const s=[];for(const t of e.bindings){if(t.isUniformBuffer){const e=n.get(t);if(void 0===e.buffer){const n=t.byteLength,i=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,s=r.createBuffer({label:"bindingBuffer_"+t.name,size:n,usage:i});e.buffer=s}s.push({binding:i,resource:{buffer:e.buffer}})}else if(t.isStorageBuffer){const e=n.get(t);if(void 0===e.buffer){const r=t.attribute;e.buffer=n.get(r).buffer}s.push({binding:i,resource:{buffer:e.buffer}})}else if(t.isSampler){const e=n.get(t.texture);s.push({binding:i,resource:e.sampler})}else if(t.isSampledTexture){const e=n.get(t.texture);let a;if(void 0!==e.externalTexture)a=r.importExternalTexture({source:e.externalTexture});else{const n=t.store?1:e.texture.mipLevelCount,r=`view-${e.texture.width}-${e.texture.height}-${n}`;if(a=e[r],void 0===a){const i=fL;let s;s=t.isSampledCubeTexture?dL:t.isSampledTexture3D?pL:t.texture.isArrayTexture||t.texture.isDataArrayTexture||t.texture.isCompressedArrayTexture?hL:cL,a=e[r]=e.texture.createView({aspect:i,dimension:s,mipLevelCount:n})}}s.push({binding:i,resource:a})}i++}return r.createBindGroup({label:"bindGroup_"+e.name,layout:t,entries:s})}}class QL{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:n,material:r,geometry:i,pipeline:s}=e,{vertexProgram:a,fragmentProgram:o}=s,l=this.backend,u=l.device,c=l.utils,h=l.get(s),d=[];for(const t of e.getBindings()){const e=l.get(t);d.push(e.layout)}const p=l.attributeUtils.createShaderVertexBuffers(e);let f;0===r.blending||1===r.blending&&!1===r.transparent||(f=this._getBlending(r));let m={};!0===r.stencilWrite&&(m={compare:this._getStencilCompare(r),failOp:this._getStencilOperation(r.stencilFail),depthFailOp:this._getStencilOperation(r.stencilZFail),passOp:this._getStencilOperation(r.stencilZPass)});const g=this._getColorWriteMask(r),_=[];if(null!==e.context.textures){const t=e.context.textures;for(let e=0;e<t.length;e++){const n=c.getTextureFormatGPU(t[e]);_.push({format:n,blend:f,writeMask:g})}}else{const t=c.getCurrentColorFormat(e.context);_.push({format:t,blend:f,writeMask:g})}const v=l.get(a).module,y=l.get(o).module,x=this._getPrimitiveState(n,i,r),b=this._getDepthCompare(r),T=c.getCurrentDepthStencilFormat(e.context),S=this._getSampleCount(e.context),M={label:`renderPipeline_${r.name||r.type}_${r.id}`,vertex:Object.assign({},v,{buffers:p}),fragment:Object.assign({},y,{targets:_}),primitive:x,multisample:{count:S,alphaToCoverageEnabled:r.alphaToCoverage&&S>1},layout:u.createPipelineLayout({bindGroupLayouts:d})},w={},E=e.context.depth,A=e.context.stencil;if(!0!==E&&!0!==A||(!0===E&&(w.format=T,w.depthWriteEnabled=r.depthWrite,w.depthCompare=b),!0===A&&(w.stencilFront=m,w.stencilBack={},w.stencilReadMask=r.stencilFuncMask,w.stencilWriteMask=r.stencilWriteMask),!0===r.polygonOffset&&(w.depthBias=r.polygonOffsetUnits,w.depthBiasSlopeScale=r.polygonOffsetFactor,w.depthBiasClamp=0),M.depthStencil=w),null===t)h.pipeline=u.createRenderPipeline(M);else{const e=new Promise(e=>{u.createRenderPipelineAsync(M).then(t=>{h.pipeline=t,e()})});t.push(e)}}createBundleEncoder(e,t="renderBundleEncoder"){const n=this.backend,{utils:r,device:i}=n,s=r.getCurrentDepthStencilFormat(e),a={label:t,colorFormats:[r.getCurrentColorFormat(e)],depthStencilFormat:s,sampleCount:this._getSampleCount(e)};return i.createRenderBundleEncoder(a)}createComputePipeline(e,t){const n=this.backend,r=n.device,i=n.get(e.computeProgram).module,s=n.get(e),a=[];for(const e of t){const t=n.get(e);a.push(t.layout)}s.pipeline=r.createComputePipeline({compute:i,layout:r.createPipelineLayout({bindGroupLayouts:a})})}_getBlending(e){let t,n;const r=e.blending,i=e.blendSrc,s=e.blendDst,a=e.blendEquation;if(5===r){const r=null!==e.blendSrcAlpha?e.blendSrcAlpha:i,o=null!==e.blendDstAlpha?e.blendDstAlpha:s,l=null!==e.blendEquationAlpha?e.blendEquationAlpha:a;t={srcFactor:this._getBlendFactor(i),dstFactor:this._getBlendFactor(s),operation:this._getBlendOperation(a)},n={srcFactor:this._getBlendFactor(r),dstFactor:this._getBlendFactor(o),operation:this._getBlendOperation(l)}}else{const i=(e,r,i,s)=>{t={srcFactor:e,dstFactor:r,operation:UP},n={srcFactor:i,dstFactor:s,operation:UP}};if(e.premultipliedAlpha)switch(r){case 1:i(SP,AP,SP,AP);break;case 2:i(SP,SP,SP,SP);break;case 3:i(TP,wP,TP,SP);break;case 4:i(RP,AP,TP,SP)}else switch(r){case 1:i(EP,AP,SP,AP);break;case 2:i(EP,SP,SP,SP);break;case 3:console.error("THREE.WebGPURenderer: SubtractiveBlending requires material.premultipliedAlpha = true");break;case 4:console.error("THREE.WebGPURenderer: MultiplyBlending requires material.premultipliedAlpha = true")}}if(void 0!==t&&void 0!==n)return{color:t,alpha:n};console.error("THREE.WebGPURenderer: Invalid blending: ",r)}_getBlendFactor(e){let t;switch(e){case y:t=TP;break;case 201:t=SP;break;case 202:t=MP;break;case 203:t=wP;break;case S:t=EP;break;case M:t=AP;break;case 208:t=RP;break;case 209:t=CP;break;case 206:t=NP;break;case 207:t=PP;break;case 210:t=LP;break;case 211:t=DP;break;case 212:t=IP;break;default:console.error("THREE.WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const n=e.stencilFunc;switch(n){case 512:t=mC;break;case 519:t=TC;break;case 513:t=gC;break;case 515:t=vC;break;case 514:t=_C;break;case 518:t=bC;break;case 516:t=yC;break;case 517:t=xC;break;default:console.error("THREE.WebGPURenderer: Invalid stencil function.",n)}return t}_getStencilOperation(e){let t;switch(e){case ot:t=GP;break;case 0:t=HP;break;case 7681:t=jP;break;case 5386:t=WP;break;case 7682:t=XP;break;case 7683:t=qP;break;case 34055:t=$P;break;case 34056:t=YP;break;default:console.error("THREE.WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case g:t=UP;break;case 101:t=OP;break;case 102:t=FP;break;case 103:t=BP;break;case 104:t=kP;break;default:console.error("THREE.WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,n){const r={},i=this.backend.utils;switch(r.topology=i.getPrimitiveTopology(e,n),null!==t.index&&!0===e.isLine&&!0!==e.isLineSegments&&(r.stripIndexFormat=t.index.array instanceof Uint16Array?NC:PC),n.side){case 0:r.frontFace=EC,r.cullMode=CC;break;case 1:r.frontFace=EC,r.cullMode=RC;break;case 2:r.frontFace=EC,r.cullMode=AC;break;default:console.error("THREE.WebGPUPipelineUtils: Unknown material.side value.",n.side)}return r}_getColorWriteMask(e){return!0===e.colorWrite?VP:zP}_getDepthCompare(e){let t;if(!1===e.depthTest)t=TC;else{const n=e.depthFunc;switch(n){case 0:t=mC;break;case 1:t=TC;break;case 2:t=gC;break;case 3:t=vC;break;case 4:t=_C;break;case 5:t=bC;break;case 6:t=yC;break;case 7:t=xC;break;default:console.error("THREE.WebGPUPipelineUtils: Invalid depth function.",n)}}return t}}class ZL extends aC{constructor(e,t,n=2048){super(n),this.device=e,this.type=t,this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxQueries,label:`queryset_global_timestamp_${t}`});const r=8*this.maxQueries;this.resolveBuffer=this.device.createBuffer({label:`buffer_timestamp_resolve_${t}`,size:r,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.resultBuffer=this.device.createBuffer({label:`buffer_timestamp_result_${t}`,size:r,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ})}allocateQueriesForContext(e){if(!this.trackTimestamp||this.isDisposed)return null;if(this.currentQueryIndex+2>this.maxQueries)return jt(`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.id,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,n=8*t;this.currentQueryIndex=0,this.queryOffsets.clear();const r=this.device.createCommandEncoder();r.resolveQuerySet(this.querySet,0,t,this.resolveBuffer,0),r.copyBufferToBuffer(this.resolveBuffer,0,this.resultBuffer,0,n);const i=r.finish();if(this.device.queue.submit([i]),"unmapped"!==this.resultBuffer.mapState)return this.lastValue;if(await this.resultBuffer.mapAsync(GPUMapMode.READ,0,n),this.isDisposed)return"mapped"===this.resultBuffer.mapState&&this.resultBuffer.unmap(),this.lastValue;const s=new BigUint64Array(this.resultBuffer.getMappedRange(0,n));let a=0;for(const[,t]of e){const e=s[t],n=s[t+1];a+=Number(n-e)/1e6}return this.resultBuffer.unmap(),this.lastValue=a,a}catch(e){return console.error("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){console.error("Error waiting for pending resolve:",e)}if(this.resultBuffer&&"mapped"===this.resultBuffer.mapState)try{this.resultBuffer.unmap()}catch(e){console.error("Error unmapping buffer:",e)}this.querySet&&(this.querySet.destroy(),this.querySet=null),this.resolveBuffer&&(this.resolveBuffer.destroy(),this.resolveBuffer=null),this.resultBuffer&&(this.resultBuffer.destroy(),this.resultBuffer=null),this.queryOffsets.clear(),this.pendingResolve=null}}}class JL extends GR{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=void 0===e.alpha||e.alpha,this.parameters.compatibilityMode=void 0!==e.compatibilityMode&&e.compatibilityMode,this.parameters.requiredLimits=void 0===e.requiredLimits?{}:e.requiredLimits,this.compatibilityMode=this.parameters.compatibilityMode,this.device=null,this.context=null,this.colorBuffer=null,this.defaultRenderPassdescriptor=null,this.utils=new WL(this),this.attributeUtils=new YL(this),this.bindingUtils=new KL(this),this.pipelineUtils=new QL(this),this.textureUtils=new EL(this),this.occludedResolveCache=new Map}async init(e){await super.init(e);const t=this.parameters;let n;if(void 0===t.device){const e={powerPreference:t.powerPreference,featureLevel:t.compatibilityMode?"compatibility":void 0},r="undefined"!=typeof navigator?await navigator.gpu.requestAdapter(e):null;if(null===r)throw new Error("WebGPUBackend: Unable to create WebGPU adapter.");const i=Object.values(_L),s=[];for(const e of i)r.features.has(e)&&s.push(e);const a={requiredFeatures:s,requiredLimits:t.requiredLimits};n=await r.requestDevice(a)}else n=t.device;n.lost.then(t=>{const n={api:"WebGPU",message:t.message||"Unknown reason",reason:t.reason||null,originalEvent:t};e.onDeviceLost(n)});const r=void 0!==t.context?t.context:e.domElement.getContext("webgpu");this.device=n,this.context=r;const i=t.alpha?"premultiplied":"opaque";this.trackTimestamp=this.trackTimestamp&&this.hasFeature(_L.TimestampQuery),this.context.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:i}),this.updateSize()}get coordinateSystem(){return xt}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){let e=this.defaultRenderPassdescriptor;if(null===e){const t=this.renderer;e={colorAttachments:[{view:null}]},!0!==this.renderer.depth&&!0!==this.renderer.stencil||(e.depthStencilAttachment={view:this.textureUtils.getDepthBuffer(t.depth,t.stencil).createView()});const n=e.colorAttachments[0];this.renderer.samples>0?n.view=this.colorBuffer.createView():n.resolveTarget=void 0,this.defaultRenderPassdescriptor=e}const t=e.colorAttachments[0];return this.renderer.samples>0?t.resolveTarget=this.context.getCurrentTexture().createView():t.view=this.context.getCurrentTexture().createView(),e}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.image.depth>1&&e.camera.isArrayCamera}_getRenderPassDescriptor(e,t={}){const n=e.renderTarget,r=this.get(n);let i=r.descriptors;if(void 0===i||r.width!==n.width||r.height!==n.height||r.dimensions!==n.dimensions||r.activeMipmapLevel!==e.activeMipmapLevel||r.activeCubeFace!==e.activeCubeFace||r.samples!==n.samples){i={},r.descriptors=i;const e=()=>{n.removeEventListener("dispose",e),this.delete(n)};!1===n.hasEventListener("dispose",e)&&n.addEventListener("dispose",e)}const s=e.getCacheKey();let a=i[s];if(void 0===a){const t=e.textures,o=[];let l;const u=this._isRenderCameraDepthArray(e);for(let r=0;r<t.length;r++){const i=this.get(t[r]),s={label:`colorAttachment_${r}`,baseMipLevel:e.activeMipmapLevel,mipLevelCount:1,baseArrayLayer:e.activeCubeFace,arrayLayerCount:1,dimension:cL};if(n.isRenderTarget3D)l=e.activeCubeFace,s.baseArrayLayer=0,s.dimension=pL,s.depthOrArrayLayers=t[r].image.depth;else if(n.isRenderTarget&&t[r].image.depth>1)if(!0===u){const t=e.camera.cameras;for(let e=0;e<t.length;e++){const t={...s,baseArrayLayer:e,arrayLayerCount:1,dimension:cL},n=i.texture.createView(t);o.push({view:n,resolveTarget:void 0,depthSlice:void 0})}}else s.dimension=hL,s.depthOrArrayLayers=t[r].image.depth;if(!0!==u){const e=i.texture.createView(s);let t,n;void 0!==i.msaaTexture?(t=i.msaaTexture.createView(),n=e):(t=e,n=void 0),o.push({view:t,resolveTarget:n,depthSlice:l})}}if(a={textureViews:o},e.depth){const t=this.get(e.depthTexture),n={};e.depthTexture.isArrayTexture&&(n.dimension=cL,n.arrayLayerCount=1,n.baseArrayLayer=e.activeCubeFace),a.depthStencilView=t.texture.createView(n)}i[s]=a,r.width=n.width,r.height=n.height,r.samples=n.samples,r.activeMipmapLevel=e.activeMipmapLevel,r.activeCubeFace=e.activeCubeFace,r.dimensions=n.dimensions}const o={colorAttachments:[]};for(let e=0;e<a.textureViews.length;e++){const n=a.textureViews[e];let r={r:0,g:0,b:0,a:1};0===e&&t.clearValue&&(r=t.clearValue),o.colorAttachments.push({view:n.view,depthSlice:n.depthSlice,resolveTarget:n.resolveTarget,loadOp:t.loadOp||MC,storeOp:t.storeOp||SC,clearValue:r})}return a.depthStencilView&&(o.depthStencilAttachment={view:a.depthStencilView}),o}beginRender(e){const t=this.get(e),n=this.device,r=e.occlusionQueryCount;let i,s;r>0&&(t.currentOcclusionQuerySet&&t.currentOcclusionQuerySet.destroy(),t.currentOcclusionQueryBuffer&&t.currentOcclusionQueryBuffer.destroy(),t.currentOcclusionQuerySet=t.occlusionQuerySet,t.currentOcclusionQueryBuffer=t.occlusionQueryBuffer,t.currentOcclusionQueryObjects=t.occlusionQueryObjects,i=n.createQuerySet({type:"occlusion",count:r,label:`occlusionQuerySet_${e.id}`}),t.occlusionQuerySet=i,t.occlusionQueryIndex=0,t.occlusionQueryObjects=new Array(r),t.lastOcclusionObject=null),s=null===e.textures?this._getDefaultRenderPassDescriptor():this._getRenderPassDescriptor(e,{loadOp:MC}),this.initTimestampQuery(e,s),s.occlusionQuerySet=i;const a=s.depthStencilAttachment;if(null!==e.textures){const t=s.colorAttachments;for(let n=0;n<t.length;n++){const r=t[n];e.clearColor?(r.clearValue=0===n?e.clearColorValue:{r:0,g:0,b:0,a:1},r.loadOp=wC):r.loadOp=MC,r.storeOp=SC}}else{const t=s.colorAttachments[0];e.clearColor?(t.clearValue=e.clearColorValue,t.loadOp=wC):t.loadOp=MC,t.storeOp=SC}e.depth&&(e.clearDepth?(a.depthClearValue=e.clearDepthValue,a.depthLoadOp=wC):a.depthLoadOp=MC,a.depthStoreOp=SC),e.stencil&&(e.clearStencil?(a.stencilClearValue=e.clearStencilValue,a.stencilLoadOp=wC):a.stencilLoadOp=MC,a.stencilStoreOp=SC);const o=n.createCommandEncoder({label:"renderContext_"+e.id});if(!0===this._isRenderCameraDepthArray(e)){const n=e.camera.cameras;t.layerDescriptors&&t.layerDescriptors.length===n.length?this._updateDepthLayerDescriptors(e,t,n):this._createDepthLayerDescriptors(e,t,s,n),t.bundleEncoders=[],t.bundleSets=[];for(let r=0;r<n.length;r++){const n=this.pipelineUtils.createBundleEncoder(e,"renderBundleArrayCamera_"+r),i={attributes:{},bindingGroups:[],pipeline:null,index:null};t.bundleEncoders.push(n),t.bundleSets.push(i)}t.currentPass=null}else{const n=o.beginRenderPass(s);if(t.currentPass=n,e.viewport&&this.updateViewport(e),e.scissor){const{x:t,y:r,width:i,height:s}=e.scissorValue;n.setScissorRect(t,r,i,s)}}t.descriptor=s,t.encoder=o,t.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.renderBundles=[]}_createDepthLayerDescriptors(e,t,n,r){const i=n.depthStencilAttachment;t.layerDescriptors=[];const s=this.get(e.depthTexture);s.viewCache||(s.viewCache=[]);for(let a=0;a<r.length;a++){const r={...n,colorAttachments:[{...n.colorAttachments[0],view:n.colorAttachments[a].view}]};if(n.depthStencilAttachment){const t=a;s.viewCache[t]||(s.viewCache[t]=s.texture.createView({dimension:cL,baseArrayLayer:a,arrayLayerCount:1})),r.depthStencilAttachment={view:s.viewCache[t],depthLoadOp:i.depthLoadOp||wC,depthStoreOp:i.depthStoreOp||SC,depthClearValue:i.depthClearValue||1},e.stencil&&(r.depthStencilAttachment.stencilLoadOp=i.stencilLoadOp,r.depthStencilAttachment.stencilStoreOp=i.stencilStoreOp,r.depthStencilAttachment.stencilClearValue=i.stencilClearValue)}else r.depthStencilAttachment={...i};t.layerDescriptors.push(r)}}_updateDepthLayerDescriptors(e,t,n){for(let r=0;r<n.length;r++){const n=t.layerDescriptors[r];if(n.depthStencilAttachment){const t=n.depthStencilAttachment;e.depth&&(e.clearDepth?(t.depthClearValue=e.clearDepthValue,t.depthLoadOp=wC):t.depthLoadOp=MC),e.stencil&&(e.clearStencil?(t.stencilClearValue=e.clearStencilValue,t.stencilLoadOp=wC):t.stencilLoadOp=MC)}}}finishRender(e){const t=this.get(e),n=e.occlusionQueryCount;t.renderBundles.length>0&&t.currentPass.executeBundles(t.renderBundles),n>t.occlusionQueryIndex&&t.currentPass.endOcclusionQuery();const r=t.encoder;if(!0===this._isRenderCameraDepthArray(e)){const n=[];for(let e=0;e<t.bundleEncoders.length;e++){const r=t.bundleEncoders[e];n.push(r.finish())}for(let i=0;i<t.layerDescriptors.length;i++)if(i<n.length){const s=t.layerDescriptors[i],a=r.beginRenderPass(s);if(e.viewport){const{x:t,y:n,width:r,height:i,minDepth:s,maxDepth:o}=e.viewportValue;a.setViewport(t,n,r,i,s,o)}if(e.scissor){const{x:t,y:n,width:r,height:i}=e.scissorValue;a.setScissorRect(t,n,r,i)}a.executeBundles([n[i]]),a.end()}}else t.currentPass&&t.currentPass.end();if(n>0){const r=8*n;let i=this.occludedResolveCache.get(r);void 0===i&&(i=this.device.createBuffer({size:r,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.occludedResolveCache.set(r,i));const s=this.device.createBuffer({size:r,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});t.encoder.resolveQuerySet(t.occlusionQuerySet,0,n,i,0),t.encoder.copyBufferToBuffer(i,0,s,0,r),t.occlusionQueryBuffer=s,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 n=t[e];!0===n.generateMipmaps&&this.textureUtils.generateMipmaps(n)}}}isOccluded(e,t){const n=this.get(e);return n.occluded&&n.occluded.has(t)}async resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueryBuffer:n,currentOcclusionQueryObjects:r}=t;if(n&&r){const e=new WeakSet;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueryBuffer=null,await n.mapAsync(GPUMapMode.READ);const i=n.getMappedRange(),s=new BigUint64Array(i);for(let t=0;t<r.length;t++)s[t]===BigInt(0)&&e.add(r[t]);n.destroy(),t.occluded=e}}updateViewport(e){const{currentPass:t}=this.get(e),{x:n,y:r,width:i,height:s,minDepth:a,maxDepth:o}=e.viewportValue;t.setViewport(n,r,i,s,a,o)}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,n,r=null){const i=this.device,s=this.renderer;let a,o,l,u,c=[];if(e){const e=this.getClearColor();o={r:e.r,g:e.g,b:e.b,a:e.a}}if(null===r){l=s.depth,u=s.stencil;const t=this._getDefaultRenderPassDescriptor();if(e){c=t.colorAttachments;const e=c[0];e.clearValue=o,e.loadOp=wC,e.storeOp=SC}(l||u)&&(a=t.depthStencilAttachment)}else{l=r.depth,u=r.stencil;const i={loadOp:e?wC:MC,clearValue:e?o:void 0};l&&(i.depthLoadOp=t?wC:MC,i.depthClearValue=t?s.getClearDepth():void 0,i.depthStoreOp=SC),u&&(i.stencilLoadOp=n?wC:MC,i.stencilClearValue=n?s.getClearStencil():void 0,i.stencilStoreOp=SC);const h=this._getRenderPassDescriptor(r,i);c=h.colorAttachments,a=h.depthStencilAttachment}l&&a&&void 0===a.depthLoadOp&&(t?(a.depthLoadOp=wC,a.depthClearValue=s.getClearDepth(),a.depthStoreOp=SC):(a.depthLoadOp=MC,a.depthStoreOp=SC)),u&&a&&void 0===a.stencilLoadOp&&(n?(a.stencilLoadOp=wC,a.stencilClearValue=s.getClearStencil(),a.stencilStoreOp=SC):(a.stencilLoadOp=MC,a.stencilStoreOp=SC));const h=i.createCommandEncoder({label:"clear"});h.beginRenderPass({colorAttachments:c,depthStencilAttachment:a}).end(),i.queue.submit([h.finish()])}beginCompute(e){const t=this.get(e),n={label:"computeGroup_"+e.id};this.initTimestampQuery(e,n),t.cmdEncoderGPU=this.device.createCommandEncoder({label:"computeGroup_"+e.id}),t.passEncoderGPU=t.cmdEncoderGPU.beginComputePass(n)}compute(e,t,n,r){const{passEncoderGPU:i}=this.get(e),s=this.get(r).pipeline;this.pipelineUtils.setPipeline(i,s);for(let e=0,t=n.length;e<t;e++){const t=n[e],r=this.get(t);i.setBindGroup(e,r.group)}const a=this.device.limits.maxComputeWorkgroupsPerDimension,o=this.get(t);void 0===o.dispatchSize&&(o.dispatchSize={x:0,y:1,z:1});const{dispatchSize:l}=o;t.dispatchCount>a?(l.x=Math.min(t.dispatchCount,a),l.y=Math.ceil(t.dispatchCount/a)):l.x=t.dispatchCount,i.dispatchWorkgroups(l.x,l.y,l.z)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),this.device.queue.submit([t.cmdEncoderGPU.finish()])}async waitForGPU(){await this.device.queue.onSubmittedWorkDone()}draw(e,t){const{object:n,material:r,context:i,pipeline:s}=e,a=e.getBindings(),o=this.get(i),l=this.get(s).pipeline,u=e.getIndex(),c=null!==u,h=e.getDrawParameters();if(null===h)return;const d=(t,n)=>{this.pipelineUtils.setPipeline(t,l),n.pipeline=l;const s=n.bindingGroups;for(let e=0,n=a.length;e<n;e++){const n=a[e],r=this.get(n);s[n.index]!==n.id&&(t.setBindGroup(n.index,r.group),s[n.index]=n.id)}if(!0===c&&n.index!==u){const e=this.get(u).buffer,r=u.array instanceof Uint16Array?NC:PC;t.setIndexBuffer(e,r),n.index=u}const h=e.getVertexBuffers();for(let e=0,r=h.length;e<r;e++){const r=h[e];if(n.attributes[e]!==r){const i=this.get(r).buffer;t.setVertexBuffer(e,i),n.attributes[e]=r}}!0===i.stencil&&!0===r.stencilWrite&&o.currentStencilRef!==r.stencilRef&&(t.setStencilReference(r.stencilRef),o.currentStencilRef=r.stencilRef)},p=(r,i)=>{if(d(r,i),!0===n.isBatchedMesh){const e=n._multiDrawStarts,i=n._multiDrawCounts,s=n._multiDrawCount,a=n._multiDrawInstances;null!==a&&jt("THREE.WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.");for(let o=0;o<s;o++){const s=a?a[o]:1,l=s>1?0:o;!0===c?r.drawIndexed(i[o],s,e[o]/u.array.BYTES_PER_ELEMENT,0,l):r.draw(i[o],s,e[o],l),t.update(n,i[o],s)}}else if(!0===c){const{vertexCount:i,instanceCount:s,firstVertex:a}=h,o=e.getIndirect();if(null!==o){const e=this.get(o).buffer;r.drawIndexedIndirect(e,0)}else r.drawIndexed(i,s,a,0,0);t.update(n,i,s)}else{const{vertexCount:i,instanceCount:s,firstVertex:a}=h,o=e.getIndirect();if(null!==o){const e=this.get(o).buffer;r.drawIndirect(e,0)}else r.draw(i,s,a,0);t.update(n,i,s)}};if(e.camera.isArrayCamera&&e.camera.cameras.length>0){const t=this.get(e.camera),r=e.camera.cameras,s=e.getBindingGroup("cameraIndex");if(void 0===t.indexesGPU||t.indexesGPU.length!==r.length){const e=this.get(s),n=[],i=new Uint32Array([0,0,0,0]);for(let t=0,s=r.length;t<s;t++){i[0]=t;const r=this.bindingUtils.createBindGroupIndex(i,e.layout);n.push(r)}t.indexesGPU=n}const a=this.renderer.getPixelRatio();for(let e=0,l=r.length;e<l;e++){const l=r[e];if(n.layers.test(l.layers)){const n=l.viewport;let r=o.currentPass,u=o.currentSets;if(o.bundleEncoders){r=o.bundleEncoders[e],u=o.bundleSets[e]}n&&r.setViewport(Math.floor(n.x*a),Math.floor(n.y*a),Math.floor(n.width*a),Math.floor(n.height*a),i.viewportValue.minDepth,i.viewportValue.maxDepth),s&&t.indexesGPU&&(r.setBindGroup(s.index,t.indexesGPU[e]),u.bindingGroups[s.index]=s.id),p(r,u)}}}else if(o.currentPass){if(void 0!==o.occlusionQuerySet){const e=o.lastOcclusionObject;e!==n&&(null!==e&&!0===e.occlusionTest&&(o.currentPass.endOcclusionQuery(),o.occlusionQueryIndex++),!0===n.occlusionTest&&(o.currentPass.beginOcclusionQuery(o.occlusionQueryIndex),o.occlusionQueryObjects[o.occlusionQueryIndex]=n),o.lastOcclusionObject=n)}p(o.currentPass,o.currentSets)}}needsRenderUpdate(e){const t=this.get(e),{object:n,material:r}=e,i=this.utils,s=i.getSampleCountRenderContext(e.context),a=i.getCurrentColorSpace(e.context),o=i.getCurrentColorFormat(e.context),l=i.getCurrentDepthStencilFormat(e.context),u=i.getPrimitiveTopology(n,r);let c=!1;return t.material===r&&t.materialVersion===r.version&&t.transparent===r.transparent&&t.blending===r.blending&&t.premultipliedAlpha===r.premultipliedAlpha&&t.blendSrc===r.blendSrc&&t.blendDst===r.blendDst&&t.blendEquation===r.blendEquation&&t.blendSrcAlpha===r.blendSrcAlpha&&t.blendDstAlpha===r.blendDstAlpha&&t.blendEquationAlpha===r.blendEquationAlpha&&t.colorWrite===r.colorWrite&&t.depthWrite===r.depthWrite&&t.depthTest===r.depthTest&&t.depthFunc===r.depthFunc&&t.stencilWrite===r.stencilWrite&&t.stencilFunc===r.stencilFunc&&t.stencilFail===r.stencilFail&&t.stencilZFail===r.stencilZFail&&t.stencilZPass===r.stencilZPass&&t.stencilFuncMask===r.stencilFuncMask&&t.stencilWriteMask===r.stencilWriteMask&&t.side===r.side&&t.alphaToCoverage===r.alphaToCoverage&&t.sampleCount===s&&t.colorSpace===a&&t.colorFormat===o&&t.depthStencilFormat===l&&t.primitiveTopology===u&&t.clippingContextCacheKey===e.clippingContextCacheKey||(t.material=r,t.materialVersion=r.version,t.transparent=r.transparent,t.blending=r.blending,t.premultipliedAlpha=r.premultipliedAlpha,t.blendSrc=r.blendSrc,t.blendDst=r.blendDst,t.blendEquation=r.blendEquation,t.blendSrcAlpha=r.blendSrcAlpha,t.blendDstAlpha=r.blendDstAlpha,t.blendEquationAlpha=r.blendEquationAlpha,t.colorWrite=r.colorWrite,t.depthWrite=r.depthWrite,t.depthTest=r.depthTest,t.depthFunc=r.depthFunc,t.stencilWrite=r.stencilWrite,t.stencilFunc=r.stencilFunc,t.stencilFail=r.stencilFail,t.stencilZFail=r.stencilZFail,t.stencilZPass=r.stencilZPass,t.stencilFuncMask=r.stencilFuncMask,t.stencilWriteMask=r.stencilWriteMask,t.side=r.side,t.alphaToCoverage=r.alphaToCoverage,t.sampleCount=s,t.colorSpace=a,t.colorFormat=o,t.depthStencilFormat=l,t.primitiveTopology=u,t.clippingContextCacheKey=e.clippingContextCacheKey,c=!0),c}getRenderCacheKey(e){const{object:t,material:n}=e,r=this.utils,i=e.context;return[n.transparent,n.blending,n.premultipliedAlpha,n.blendSrc,n.blendDst,n.blendEquation,n.blendSrcAlpha,n.blendDstAlpha,n.blendEquationAlpha,n.colorWrite,n.depthWrite,n.depthTest,n.depthFunc,n.stencilWrite,n.stencilFunc,n.stencilFail,n.stencilZFail,n.stencilZPass,n.stencilFuncMask,n.stencilWriteMask,n.side,r.getSampleCountRenderContext(i),r.getCurrentColorSpace(i),r.getCurrentColorFormat(i),r.getCurrentDepthStencilFormat(i),r.getPrimitiveTopology(t,n),e.getGeometryCacheKey(),e.clippingContextCacheKey].join()}createSampler(e){this.textureUtils.createSampler(e)}destroySampler(e){this.textureUtils.destroySampler(e)}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){this.textureUtils.destroyTexture(e)}async copyTextureToBuffer(e,t,n,r,i,s){return this.textureUtils.copyTextureToBuffer(e,t,n,r,i,s)}initTimestampQuery(e,t){if(!this.trackTimestamp)return;const n=e.isComputeNode?"compute":"render";this.timestampQueryPool[n]||(this.timestampQueryPool[n]=new ZL(this.device,n,2048));const r=this.timestampQueryPool[n],i=r.allocateQueriesForContext(e);t.timestampWrites={querySet:r.querySet,beginningOfPassWriteIndex:i,endOfPassWriteIndex:i+1}}createNodeBuilder(e,t){return new jL(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 n=this.get(e),r=n.currentPass.finish();this.get(t).bundleGPU=r,n.currentSets=n._currentSets,n.currentPass=n._currentPass}addBundle(e,t){this.get(e).renderBundles.push(this.get(t).bundleGPU)}createBindings(e,t,n,r){this.bindingUtils.createBindings(e,t,n,r)}updateBindings(e,t,n,r){this.bindingUtils.createBindings(e,t,n,r)}updateBinding(e){this.bindingUtils.updateBinding(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.colorBuffer=this.textureUtils.getColorBuffer(),this.defaultRenderPassdescriptor=null}getMaxAnisotropy(){return 16}hasFeature(e){return this.device.features.has(e)}copyTextureToTexture(e,t,n=null,r=null,i=0,s=0){let a=0,o=0,l=0,u=0,c=0,h=0,d=e.image.width,p=e.image.height,f=1;null!==n&&(!0===n.isBox3?(u=n.min.x,c=n.min.y,h=n.min.z,d=n.max.x-n.min.x,p=n.max.y-n.min.y,f=n.max.z-n.min.z):(u=n.min.x,c=n.min.y,d=n.max.x-n.min.x,p=n.max.y-n.min.y,f=1)),null!==r&&(a=r.x,o=r.y,l=r.z||0);const m=this.device.createCommandEncoder({label:"copyTextureToTexture_"+e.id+"_"+t.id}),g=this.get(e).texture,_=this.get(t).texture;m.copyTextureToTexture({texture:g,mipLevel:i,origin:{x:u,y:c,z:h}},{texture:_,mipLevel:s,origin:{x:a,y:o,z:l}},[d,p,f]),this.device.queue.submit([m.finish()]),0===s&&t.generateMipmaps&&this.textureUtils.generateMipmaps(t)}copyFramebufferToTexture(e,t,n){const r=this.get(t);let i=null;i=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 s=this.get(e).texture;if(i.format!==s.format)return void console.error("WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.",i.format,s.format);let a;if(r.currentPass?(r.currentPass.end(),a=r.encoder):a=this.device.createCommandEncoder({label:"copyFramebufferToTexture_"+e.id}),a.copyTextureToTexture({texture:i,origin:[n.x,n.y,0]},{texture:s},[n.z,n.w]),r.currentPass){const{descriptor:e}=r;for(let t=0;t<e.colorAttachments.length;t++)e.colorAttachments[t].loadOp=MC;if(t.depth&&(e.depthStencilAttachment.depthLoadOp=MC),t.stencil&&(e.depthStencilAttachment.stencilLoadOp=MC),r.currentPass=a.beginRenderPass(e),r.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.viewport&&this.updateViewport(t),t.scissor){const{x:e,y:n,width:i,height:s}=t.scissorValue;r.currentPass.setScissorRect(e,n,i,s)}}else this.device.queue.submit([a.finish()]);e.generateMipmaps&&this.textureUtils.generateMipmaps(e)}}class eD extends Ks{constructor(e,t,n,r,i,s){super(e,t,n,r,i,s),this.iesMap=null}copy(e,t){return super.copy(e,t),this.iesMap=e.iesMap,this}}class tD extends Ks{constructor(e,t,n,r,i,s){super(e,t,n,r,i,s),this.aspect=null}copy(e,t){return super.copy(e,t),this.aspect=e.aspect,this}}class nD extends ZA{constructor(){super(),this.addMaterial(wT,"MeshPhongMaterial"),this.addMaterial(dM,"MeshStandardMaterial"),this.addMaterial(fM,"MeshPhysicalMaterial"),this.addMaterial(vM,"MeshToonMaterial"),this.addMaterial(gT,"MeshBasicMaterial"),this.addMaterial(ST,"MeshLambertMaterial"),this.addMaterial(rT,"MeshNormalMaterial"),this.addMaterial(bM,"MeshMatcapMaterial"),this.addMaterial(Jb,"LineBasicMaterial"),this.addMaterial(tT,"LineDashedMaterial"),this.addMaterial(AM,"PointsMaterial"),this.addMaterial(wM,"SpriteMaterial"),this.addMaterial(NM,"ShadowMaterial"),this.addLight(zE,ta),this.addLight(MA,ia),this.addLight(RA,aa),this.addLight(CA,Ks),this.addLight(DA,sa),this.addLight(IA,js),this.addLight(UA,la),this.addLight(NA,eD),this.addLight(LA,tD),this.addToneMapping(Bw,1),this.addToneMapping(kw,2),this.addToneMapping(zw,3),this.addToneMapping(Gw,4),this.addToneMapping(Xw,6),this.addToneMapping(qw,7)}}class rD extends yR{constructor(e={}){let t;e.forceWebGL?t=uC:(t=JL,e.getFallback=()=>(console.warn("THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new uC(e)));super(new t(e),e),this.library=new nD,this.isWebGPURenderer=!0,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}}const iD={type:"change"},sD={type:"start"},aD={type:"end"},oD=1e-6,lD=-1,uD=0,cD=1,hD=2,dD=3,pD=4,fD=new Dt,mD=new Dt,gD=new Ut,_D=new Ut,vD=new Ut,yD=new It,xD=new Ut,bD=new Ut,TD=new Ut,SD=new Ut;class MD extends va{constructor(e,t=null){super(e,t),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:a,MIDDLE:o,RIGHT:l},this.target=new Ut,this.state=lD,this.keyState=lD,this._lastPosition=new Ut,this._lastZoom=1,this._touchZoomDistanceStart=0,this._touchZoomDistanceEnd=0,this._lastAngle=0,this._eye=new Ut,this._movePrev=new Dt,this._moveCurr=new Dt,this._lastAxis=new Ut,this._zoomStart=new Dt,this._zoomEnd=new Dt,this._panStart=new Dt,this._panEnd=new Dt,this._pointers=[],this._pointerPositions={},this._onPointerMove=ED.bind(this),this._onPointerDown=wD.bind(this),this._onPointerUp=AD.bind(this),this._onPointerCancel=RD.bind(this),this._onContextMenu=UD.bind(this),this._onMouseWheel=ID.bind(this),this._onKeyDown=ND.bind(this),this._onKeyUp=CD.bind(this),this._onTouchStart=OD.bind(this),this._onTouchMove=FD.bind(this),this._onTouchEnd=BD.bind(this),this._onMouseDown=PD.bind(this),this._onMouseMove=LD.bind(this),this._onMouseUp=DD.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!==t&&(this.connect(t),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.removeEventListener("pointermove",this._onPointerMove),this.domElement.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="auto"}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)>oD&&(this.dispatchEvent(iD),this._lastPosition.copy(this.object.position))):this.object.isOrthographicCamera?(this.object.lookAt(this.target),(this._lastPosition.distanceToSquared(this.object.position)>oD||this._lastZoom!==this.object.zoom)&&(this.dispatchEvent(iD),this._lastPosition.copy(this.object.position),this._lastZoom=this.object.zoom)):console.warn("THREE.TrackballControls: Unsupported camera type.")}reset(){this.state=lD,this.keyState=lD,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(iD),this._lastPosition.copy(this.object.position),this._lastZoom=this.object.zoom}_panCamera(){if(mD.copy(this._panEnd).sub(this._panStart),mD.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;mD.x*=e,mD.y*=t}mD.multiplyScalar(this._eye.length()*this.panSpeed),_D.copy(this._eye).cross(this.object.up).setLength(mD.x),_D.add(gD.copy(this.object.up).setLength(mD.y)),this.object.position.add(_D),this.target.add(_D),this.staticMoving?this._panStart.copy(this._panEnd):this._panStart.add(mD.subVectors(this._panEnd,this._panStart).multiplyScalar(this.dynamicDampingFactor))}}_rotateCamera(){SD.set(this._moveCurr.x-this._movePrev.x,this._moveCurr.y-this._movePrev.y,0);let e=SD.length();e?(this._eye.copy(this.object.position).sub(this.target),xD.copy(this._eye).normalize(),bD.copy(this.object.up).normalize(),TD.crossVectors(bD,xD).normalize(),bD.setLength(this._moveCurr.y-this._movePrev.y),TD.setLength(this._moveCurr.x-this._movePrev.x),SD.copy(bD.add(TD)),vD.crossVectors(SD,this._eye).normalize(),e*=this.rotateSpeed,yD.setFromAxisAngle(vD,e),this._eye.applyQuaternion(yD),this.object.up.applyQuaternion(yD),this._lastAxis.copy(vD),this._lastAngle=e):!this.staticMoving&&this._lastAngle&&(this._lastAngle*=Math.sqrt(1-this.dynamicDampingFactor),this._eye.copy(this.object.position).sub(this.target),yD.setFromAxisAngle(this._lastAxis,this._lastAngle),this._eye.applyQuaternion(yD),this.object.up.applyQuaternion(yD)),this._movePrev.copy(this._moveCurr)}_zoomCamera(){let e;this.state===pD?(e=this._touchZoomDistanceStart/this._touchZoomDistanceEnd,this._touchZoomDistanceStart=this._touchZoomDistanceEnd,this.object.isPerspectiveCamera?this._eye.multiplyScalar(e):this.object.isOrthographicCamera?(this.object.zoom=Lt.clamp(this.object.zoom/e,this.minZoom,this.maxZoom),this._lastZoom!==this.object.zoom&&this.object.updateProjectionMatrix()):console.warn("THREE.TrackballControls: Unsupported camera type")):(e=1+(this._zoomEnd.y-this._zoomStart.y)*this.zoomSpeed,1!==e&&e>0&&(this.object.isPerspectiveCamera?this._eye.multiplyScalar(e):this.object.isOrthographicCamera?(this.object.zoom=Lt.clamp(this.object.zoom/e,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 fD.set((e-this.screen.left)/this.screen.width,(t-this.screen.top)/this.screen.height),fD}_getMouseOnCircle(e,t){return fD.set((e-.5*this.screen.width-this.screen.left)/(.5*this.screen.width),(this.screen.height+2*(this.screen.top-t))/this.screen.width),fD}_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(e){let t=this._pointerPositions[e.pointerId];void 0===t&&(t=new Dt,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.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 wD(e){!1!==this.enabled&&(0===this._pointers.length&&(this.domElement.setPointerCapture(e.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerup",this._onPointerUp)),this._addPointer(e),"touch"===e.pointerType?this._onTouchStart(e):this._onMouseDown(e))}function ED(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchMove(e):this._onMouseMove(e))}function AD(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.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp)))}function RD(e){this._removePointer(e)}function CD(){!1!==this.enabled&&(this.keyState=lD,window.addEventListener("keydown",this._onKeyDown))}function ND(e){!1!==this.enabled&&(window.removeEventListener("keydown",this._onKeyDown),this.keyState===lD&&(e.code!==this.keys[uD]||this.noRotate?e.code!==this.keys[cD]||this.noZoom?e.code!==this.keys[hD]||this.noPan||(this.keyState=hD):this.keyState=cD:this.keyState=uD))}function PD(e){let t;switch(e.button){case 0:t=this.mouseButtons.LEFT;break;case 1:t=this.mouseButtons.MIDDLE;break;case 2:t=this.mouseButtons.RIGHT;break;default:t=-1}switch(t){case o:this.state=cD;break;case a:this.state=uD;break;case l:this.state=hD;break;default:this.state=lD}const n=this.keyState!==lD?this.keyState:this.state;n!==uD||this.noRotate?n!==cD||this.noZoom?n!==hD||this.noPan||(this._panStart.copy(this._getMouseOnScreen(e.pageX,e.pageY)),this._panEnd.copy(this._panStart)):(this._zoomStart.copy(this._getMouseOnScreen(e.pageX,e.pageY)),this._zoomEnd.copy(this._zoomStart)):(this._moveCurr.copy(this._getMouseOnCircle(e.pageX,e.pageY)),this._movePrev.copy(this._moveCurr)),this.dispatchEvent(sD)}function LD(e){const t=this.keyState!==lD?this.keyState:this.state;t!==uD||this.noRotate?t!==cD||this.noZoom?t!==hD||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 DD(){this.state=lD,this.dispatchEvent(aD)}function ID(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(sD),this.dispatchEvent(aD)}}function UD(e){!1!==this.enabled&&e.preventDefault()}function OD(e){if(this._trackPointer(e),1===this._pointers.length)this.state=dD,this._moveCurr.copy(this._getMouseOnCircle(this._pointers[0].pageX,this._pointers[0].pageY)),this._movePrev.copy(this._moveCurr);else{this.state=pD;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 n=(this._pointers[0].pageX+this._pointers[1].pageX)/2,r=(this._pointers[0].pageY+this._pointers[1].pageY)/2;this._panStart.copy(this._getMouseOnScreen(n,r)),this._panEnd.copy(this._panStart)}this.dispatchEvent(sD)}function FD(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),n=e.pageX-t.x,r=e.pageY-t.y;this._touchZoomDistanceEnd=Math.sqrt(n*n+r*r);const i=(e.pageX+t.x)/2,s=(e.pageY+t.y)/2;this._panEnd.copy(this._getMouseOnScreen(i,s))}}function BD(e){switch(this._pointers.length){case 0:this.state=lD;break;case 1:this.state=dD,this._moveCurr.copy(this._getMouseOnCircle(e.pageX,e.pageY)),this._movePrev.copy(this._moveCurr);break;case 2:this.state=pD;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(aD)}const kD={type:"change"},zD={type:"start"},VD={type:"end"},GD=new Fn,HD=new Gi,jD=Math.cos(70*Lt.DEG2RAD),WD=new Ut,XD=2*Math.PI,qD=-1,$D=0,YD=1,KD=2,QD=3,ZD=4,JD=5,eI=6,tI=1e-6;class nI extends va{constructor(e,t=null){super(e,t),this.state=qD,this.target=new Ut,this.cursor=new Ut,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:a,MIDDLE:o,RIGHT:l},this.touches={ONE:u,TWO:h},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this._lastPosition=new Ut,this._lastQuaternion=new It,this._lastTargetPosition=new Ut,this._quat=(new It).setFromUnitVectors(e.up,new Ut(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new ga,this._sphericalDelta=new ga,this._scale=1,this._panOffset=new Ut,this._rotateStart=new Dt,this._rotateEnd=new Dt,this._rotateDelta=new Dt,this._panStart=new Dt,this._panEnd=new Dt,this._panDelta=new Dt,this._dollyStart=new Dt,this._dollyEnd=new Dt,this._dollyDelta=new Dt,this._dollyDirection=new Ut,this._mouse=new Dt,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=iI.bind(this),this._onPointerDown=rI.bind(this),this._onPointerUp=sI.bind(this),this._onContextMenu=dI.bind(this),this._onMouseWheel=lI.bind(this),this._onKeyDown=uI.bind(this),this._onTouchStart=cI.bind(this),this._onTouchMove=hI.bind(this),this._onMouseDown=aI.bind(this),this._onMouseMove=oI.bind(this),this._interceptControlDown=pI.bind(this),this._interceptControlUp=fI.bind(this),null!==this.domElement&&this.connect(this.domElement),this.update()}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.removeEventListener("pointermove",this._onPointerMove),this.domElement.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="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(kD),this.update(),this.state=qD}update(e=null){const t=this.object.position;WD.copy(t).sub(this.target),WD.applyQuaternion(this._quat),this._spherical.setFromVector3(WD),this.autoRotate&&this.state===qD&&this._rotateLeft(this._getAutoRotationAngle(e)),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 n=this.minAzimuthAngle,r=this.maxAzimuthAngle;isFinite(n)&&isFinite(r)&&(n<-Math.PI?n+=XD:n>Math.PI&&(n-=XD),r<-Math.PI?r+=XD:r>Math.PI&&(r-=XD),this._spherical.theta=n<=r?Math.max(n,Math.min(r,this._spherical.theta)):this._spherical.theta>(n+r)/2?Math.max(n,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 i=!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),i=e!=this._spherical.radius}if(WD.setFromSpherical(this._spherical),WD.applyQuaternion(this._quatInverse),t.copy(this.target).add(WD),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 e=null;if(this.object.isPerspectiveCamera){const t=WD.length();e=this._clampDistance(t*this._scale);const n=t-e;this.object.position.addScaledVector(this._dollyDirection,n),this.object.updateMatrixWorld(),i=!!n}else if(this.object.isOrthographicCamera){const t=new Ut(this._mouse.x,this._mouse.y,0);t.unproject(this.object);const n=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),i=n!==this.object.zoom;const r=new Ut(this._mouse.x,this._mouse.y,0);r.unproject(this.object),this.object.position.sub(r).add(t),this.object.updateMatrixWorld(),e=WD.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;null!==e&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(e).add(this.object.position):(GD.origin.copy(this.object.position),GD.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(GD.direction))<jD?this.object.lookAt(this.target):(HD.setFromNormalAndCoplanarPoint(this.object.up,this.target),GD.intersectPlane(HD,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(),i=!0)}return this._scale=1,this._performCursorZoom=!1,!!(i||this._lastPosition.distanceToSquared(this.object.position)>tI||8*(1-this._lastQuaternion.dot(this.object.quaternion))>tI||this._lastTargetPosition.distanceToSquared(this.target)>tI)&&(this.dispatchEvent(kD),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0)}_getAutoRotationAngle(e){return null!==e?XD/60*this.autoRotateSpeed*e:XD/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){WD.setFromMatrixColumn(t,0),WD.multiplyScalar(-e),this._panOffset.add(WD)}_panUp(e,t){!0===this.screenSpacePanning?WD.setFromMatrixColumn(t,1):(WD.setFromMatrixColumn(t,0),WD.crossVectors(this.object.up,WD)),WD.multiplyScalar(e),this._panOffset.add(WD)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const r=this.object.position;WD.copy(r).sub(this.target);let i=WD.length();i*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*i/n.clientHeight,this.object.matrix),this._panUp(2*t*i/n.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/n.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/n.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 n=this.domElement.getBoundingClientRect(),r=e-n.left,i=t-n.top,s=n.width,a=n.height;this._mouse.x=r/s*2-1,this._mouse.y=-i/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(XD*this._rotateDelta.x/t.clientHeight),this._rotateUp(XD*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(XD*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(-XD*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(XD*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(-XD*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),n=.5*(e.pageX+t.x),r=.5*(e.pageY+t.y);this._rotateStart.set(n,r)}}_handleTouchStartPan(e){if(1===this._pointers.length)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),r=.5*(e.pageY+t.y);this._panStart.set(n,r)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,r=e.pageY-t.y,i=Math.sqrt(n*n+r*r);this._dollyStart.set(0,i)}_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),n=.5*(e.pageX+t.x),r=.5*(e.pageY+t.y);this._rotateEnd.set(n,r)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(XD*this._rotateDelta.x/t.clientHeight),this._rotateUp(XD*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),n=.5*(e.pageX+t.x),r=.5*(e.pageY+t.y);this._panEnd.set(n,r)}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),n=e.pageX-t.x,r=e.pageY-t.y,i=Math.sqrt(n*n+r*r);this._dollyEnd.set(0,i),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 s=.5*(e.pageX+t.x),a=.5*(e.pageY+t.y);this._updateZoomParameters(s,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(e){let t=this._pointerPositions[e.pointerId];void 0===t&&(t=new Dt,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.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,n={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:n.deltaY*=16;break;case 2:n.deltaY*=100}return e.ctrlKey&&!this._controlActive&&(n.deltaY*=10),n}}function rI(e){!1!==this.enabled&&(0===this._pointers.length&&(this.domElement.setPointerCapture(e.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerup",this._onPointerUp)),this._isTrackingPointer(e)||(this._addPointer(e),"touch"===e.pointerType?this._onTouchStart(e):this._onMouseDown(e)))}function iI(e){!1!==this.enabled&&("touch"===e.pointerType?this._onTouchMove(e):this._onMouseMove(e))}function sI(e){switch(this._removePointer(e),this._pointers.length){case 0:this.domElement.releasePointerCapture(e.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(VD),this.state=qD;break;case 1:const t=this._pointers[0],n=this._pointerPositions[t];this._onTouchStart({pointerId:t,pageX:n.x,pageY:n.y})}}function aI(e){let t;switch(e.button){case 0:t=this.mouseButtons.LEFT;break;case 1:t=this.mouseButtons.MIDDLE;break;case 2:t=this.mouseButtons.RIGHT;break;default:t=-1}switch(t){case o:if(!1===this.enableZoom)return;this._handleMouseDownDolly(e),this.state=YD;break;case a:if(e.ctrlKey||e.metaKey||e.shiftKey){if(!1===this.enablePan)return;this._handleMouseDownPan(e),this.state=KD}else{if(!1===this.enableRotate)return;this._handleMouseDownRotate(e),this.state=$D}break;case l:if(e.ctrlKey||e.metaKey||e.shiftKey){if(!1===this.enableRotate)return;this._handleMouseDownRotate(e),this.state=$D}else{if(!1===this.enablePan)return;this._handleMouseDownPan(e),this.state=KD}break;default:this.state=qD}this.state!==qD&&this.dispatchEvent(zD)}function oI(e){switch(this.state){case $D:if(!1===this.enableRotate)return;this._handleMouseMoveRotate(e);break;case YD:if(!1===this.enableZoom)return;this._handleMouseMoveDolly(e);break;case KD:if(!1===this.enablePan)return;this._handleMouseMovePan(e)}}function lI(e){!1!==this.enabled&&!1!==this.enableZoom&&this.state===qD&&(e.preventDefault(),this.dispatchEvent(zD),this._handleMouseWheel(this._customWheelEvent(e)),this.dispatchEvent(VD))}function uI(e){!1!==this.enabled&&this._handleKeyDown(e)}function cI(e){switch(this._trackPointer(e),this._pointers.length){case 1:switch(this.touches.ONE){case u:if(!1===this.enableRotate)return;this._handleTouchStartRotate(e),this.state=QD;break;case c:if(!1===this.enablePan)return;this._handleTouchStartPan(e),this.state=ZD;break;default:this.state=qD}break;case 2:switch(this.touches.TWO){case h:if(!1===this.enableZoom&&!1===this.enablePan)return;this._handleTouchStartDollyPan(e),this.state=JD;break;case d:if(!1===this.enableZoom&&!1===this.enableRotate)return;this._handleTouchStartDollyRotate(e),this.state=eI;break;default:this.state=qD}break;default:this.state=qD}this.state!==qD&&this.dispatchEvent(zD)}function hI(e){switch(this._trackPointer(e),this.state){case QD:if(!1===this.enableRotate)return;this._handleTouchMoveRotate(e),this.update();break;case ZD:if(!1===this.enablePan)return;this._handleTouchMovePan(e),this.update();break;case JD:if(!1===this.enableZoom&&!1===this.enablePan)return;this._handleTouchMoveDollyPan(e),this.update();break;case eI:if(!1===this.enableZoom&&!1===this.enableRotate)return;this._handleTouchMoveDollyRotate(e),this.update();break;default:this.state=qD}}function dI(e){!1!==this.enabled&&e.preventDefault()}function pI(e){if("Control"===e.key){this._controlActive=!0;this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}}function fI(e){if("Control"===e.key){this._controlActive=!1;this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0})}}const mI={type:"change"},gI=1e-6,_I=new It;class vI extends va{constructor(e,t=null){super(e,t),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 Ut(0,0,0),this._rotationVector=new Ut(0,0,0),this._lastQuaternion=new It,this._lastPosition=new Ut,this._status=0,this._onKeyDown=yI.bind(this),this._onKeyUp=xI.bind(this),this._onPointerMove=TI.bind(this),this._onPointerDown=bI.bind(this),this._onPointerUp=SI.bind(this),this._onPointerCancel=MI.bind(this),this._onContextMenu=wI.bind(this),null!==t&&this.connect(t)}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)}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)}dispose(){this.disconnect()}update(e){if(!1===this.enabled)return;const t=this.object,n=e*this.movementSpeed,r=e*this.rollSpeed;t.translateX(this._moveVector.x*n),t.translateY(this._moveVector.y*n),t.translateZ(this._moveVector.z*n),_I.set(this._rotationVector.x*r,this._rotationVector.y*r,this._rotationVector.z*r,1).normalize(),t.quaternion.multiply(_I),(this._lastPosition.distanceToSquared(t.position)>gI||8*(1-this._lastQuaternion.dot(t.quaternion))>gI)&&(this.dispatchEvent(mI),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 yI(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 xI(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 bI(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 TI(e){if(!1!==this.enabled&&(!this.dragToLook||this._status>0)){const t=this._getContainerDimensions(),n=t.size[0]/2,r=t.size[1]/2;this._moveState.yawLeft=-(e.pageX-t.offset[0]-n)/n,this._moveState.pitchDown=(e.pageY-t.offset[1]-r)/r,this._updateRotationVector()}}function SI(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 MI(){!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 wI(e){!1!==this.enabled&&e.preventDefault()}const EI={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 AI{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 RI=new na(-1,1,1,-1,0,1);const CI=new class extends ei{constructor(){super(),this.setAttribute("position",new Xr([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new Xr([0,2,0,0,2,0],2))}};class NI{constructor(e){this._mesh=new di(CI,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,RI)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}class PI extends AI{constructor(e,t="tDiffuse"){super(),this.textureID=t,this.uniforms=null,this.material=null,e instanceof yi?(this.uniforms=e.uniforms,this.material=e):e&&(this.uniforms=vi.clone(e.uniforms),this.material=new yi({name:void 0!==e.name?e.name:"unspecified",defines:Object.assign({},e.defines),uniforms:this.uniforms,vertexShader:e.vertexShader,fragmentShader:e.fragmentShader})),this._fsQuad=new NI(this.material)}render(e,t,n){this.uniforms[this.textureID]&&(this.uniforms[this.textureID].value=n.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 LI extends AI{constructor(e,t){super(),this.scene=e,this.camera=t,this.clear=!0,this.needsSwap=!1,this.inverse=!1}render(e,t,n){const r=e.getContext(),i=e.state;let s,a;i.buffers.color.setMask(!1),i.buffers.depth.setMask(!1),i.buffers.color.setLocked(!0),i.buffers.depth.setLocked(!0),this.inverse?(s=0,a=1):(s=1,a=0),i.buffers.stencil.setTest(!0),i.buffers.stencil.setOp(r.REPLACE,r.REPLACE,r.REPLACE),i.buffers.stencil.setFunc(r.ALWAYS,s,4294967295),i.buffers.stencil.setClear(a),i.buffers.stencil.setLocked(!0),e.setRenderTarget(n),this.clear&&e.clear(),e.render(this.scene,this.camera),e.setRenderTarget(t),this.clear&&e.clear(),e.render(this.scene,this.camera),i.buffers.color.setLocked(!1),i.buffers.depth.setLocked(!1),i.buffers.color.setMask(!0),i.buffers.depth.setMask(!0),i.buffers.stencil.setLocked(!1),i.buffers.stencil.setFunc(r.EQUAL,1,4294967295),i.buffers.stencil.setOp(r.KEEP,r.KEEP,r.KEEP),i.buffers.stencil.setLocked(!0)}}class DI extends AI{constructor(){super(),this.needsSwap=!1}render(e){e.state.buffers.stencil.setLocked(!1),e.state.buffers.stencil.setTest(!1)}}class II{constructor(e,t){if(this.renderer=e,this._pixelRatio=e.getPixelRatio(),void 0===t){const n=e.getSize(new Dt);this._width=n.width,this._height=n.height,(t=new ln(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:ue})).texture.name="EffectComposer.rt1"}else this._width=t.width,this._height=t.height;this.renderTarget1=t,this.renderTarget2=t.clone(),this.renderTarget2.texture.name="EffectComposer.rt2",this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2,this.renderToScreen=!0,this.passes=[],this.copyPass=new PI(EI),this.copyPass.material.blending=0,this.clock=new ca}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){void 0===e&&(e=this.clock.getDelta());const t=this.renderer.getRenderTarget();let n=!1;for(let t=0,r=this.passes.length;t<r;t++){const r=this.passes[t];if(!1!==r.enabled){if(r.renderToScreen=this.renderToScreen&&this.isLastEnabledPass(t),r.render(this.renderer,this.writeBuffer,this.readBuffer,e,n),r.needsSwap){if(n){const t=this.renderer.getContext(),n=this.renderer.state.buffers.stencil;n.setFunc(t.NOTEQUAL,1,4294967295),this.copyPass.render(this.renderer,this.writeBuffer,this.readBuffer,e),n.setFunc(t.EQUAL,1,4294967295)}this.swapBuffers()}void 0!==LI&&(r instanceof LI?n=!0:r instanceof DI&&(n=!1))}}this.renderer.setRenderTarget(t)}reset(e){if(void 0===e){const t=this.renderer.getSize(new Dt);this._pixelRatio=this.renderer.getPixelRatio(),this._width=t.width,this._height=t.height,(e=this.renderTarget1.clone()).setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}this.renderTarget1.dispose(),this.renderTarget2.dispose(),this.renderTarget1=e,this.renderTarget2=e.clone(),this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2}setSize(e,t){this._width=e,this._height=t;const n=this._width*this._pixelRatio,r=this._height*this._pixelRatio;this.renderTarget1.setSize(n,r),this.renderTarget2.setSize(n,r);for(let e=0;e<this.passes.length;e++)this.passes[e].setSize(n,r)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget1.dispose(),this.renderTarget2.dispose(),this.copyPass.dispose()}}class UI extends AI{constructor(e,t,n=null,r=null,i=null){super(),this.scene=e,this.camera=t,this.overrideMaterial=n,this.clearColor=r,this.clearAlpha=i,this.clear=!0,this.clearDepth=!1,this.needsSwap=!1,this._oldClearColor=new Nr}render(e,t,n){const r=e.autoClear;let i,s;e.autoClear=!1,null!==this.overrideMaterial&&(s=this.scene.overrideMaterial,this.scene.overrideMaterial=this.overrideMaterial),null!==this.clearColor&&(e.getClearColor(this._oldClearColor),e.setClearColor(this.clearColor,e.getClearAlpha())),null!==this.clearAlpha&&(i=e.getClearAlpha(),e.setClearAlpha(this.clearAlpha)),1==this.clearDepth&&e.clearDepth(),e.setRenderTarget(this.renderToScreen?null:n),!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(i),null!==this.overrideMaterial&&(this.scene.overrideMaterial=s),e.autoClear=r}}function OI(){return OI=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},OI.apply(null,arguments)}function FI(e,t){return FI=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},FI(e,t)}function BI(e){return BI=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},BI(e)}function kI(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(kI=function(){return!!e})()}function zI(e){var t="function"==typeof Map?new Map:void 0;return zI=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,n)}function n(){return function(e,t,n){if(kI())return Reflect.construct.apply(null,arguments);var r=[null];r.push.apply(r,t);var i=new(e.bind.apply(e,r));return n&&FI(i,n.prototype),i}(e,arguments,BI(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),FI(n,e)},zI(e)}var VI={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 GI(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];var r,i=t[0],s=[];for(r=1;r<t.length;r+=1)s.push(t[r]);return s.forEach(function(e){i=i.replace(/%[a-z]/,e)}),i}var HI=function(e){function t(t){var n;if("production"===process.env.NODE_ENV)n=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 r=arguments.length,i=new Array(r>1?r-1:0),s=1;s<r;s++)i[s-1]=arguments[s];n=e.call(this,GI.apply(void 0,[VI[t]].concat(i)))||this}return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(n)}return function(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,FI(e,t)}(t,e),t}(zI(Error));function jI(e){return Math.round(255*e)}function WI(e,t,n){return jI(e)+","+jI(t)+","+jI(n)}function XI(e,t,n,r){if(void 0===r&&(r=WI),0===t)return r(n,n,n);var i=(e%360+360)%360/60,s=(1-Math.abs(2*n-1))*t,a=s*(1-Math.abs(i%2-1)),o=0,l=0,u=0;i>=0&&i<1?(o=s,l=a):i>=1&&i<2?(o=a,l=s):i>=2&&i<3?(l=s,u=a):i>=3&&i<4?(l=a,u=s):i>=4&&i<5?(o=a,u=s):i>=5&&i<6&&(o=s,u=a);var c=n-s/2;return r(o+c,l+c,u+c)}var qI={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 $I=/^#[a-fA-F0-9]{6}$/,YI=/^#[a-fA-F0-9]{8}$/,KI=/^#[a-fA-F0-9]{3}$/,QI=/^#[a-fA-F0-9]{4}$/,ZI=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,JI=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,eU=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,tU=/^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 nU(e){if("string"!=typeof e)throw new HI(3);var t=function(e){if("string"!=typeof e)return e;var t=e.toLowerCase();return qI[t]?"#"+qI[t]:e}(e);if(t.match($I))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(YI)){var n=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:n}}if(t.match(KI))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(QI)){var r=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:r}}var i=ZI.exec(t);if(i)return{red:parseInt(""+i[1],10),green:parseInt(""+i[2],10),blue:parseInt(""+i[3],10)};var s=JI.exec(t.substring(0,50));if(s)return{red:parseInt(""+s[1],10),green:parseInt(""+s[2],10),blue:parseInt(""+s[3],10),alpha:parseFloat(""+s[4])>1?parseFloat(""+s[4])/100:parseFloat(""+s[4])};var a=eU.exec(t);if(a){var o="rgb("+XI(parseInt(""+a[1],10),parseInt(""+a[2],10)/100,parseInt(""+a[3],10)/100)+")",l=ZI.exec(o);if(!l)throw new HI(4,t,o);return{red:parseInt(""+l[1],10),green:parseInt(""+l[2],10),blue:parseInt(""+l[3],10)}}var u=tU.exec(t.substring(0,50));if(u){var c="rgb("+XI(parseInt(""+u[1],10),parseInt(""+u[2],10)/100,parseInt(""+u[3],10)/100)+")",h=ZI.exec(c);if(!h)throw new HI(4,t,c);return{red:parseInt(""+h[1],10),green:parseInt(""+h[2],10),blue:parseInt(""+h[3],10),alpha:parseFloat(""+u[4])>1?parseFloat(""+u[4])/100:parseFloat(""+u[4])}}throw new HI(5)}function rU(e){return function(e){var t,n=e.red/255,r=e.green/255,i=e.blue/255,s=Math.max(n,r,i),a=Math.min(n,r,i),o=(s+a)/2;if(s===a)return void 0!==e.alpha?{hue:0,saturation:0,lightness:o,alpha:e.alpha}:{hue:0,saturation:0,lightness:o};var l=s-a,u=o>.5?l/(2-s-a):l/(s+a);switch(s){case n:t=(r-i)/l+(r<i?6:0);break;case r:t=(i-n)/l+2;break;default:t=(n-r)/l+4}return t*=60,void 0!==e.alpha?{hue:t,saturation:u,lightness:o,alpha:e.alpha}:{hue:t,saturation:u,lightness:o}}(nU(e))}var iU=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 sU(e){var t=e.toString(16);return 1===t.length?"0"+t:t}function aU(e){return sU(Math.round(255*e))}function oU(e,t,n){return iU("#"+aU(e)+aU(t)+aU(n))}function lU(e,t,n){return XI(e,t,n,oU)}function uU(e,t,n){if("number"==typeof e&&"number"==typeof t&&"number"==typeof n)return iU("#"+sU(e)+sU(t)+sU(n));if("object"==typeof e&&void 0===t&&void 0===n)return iU("#"+sU(e.red)+sU(e.green)+sU(e.blue));throw new HI(6)}function cU(e,t,n,r){if("object"==typeof e&&void 0===t&&void 0===n&&void 0===r)return e.alpha>=1?uU(e.red,e.green,e.blue):"rgba("+e.red+","+e.green+","+e.blue+","+e.alpha+")";throw new HI(7)}function hU(e){if("object"!=typeof e)throw new HI(8);if(function(e){return"number"==typeof e.red&&"number"==typeof e.green&&"number"==typeof e.blue&&"number"==typeof e.alpha}(e))return cU(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 uU(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,n,r){if("object"==typeof e&&void 0===t&&void 0===n&&void 0===r)return e.alpha>=1?lU(e.hue,e.saturation,e.lightness):"rgba("+XI(e.hue,e.saturation,e.lightness)+","+e.alpha+")";throw new HI(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,n){if("object"==typeof e&&void 0===t&&void 0===n)return lU(e.hue,e.saturation,e.lightness);throw new HI(1)}(e);throw new HI(8)}function dU(e,t,n){return function(){var r=n.concat(Array.prototype.slice.call(arguments));return r.length>=t?e.apply(this,r):dU(e,t,r)}}function pU(e){return dU(e,e.length,[])}function fU(e,t,n){return Math.max(e,Math.min(t,n))}pU(function(e,t){if("transparent"===t)return t;var n=rU(t);return hU(OI({},n,{hue:n.hue+parseFloat(e)}))}),pU(function(e,t){if("transparent"===t)return t;var n=rU(t);return hU(OI({},n,{lightness:fU(0,1,n.lightness-parseFloat(e))}))}),pU(function(e,t){if("transparent"===t)return t;var n=rU(t);return hU(OI({},n,{saturation:fU(0,1,n.saturation-parseFloat(e))}))}),pU(function(e,t){if("transparent"===t)return t;var n=rU(t);return hU(OI({},n,{lightness:fU(0,1,n.lightness+parseFloat(e))}))});var mU=pU(function(e,t,n){if("transparent"===t)return n;if("transparent"===n)return t;if(0===e)return n;var r=nU(t),i=OI({},r,{alpha:"number"==typeof r.alpha?r.alpha:1}),s=nU(n),a=OI({},s,{alpha:"number"==typeof s.alpha?s.alpha:1}),o=i.alpha-a.alpha,l=2*parseFloat(e)-1,u=((l*o===-1?l:l+o)/(1+l*o)+1)/2,c=1-u;return cU({red:Math.floor(i.red*u+a.red*c),green:Math.floor(i.green*u+a.green*c),blue:Math.floor(i.blue*u+a.blue*c),alpha:i.alpha*parseFloat(e)+a.alpha*(1-parseFloat(e))})}),gU=mU;var _U=pU(function(e,t){if("transparent"===t)return t;var n=nU(t);return cU(OI({},n,{alpha:fU(0,1,(100*("number"==typeof n.alpha?n.alpha:1)+100*parseFloat(e))/100)}))}),vU=_U;pU(function(e,t){if("transparent"===t)return t;var n=rU(t);return hU(OI({},n,{saturation:fU(0,1,n.saturation+parseFloat(e))}))}),pU(function(e,t){return"transparent"===t?t:hU(OI({},rU(t),{hue:parseFloat(e)}))}),pU(function(e,t){return"transparent"===t?t:hU(OI({},rU(t),{lightness:parseFloat(e)}))}),pU(function(e,t){return"transparent"===t?t:hU(OI({},rU(t),{saturation:parseFloat(e)}))}),pU(function(e,t){return"transparent"===t?t:gU(parseFloat(e),"rgb(0, 0, 0)",t)}),pU(function(e,t){return"transparent"===t?t:gU(parseFloat(e),"rgb(255, 255, 255)",t)}),pU(function(e,t){if("transparent"===t)return t;var n=nU(t);return cU(OI({},n,{alpha:fU(0,1,+(100*("number"==typeof n.alpha?n.alpha:1)-100*parseFloat(e)).toFixed(2)/100)}))});var yU=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-yU.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*yU.Bounce.In(2*e):.5*yU.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}}}}),xU=function(){return performance.now()},bU=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=[],n=0;n<arguments.length;n++)t[n]=arguments[n];for(var r=0,i=t;r<i.length;r++){var s=i[r];null===(e=s._group)||void 0===e||e.remove(s),s._group=this,this._tweens[s.getId()]=s,this._tweensAddedDuringUpdate[s.getId()]=s}},e.prototype.remove=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];for(var n=0,r=e;n<r.length;n++){var i=r[n];i._group=void 0,delete this._tweens[i.getId()],delete this._tweensAddedDuringUpdate[i.getId()]}},e.prototype.allStopped=function(){return this.getAll().every(function(e){return!e.isPlaying()})},e.prototype.update=function(e,t){void 0===e&&(e=xU()),void 0===t&&(t=!0);var n=Object.keys(this._tweens);if(0!==n.length)for(;n.length>0;){this._tweensAddedDuringUpdate={};for(var r=0;r<n.length;r++){var i=this._tweens[n[r]],s=!t;i&&!1===i.update(e,s)&&!t&&this.remove(i)}n=Object.keys(this._tweensAddedDuringUpdate)}},e}(),TU={Linear:function(e,t){var n=e.length-1,r=n*t,i=Math.floor(r),s=TU.Utils.Linear;return t<0?s(e[0],e[1],r):t>1?s(e[n],e[n-1],n-r):s(e[i],e[i+1>n?n:i+1],r-i)},Utils:{Linear:function(e,t,n){return(t-e)*n+e}}},SU=function(){function e(){}return e.nextId=function(){return e._nextId++},e._nextId=0,e}(),MU=new bU,wU=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=yU.Linear.None,this._interpolationFunction=TU.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=SU.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=MU,MU.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=xU()),void 0===t&&(t=!1),this._isPlaying)return this;if(this._repeat=this._initialRepeat,this._reversed)for(var n in this._reversed=!1,this._valuesStartRepeat)this._swapEndStartRepeatValues(n),this._valuesStart[n]=this._valuesStartRepeat[n];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 r={};for(var i in this._valuesEnd)r[i]=this._valuesEnd[i];this._valuesEnd=r}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,n,r,i){for(var s in n){var a=e[s],o=Array.isArray(a),l=o?"array":typeof a,u=!o&&Array.isArray(n[s]);if("undefined"!==l&&"function"!==l){if(u){if(0===(g=n[s]).length)continue;for(var c=[a],h=0,d=g.length;h<d;h+=1){var p=this._handleRelativeValue(a,g[h]);if(isNaN(p)){u=!1,console.warn("Found invalid interpolation list. Skipping.");break}c.push(p)}u&&(n[s]=c)}if("object"!==l&&!o||!a||u)(void 0===t[s]||i)&&(t[s]=a),o||(t[s]*=1),r[s]=u?n[s].slice().reverse():t[s]||0;else{t[s]=o?[]:{};var f=a;for(var m in f)t[s][m]=f[m];r[s]=o?[]:{};var g=n[s];if(!this._isDynamic){var _={};for(var m in g)_[m]=g[m];n[s]=g=_}this._setupProperties(f,t[s],g,r[s],i)}}}},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=xU()),this._isPaused||!this._isPlaying||(this._isPaused=!0,this._pauseStart=e),this},e.prototype.resume=function(e){return void 0===e&&(e=xU()),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=yU.Linear.None),this._easingFunction=e,this},e.prototype.interpolation=function(e){return void 0===e&&(e=TU.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,n){var r,i,s=this;if(void 0===t&&(t=xU()),void 0===n&&(n=e.autoStartOnUpdate),this._isPaused)return!0;if(!this._goToEnd&&!this._isPlaying){if(!n)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!==(r=this._repeatDelayTime)&&void 0!==r?r:this._delayTime),l=this._duration+this._repeat*o,u=function(){if(0===s._duration)return 1;if(a>l)return 1;var e=Math.trunc(a/o),t=a-e*o,n=Math.min(t/s._duration,1);return 0===n&&a===s._duration?1:n}(),c=this._easingFunction(u);if(this._updateProperties(this._object,this._valuesStart,this._valuesEnd,c),this._onUpdateCallback&&this._onUpdateCallback(this._object,u),0===this._duration||a>=this._duration){if(this._repeat>0){var h=Math.min(Math.trunc((a-this._duration)/o)+1,this._repeat);for(i in isFinite(this._repeat)&&(this._repeat-=h),this._valuesStartRepeat)this._yoyo||"string"!=typeof this._valuesEnd[i]||(this._valuesStartRepeat[i]=this._valuesStartRepeat[i]+parseFloat(this._valuesEnd[i])),this._yoyo&&this._swapEndStartRepeatValues(i),this._valuesStart[i]=this._valuesStartRepeat[i];return this._yoyo&&(this._reversed=!this._reversed),this._startTime+=o*h,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,n,r){for(var i in n)if(void 0!==t[i]){var s=t[i]||0,a=n[i],o=Array.isArray(e[i]),l=Array.isArray(a);!o&&l?e[i]=this._interpolationFunction(a,r):"object"==typeof a&&a?this._updateProperties(e[i],s,a,r):"number"==typeof(a=this._handleRelativeValue(s,a))&&(e[i]=s+(a-s)*r)}},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],n=this._valuesEnd[e];this._valuesStartRepeat[e]="string"==typeof n?this._valuesStartRepeat[e]+parseFloat(n):this._valuesEnd[e],this._valuesEnd[e]=t},e.autoStartOnUpdate=!1,e}();SU.nextId;var EU=MU;EU.getAll.bind(EU),EU.removeAll.bind(EU),EU.add.bind(EU),EU.remove.bind(EU),EU.update.bind(EU);var AU="http://www.w3.org/1999/xhtml",RU={svg:"http://www.w3.org/2000/svg",xhtml:AU,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function CU(e){var t=e+="",n=t.indexOf(":");return n>=0&&"xmlns"!==(t=e.slice(0,n))&&(e=e.slice(n+1)),RU.hasOwnProperty(t)?{space:RU[t],local:e}:e}function NU(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===AU&&t.documentElement.namespaceURI===AU?t.createElement(e):t.createElementNS(n,e)}}function PU(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function LU(e){var t=CU(e);return(t.local?PU:NU)(t)}function DU(){}function IU(e){return null==e?DU:function(){return this.querySelector(e)}}function UU(){return[]}function OU(e){return function(){return function(e){return null==e?[]:Array.isArray(e)?e:Array.from(e)}(e.apply(this,arguments))}}function FU(e){return function(t){return t.matches(e)}}var BU=Array.prototype.find;function kU(){return this.firstElementChild}var zU=Array.prototype.filter;function VU(){return Array.from(this.children)}function GU(e){return new Array(e.length)}function HU(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}function jU(e,t,n,r,i,s){for(var a,o=0,l=t.length,u=s.length;o<u;++o)(a=t[o])?(a.__data__=s[o],r[o]=a):n[o]=new HU(e,s[o]);for(;o<l;++o)(a=t[o])&&(i[o]=a)}function WU(e,t,n,r,i,s,a){var o,l,u,c=new Map,h=t.length,d=s.length,p=new Array(h);for(o=0;o<h;++o)(l=t[o])&&(p[o]=u=a.call(l,l.__data__,o,t)+"",c.has(u)?i[o]=l:c.set(u,l));for(o=0;o<d;++o)u=a.call(e,s[o],o,s)+"",(l=c.get(u))?(r[o]=l,l.__data__=s[o],c.delete(u)):n[o]=new HU(e,s[o]);for(o=0;o<h;++o)(l=t[o])&&c.get(p[o])===l&&(i[o]=l)}function XU(e){return e.__data__}function qU(e){return"object"==typeof e&&"length"in e?e:Array.from(e)}function $U(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function YU(e){return function(){this.removeAttribute(e)}}function KU(e){return function(){this.removeAttributeNS(e.space,e.local)}}function QU(e,t){return function(){this.setAttribute(e,t)}}function ZU(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function JU(e,t){return function(){var n=t.apply(this,arguments);null==n?this.removeAttribute(e):this.setAttribute(e,n)}}function eO(e,t){return function(){var n=t.apply(this,arguments);null==n?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,n)}}function tO(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function nO(e){return function(){this.style.removeProperty(e)}}function rO(e,t,n){return function(){this.style.setProperty(e,t,n)}}function iO(e,t,n){return function(){var r=t.apply(this,arguments);null==r?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function sO(e){return function(){delete this[e]}}function aO(e,t){return function(){this[e]=t}}function oO(e,t){return function(){var n=t.apply(this,arguments);null==n?delete this[e]:this[e]=n}}function lO(e){return e.trim().split(/^|\s+/)}function uO(e){return e.classList||new cO(e)}function cO(e){this._node=e,this._names=lO(e.getAttribute("class")||"")}function hO(e,t){for(var n=uO(e),r=-1,i=t.length;++r<i;)n.add(t[r])}function dO(e,t){for(var n=uO(e),r=-1,i=t.length;++r<i;)n.remove(t[r])}function pO(e){return function(){hO(this,e)}}function fO(e){return function(){dO(this,e)}}function mO(e,t){return function(){(t.apply(this,arguments)?hO:dO)(this,e)}}function gO(){this.textContent=""}function _O(e){return function(){this.textContent=e}}function vO(e){return function(){var t=e.apply(this,arguments);this.textContent=null==t?"":t}}function yO(){this.innerHTML=""}function xO(e){return function(){this.innerHTML=e}}function bO(e){return function(){var t=e.apply(this,arguments);this.innerHTML=null==t?"":t}}function TO(){this.nextSibling&&this.parentNode.appendChild(this)}function SO(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function MO(){return null}function wO(){var e=this.parentNode;e&&e.removeChild(this)}function EO(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function AO(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function RO(e){return function(){var t=this.__on;if(t){for(var n,r=0,i=-1,s=t.length;r<s;++r)n=t[r],e.type&&n.type!==e.type||n.name!==e.name?t[++i]=n:this.removeEventListener(n.type,n.listener,n.options);++i?t.length=i:delete this.__on}}}function CO(e,t,n){return function(){var r,i=this.__on,s=function(e){return function(t){e.call(this,t,this.__data__)}}(t);if(i)for(var a=0,o=i.length;a<o;++a)if((r=i[a]).type===e.type&&r.name===e.name)return this.removeEventListener(r.type,r.listener,r.options),this.addEventListener(r.type,r.listener=s,r.options=n),void(r.value=t);this.addEventListener(e.type,s,n),r={type:e.type,name:e.name,value:t,listener:s,options:n},i?i.push(r):this.__on=[r]}}function NO(e,t,n){var r=tO(e),i=r.CustomEvent;"function"==typeof i?i=new i(t,n):(i=r.document.createEvent("Event"),n?(i.initEvent(t,n.bubbles,n.cancelable),i.detail=n.detail):i.initEvent(t,!1,!1)),e.dispatchEvent(i)}function PO(e,t){return function(){return NO(this,e,t)}}function LO(e,t){return function(){return NO(this,e,t.apply(this,arguments))}}HU.prototype={constructor:HU,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)}},cO.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 DO=[null];function IO(e,t){this._groups=e,this._parents=t}IO.prototype={constructor:IO,select:function(e){"function"!=typeof e&&(e=IU(e));for(var t=this._groups,n=t.length,r=new Array(n),i=0;i<n;++i)for(var s,a,o=t[i],l=o.length,u=r[i]=new Array(l),c=0;c<l;++c)(s=o[c])&&(a=e.call(s,s.__data__,c,o))&&("__data__"in s&&(a.__data__=s.__data__),u[c]=a);return new IO(r,this._parents)},selectAll:function(e){e="function"==typeof e?OU(e):function(e){return null==e?UU:function(){return this.querySelectorAll(e)}}(e);for(var t=this._groups,n=t.length,r=[],i=[],s=0;s<n;++s)for(var a,o=t[s],l=o.length,u=0;u<l;++u)(a=o[u])&&(r.push(e.call(a,a.__data__,u,o)),i.push(a));return new IO(r,i)},selectChild:function(e){return this.select(null==e?kU:function(e){return function(){return BU.call(this.children,e)}}("function"==typeof e?e:FU(e)))},selectChildren:function(e){return this.selectAll(null==e?VU:function(e){return function(){return zU.call(this.children,e)}}("function"==typeof e?e:FU(e)))},filter:function(e){"function"!=typeof e&&(e=function(e){return function(){return this.matches(e)}}(e));for(var t=this._groups,n=t.length,r=new Array(n),i=0;i<n;++i)for(var s,a=t[i],o=a.length,l=r[i]=[],u=0;u<o;++u)(s=a[u])&&e.call(s,s.__data__,u,a)&&l.push(s);return new IO(r,this._parents)},data:function(e,t){if(!arguments.length)return Array.from(this,XU);var n=t?WU:jU,r=this._parents,i=this._groups;"function"!=typeof e&&(e=function(e){return function(){return e}}(e));for(var s=i.length,a=new Array(s),o=new Array(s),l=new Array(s),u=0;u<s;++u){var c=r[u],h=i[u],d=h.length,p=qU(e.call(c,c&&c.__data__,u,r)),f=p.length,m=o[u]=new Array(f),g=a[u]=new Array(f);n(c,h,m,g,l[u]=new Array(d),p,t);for(var _,v,y=0,x=0;y<f;++y)if(_=m[y]){for(y>=x&&(x=y+1);!(v=g[x])&&++x<f;);_._next=v||null}}return(a=new IO(a,r))._enter=o,a._exit=l,a},enter:function(){return new IO(this._enter||this._groups.map(GU),this._parents)},exit:function(){return new IO(this._exit||this._groups.map(GU),this._parents)},join:function(e,t,n){var r=this.enter(),i=this,s=this.exit();return"function"==typeof e?(r=e(r))&&(r=r.selection()):r=r.append(e+""),null!=t&&(i=t(i))&&(i=i.selection()),null==n?s.remove():n(s),r&&i?r.merge(i).order():i},merge:function(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,i=n.length,s=r.length,a=Math.min(i,s),o=new Array(i),l=0;l<a;++l)for(var u,c=n[l],h=r[l],d=c.length,p=o[l]=new Array(d),f=0;f<d;++f)(u=c[f]||h[f])&&(p[f]=u);for(;l<i;++l)o[l]=n[l];return new IO(o,this._parents)},selection:function(){return this},order:function(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r,i=e[t],s=i.length-1,a=i[s];--s>=0;)(r=i[s])&&(a&&4^r.compareDocumentPosition(a)&&a.parentNode.insertBefore(r,a),a=r);return this},sort:function(e){function t(t,n){return t&&n?e(t.__data__,n.__data__):!t-!n}e||(e=$U);for(var n=this._groups,r=n.length,i=new Array(r),s=0;s<r;++s){for(var a,o=n[s],l=o.length,u=i[s]=new Array(l),c=0;c<l;++c)(a=o[c])&&(u[c]=a);u.sort(t)}return new IO(i,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,n=e.length;t<n;++t)for(var r=e[t],i=0,s=r.length;i<s;++i){var a=r[i];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,n=0,r=t.length;n<r;++n)for(var i,s=t[n],a=0,o=s.length;a<o;++a)(i=s[a])&&e.call(i,i.__data__,a,s);return this},attr:function(e,t){var n=CU(e);if(arguments.length<2){var r=this.node();return n.local?r.getAttributeNS(n.space,n.local):r.getAttribute(n)}return this.each((null==t?n.local?KU:YU:"function"==typeof t?n.local?eO:JU:n.local?ZU:QU)(n,t))},style:function(e,t,n){return arguments.length>1?this.each((null==t?nO:"function"==typeof t?iO:rO)(e,t,null==n?"":n)):function(e,t){return e.style.getPropertyValue(t)||tO(e).getComputedStyle(e,null).getPropertyValue(t)}(this.node(),e)},property:function(e,t){return arguments.length>1?this.each((null==t?sO:"function"==typeof t?oO:aO)(e,t)):this.node()[e]},classed:function(e,t){var n=lO(e+"");if(arguments.length<2){for(var r=uO(this.node()),i=-1,s=n.length;++i<s;)if(!r.contains(n[i]))return!1;return!0}return this.each(("function"==typeof t?mO:t?pO:fO)(n,t))},text:function(e){return arguments.length?this.each(null==e?gO:("function"==typeof e?vO:_O)(e)):this.node().textContent},html:function(e){return arguments.length?this.each(null==e?yO:("function"==typeof e?bO:xO)(e)):this.node().innerHTML},raise:function(){return this.each(TO)},lower:function(){return this.each(SO)},append:function(e){var t="function"==typeof e?e:LU(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})},insert:function(e,t){var n="function"==typeof e?e:LU(e),r=null==t?MO:"function"==typeof t?t:IU(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})},remove:function(){return this.each(wO)},clone:function(e){return this.select(e?AO:EO)},datum:function(e){return arguments.length?this.property("__data__",e):this.node().__data__},on:function(e,t,n){var r,i,s=function(e){return e.trim().split(/^|\s+/).map(function(e){var t="",n=e.indexOf(".");return n>=0&&(t=e.slice(n+1),e=e.slice(0,n)),{type:e,name:t}})}(e+""),a=s.length;if(!(arguments.length<2)){for(o=t?CO:RO,r=0;r<a;++r)this.each(o(s[r],t,n));return this}var o=this.node().__on;if(o)for(var l,u=0,c=o.length;u<c;++u)for(r=0,l=o[u];r<a;++r)if((i=s[r]).type===l.type&&i.name===l.name)return l.value},dispatch:function(e,t){return this.each(("function"==typeof t?LO:PO)(e,t))},[Symbol.iterator]:function*(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r,i=e[t],s=0,a=i.length;s<a;++s)(r=i[s])&&(yield r)}};var UO,OO,FO,BO,kO,zO,VO,GO,HO,jO,WO,XO,qO={},$O=[],YO=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,KO=Array.isArray;function QO(e,t){for(var n in t)e[n]=t[n];return e}function ZO(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function JO(e,t,n,r,i){var s={type:e,props:t,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:null==i?++FO:i,__i:-1,__u:0};return null==i&&null!=OO.vnode&&OO.vnode(s),s}function eF(e){return e.children}function tF(e,t){this.props=e,this.context=t}function nF(e,t){if(null==t)return e.__?nF(e.__,e.__i+1):null;for(var n;t<e.__k.length;t++)if(null!=(n=e.__k[t])&&null!=n.__e)return n.__e;return"function"==typeof e.type?nF(e):null}function rF(e){var t,n;if(null!=(e=e.__)&&null!=e.__c){for(e.__e=e.__c.base=null,t=0;t<e.__k.length;t++)if(null!=(n=e.__k[t])&&null!=n.__e){e.__e=e.__c.base=n.__e;break}return rF(e)}}function iF(e){(!e.__d&&(e.__d=!0)&&kO.push(e)&&!sF.__r++||zO!=OO.debounceRendering)&&((zO=OO.debounceRendering)||VO)(sF)}function sF(){for(var e,t,n,r,i,s,a,o=1;kO.length;)kO.length>o&&kO.sort(GO),e=kO.shift(),o=kO.length,e.__d&&(n=void 0,i=(r=(t=e).__v).__e,s=[],a=[],t.__P&&((n=QO({},r)).__v=r.__v+1,OO.vnode&&OO.vnode(n),pF(t.__P,n,r,t.__n,t.__P.namespaceURI,32&r.__u?[i]:null,s,null==i?nF(r):i,!!(32&r.__u),a),n.__v=r.__v,n.__.__k[n.__i]=n,fF(s,n,a),n.__e!=i&&rF(n)));sF.__r=0}function aF(e,t,n,r,i,s,a,o,l,u,c){var h,d,p,f,m,g,_=r&&r.__k||$O,v=t.length;for(l=oF(n,t,_,l,v),h=0;h<v;h++)null!=(p=n.__k[h])&&(d=-1==p.__i?qO:_[p.__i]||qO,p.__i=h,g=pF(e,p,d,i,s,a,o,l,u,c),f=p.__e,p.ref&&d.ref!=p.ref&&(d.ref&&_F(d.ref,null,p),c.push(p.ref,p.__c||f,p)),null==m&&null!=f&&(m=f),4&p.__u||d.__k===p.__k?l=lF(p,l,e):"function"==typeof p.type&&void 0!==g?l=g:f&&(l=f.nextSibling),p.__u&=-7);return n.__e=m,l}function oF(e,t,n,r,i){var s,a,o,l,u,c=n.length,h=c,d=0;for(e.__k=new Array(i),s=0;s<i;s++)null!=(a=t[s])&&"boolean"!=typeof a&&"function"!=typeof a?(l=s+d,(a=e.__k[s]="string"==typeof a||"number"==typeof a||"bigint"==typeof a||a.constructor==String?JO(null,a,null,null,null):KO(a)?JO(eF,{children:a},null,null,null):null==a.constructor&&a.__b>0?JO(a.type,a.props,a.key,a.ref?a.ref:null,a.__v):a).__=e,a.__b=e.__b+1,o=null,-1!=(u=a.__i=uF(a,n,l,h))&&(h--,(o=n[u])&&(o.__u|=2)),null==o||null==o.__v?(-1==u&&(i>c?d--:i<c&&d++),"function"!=typeof a.type&&(a.__u|=4)):u!=l&&(u==l-1?d--:u==l+1?d++:(u>l?d--:d++,a.__u|=4))):e.__k[s]=null;if(h)for(s=0;s<c;s++)null!=(o=n[s])&&!(2&o.__u)&&(o.__e==r&&(r=nF(o)),vF(o,o));return r}function lF(e,t,n){var r,i;if("function"==typeof e.type){for(r=e.__k,i=0;r&&i<r.length;i++)r[i]&&(r[i].__=e,t=lF(r[i],t,n));return t}e.__e!=t&&(t&&e.type&&!n.contains(t)&&(t=nF(e)),n.insertBefore(e.__e,t||null),t=e.__e);do{t=t&&t.nextSibling}while(null!=t&&8==t.nodeType);return t}function uF(e,t,n,r){var i,s,a=e.key,o=e.type,l=t[n];if(null===l&&null==e.key||l&&a==l.key&&o==l.type&&!(2&l.__u))return n;if(r>(null==l||2&l.__u?0:1))for(i=n-1,s=n+1;i>=0||s<t.length;){if(i>=0){if((l=t[i])&&!(2&l.__u)&&a==l.key&&o==l.type)return i;i--}if(s<t.length){if((l=t[s])&&!(2&l.__u)&&a==l.key&&o==l.type)return s;s++}}return-1}function cF(e,t,n){"-"==t[0]?e.setProperty(t,null==n?"":n):e[t]=null==n?"":"number"!=typeof n||YO.test(t)?n:n+"px"}function hF(e,t,n,r,i){var s,a;e:if("style"==t)if("string"==typeof n)e.style.cssText=n;else{if("string"==typeof r&&(e.style.cssText=r=""),r)for(t in r)n&&t in n||cF(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||cF(e.style,t,n[t])}else if("o"==t[0]&&"n"==t[1])s=t!=(t=t.replace(HO,"$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+s]=n,n?r?n.u=r.u:(n.u=jO,e.addEventListener(t,s?XO:WO,s)):e.removeEventListener(t,s?XO:WO,s);else{if("http://www.w3.org/2000/svg"==i)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==n?"":n;break e}catch(e){}"function"==typeof n||(null==n||!1===n&&"-"!=t[4]?e.removeAttribute(t):e.setAttribute(t,"popover"==t&&1==n?"":n))}}function dF(e){return function(t){if(this.l){var n=this.l[t.type+e];if(null==t.t)t.t=jO++;else if(t.t<n.u)return;return n(OO.event?OO.event(t):t)}}}function pF(e,t,n,r,i,s,a,o,l,u){var c,h,d,p,f,m,g,_,v,y,x,b,T,S,M,w,E,A=t.type;if(null!=t.constructor)return null;128&n.__u&&(l=!!(32&n.__u),s=[o=t.__e=n.__e]),(c=OO.__b)&&c(t);e:if("function"==typeof A)try{if(_=t.props,v="prototype"in A&&A.prototype.render,y=(c=A.contextType)&&r[c.__c],x=c?y?y.props.value:c.__:r,n.__c?g=(h=t.__c=n.__c).__=h.__E:(v?t.__c=h=new A(_,x):(t.__c=h=new tF(_,x),h.constructor=A,h.render=yF),y&&y.sub(h),h.props=_,h.state||(h.state={}),h.context=x,h.__n=r,d=h.__d=!0,h.__h=[],h._sb=[]),v&&null==h.__s&&(h.__s=h.state),v&&null!=A.getDerivedStateFromProps&&(h.__s==h.state&&(h.__s=QO({},h.__s)),QO(h.__s,A.getDerivedStateFromProps(_,h.__s))),p=h.props,f=h.state,h.__v=t,d)v&&null==A.getDerivedStateFromProps&&null!=h.componentWillMount&&h.componentWillMount(),v&&null!=h.componentDidMount&&h.__h.push(h.componentDidMount);else{if(v&&null==A.getDerivedStateFromProps&&_!==p&&null!=h.componentWillReceiveProps&&h.componentWillReceiveProps(_,x),!h.__e&&null!=h.shouldComponentUpdate&&!1===h.shouldComponentUpdate(_,h.__s,x)||t.__v==n.__v){for(t.__v!=n.__v&&(h.props=_,h.state=h.__s,h.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(e){e&&(e.__=t)}),b=0;b<h._sb.length;b++)h.__h.push(h._sb[b]);h._sb=[],h.__h.length&&a.push(h);break e}null!=h.componentWillUpdate&&h.componentWillUpdate(_,h.__s,x),v&&null!=h.componentDidUpdate&&h.__h.push(function(){h.componentDidUpdate(p,f,m)})}if(h.context=x,h.props=_,h.__P=e,h.__e=!1,T=OO.__r,S=0,v){for(h.state=h.__s,h.__d=!1,T&&T(t),c=h.render(h.props,h.state,h.context),M=0;M<h._sb.length;M++)h.__h.push(h._sb[M]);h._sb=[]}else do{h.__d=!1,T&&T(t),c=h.render(h.props,h.state,h.context),h.state=h.__s}while(h.__d&&++S<25);h.state=h.__s,null!=h.getChildContext&&(r=QO(QO({},r),h.getChildContext())),v&&!d&&null!=h.getSnapshotBeforeUpdate&&(m=h.getSnapshotBeforeUpdate(p,f)),w=c,null!=c&&c.type===eF&&null==c.key&&(w=mF(c.props.children)),o=aF(e,KO(w)?w:[w],t,n,r,i,s,a,o,l,u),h.base=t.__e,t.__u&=-161,h.__h.length&&a.push(h),g&&(h.__E=h.__=null)}catch(e){if(t.__v=null,l||null!=s)if(e.then){for(t.__u|=l?160:128;o&&8==o.nodeType&&o.nextSibling;)o=o.nextSibling;s[s.indexOf(o)]=null,t.__e=o}else for(E=s.length;E--;)ZO(s[E]);else t.__e=n.__e,t.__k=n.__k;OO.__e(e,t,n)}else null==s&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):o=t.__e=gF(n.__e,t,n,r,i,s,a,l,u);return(c=OO.diffed)&&c(t),128&t.__u?void 0:o}function fF(e,t,n){for(var r=0;r<n.length;r++)_F(n[r],n[++r],n[++r]);OO.__c&&OO.__c(t,e),e.some(function(t){try{e=t.__h,t.__h=[],e.some(function(e){e.call(t)})}catch(e){OO.__e(e,t.__v)}})}function mF(e){return"object"!=typeof e||null==e||e.__b&&e.__b>0?e:KO(e)?e.map(mF):QO({},e)}function gF(e,t,n,r,i,s,a,o,l){var u,c,h,d,p,f,m,g=n.props,_=t.props,v=t.type;if("svg"==v?i="http://www.w3.org/2000/svg":"math"==v?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),null!=s)for(u=0;u<s.length;u++)if((p=s[u])&&"setAttribute"in p==!!v&&(v?p.localName==v:3==p.nodeType)){e=p,s[u]=null;break}if(null==e){if(null==v)return document.createTextNode(_);e=document.createElementNS(i,v,_.is&&_),o&&(OO.__m&&OO.__m(t,s),o=!1),s=null}if(null==v)g===_||o&&e.data==_||(e.data=_);else{if(s=s&&UO.call(e.childNodes),g=n.props||qO,!o&&null!=s)for(g={},u=0;u<e.attributes.length;u++)g[(p=e.attributes[u]).name]=p.value;for(u in g)if(p=g[u],"children"==u);else if("dangerouslySetInnerHTML"==u)h=p;else if(!(u in _)){if("value"==u&&"defaultValue"in _||"checked"==u&&"defaultChecked"in _)continue;hF(e,u,null,p,i)}for(u in _)p=_[u],"children"==u?d=p:"dangerouslySetInnerHTML"==u?c=p:"value"==u?f=p:"checked"==u?m=p:o&&"function"!=typeof p||g[u]===p||hF(e,u,p,g[u],i);if(c)o||h&&(c.__html==h.__html||c.__html==e.innerHTML)||(e.innerHTML=c.__html),t.__k=[];else if(h&&(e.innerHTML=""),aF("template"==t.type?e.content:e,KO(d)?d:[d],t,n,r,"foreignObject"==v?"http://www.w3.org/1999/xhtml":i,s,a,s?s[0]:n.__k&&nF(n,0),o,l),null!=s)for(u=s.length;u--;)ZO(s[u]);o||(u="value","progress"==v&&null==f?e.removeAttribute("value"):null!=f&&(f!==e[u]||"progress"==v&&!f||"option"==v&&f!=g[u])&&hF(e,u,f,g[u],i),u="checked",null!=m&&m!=e[u]&&hF(e,u,m,g[u],i))}return e}function _F(e,t,n){try{if("function"==typeof e){var r="function"==typeof e.__u;r&&e.__u(),r&&null==t||(e.__u=e(t))}else e.current=t}catch(e){OO.__e(e,n)}}function vF(e,t,n){var r,i;if(OO.unmount&&OO.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||_F(r,null,t)),null!=(r=e.__c)){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(e){OO.__e(e,t)}r.base=r.__P=null}if(r=e.__k)for(i=0;i<r.length;i++)r[i]&&vF(r[i],t,n||"function"!=typeof e.type);n||ZO(e.__e),e.__c=e.__=e.__e=void 0}function yF(e,t,n){return this.constructor(e,n)}function xF(e,t,n){var r,i,s;t==document&&(t=document.documentElement),OO.__&&OO.__(e,t),r=!1?null:t.__k,i=[],s=[],pF(t,e=t.__k=function(e,t,n){var r,i,s,a={};for(s in t)"key"==s?r=t[s]:"ref"==s?i=t[s]:a[s]=t[s];if(arguments.length>2&&(a.children=arguments.length>3?UO.call(arguments,2):n),"function"==typeof e&&null!=e.defaultProps)for(s in e.defaultProps)void 0===a[s]&&(a[s]=e.defaultProps[s]);return JO(e,a,r,i,null)}(eF,null,[e]),r||qO,qO,t.namespaceURI,r?null:t.firstChild?UO.call(t.childNodes):null,i,r?r.__e:t.firstChild,false,s),fF(i,e,s)}function bF(e,t,n){var r,i,s,a,o=QO({},e.props);for(s in e.type&&e.type.defaultProps&&(a=e.type.defaultProps),t)"key"==s?r=t[s]:"ref"==s?i=t[s]:o[s]=void 0===t[s]&&null!=a?a[s]:t[s];return arguments.length>2&&(o.children=arguments.length>3?UO.call(arguments,2):n),JO(e.type,o,r||e.key,i||e.ref,null)}function TF(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function SF(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t);if("object"!=typeof r)return r;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:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function MF(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function wF(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,s,a,o=[],l=!0,u=!1;try{if(s=(n=n.call(e)).next,0===t);else for(;!(l=(r=s.call(n)).done)&&(o.push(r.value),o.length!==t);l=!0);}catch(e){u=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(u)throw i}}return o}}(e,t)||function(e,t){if(e){if("string"==typeof e)return TF(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?TF(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)}UO=$O.slice,OO={__e:function(e,t,n,r){for(var i,s,a;t=t.__;)if((i=t.__c)&&!i.__)try{if((s=i.constructor)&&null!=s.getDerivedStateFromError&&(i.setState(s.getDerivedStateFromError(e)),a=i.__d),null!=i.componentDidCatch&&(i.componentDidCatch(e,r||{}),a=i.__d),a)return i.__E=i}catch(t){e=t}throw e}},FO=0,BO=function(e){return null!=e&&null==e.constructor},tF.prototype.setState=function(e,t){var n;n=null!=this.__s&&this.__s!=this.state?this.__s:this.__s=QO({},this.state),"function"==typeof e&&(e=e(QO({},n),this.props)),e&&QO(n,e),null!=e&&this.__v&&(t&&this._sb.push(t),iF(this))},tF.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),iF(this))},tF.prototype.render=eF,kO=[],VO="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,GO=function(e,t){return e.__v.__b-t.__v.__b},sF.__r=0,HO=/(PointerCapture)$|Capture$/i,jO=0,WO=dF(!1),XO=dF(!0);var AF=function(e){if("object"!==EF(e))return e;var t,n=bF(e);n.props&&(n.props=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?MF(Object(n),!0).forEach(function(t){SF(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):MF(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}({},n.props),null!=n&&null!==(t=n.props)&&void 0!==t&&t.children&&(n.props.children=Array.isArray(n.props.children)?n.props.children.map(AF):AF(n.props.children)));return n};!function(e,t){void 0===t&&(t={});var n=t.insertAt;if("undefined"!=typeof document){var r=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");i.type="text/css","top"===n&&r.firstChild?r.insertBefore(i,r.firstChild):r.appendChild(i),i.styleSheet?i.styleSheet.cssText=e:i.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 RF=Wh({props:{content:{default:!1},offsetX:{triggerUpdate:!1},offsetY:{triggerUpdate:!1}},init:function(e,t){var n=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).style,r=void 0===n?{}:n,i=function(e){return"string"==typeof e?new IO([[document.querySelector(e)]],[document.documentElement]):new IO([[e]],DO)}(!!e&&"object"===EF(e)&&!!e.node&&"function"==typeof e.node?e.node():e);"static"===i.style("position")&&i.style("position","relative"),t.tooltipEl=i.append("div").attr("class","float-tooltip-kap"),Object.entries(r).forEach(function(e){var n=wF(e,2),r=n[0],i=n[1];return t.tooltipEl.style(r,i)}),t.tooltipEl.style("left","-10000px").style("display","none");var s="tooltip-".concat(Math.round(1e12*Math.random()));t.mouseInside=!1,i.on("mousemove.".concat(s),function(e){t.mouseInside=!0;var n=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 n=t.ownerSVGElement||t;if(n.createSVGPoint){var r=n.createSVGPoint();return r.x=e.clientX,r.y=e.clientY,[(r=r.matrixTransform(t.getScreenCTM().inverse())).x,r.y]}if(t.getBoundingClientRect){var i=t.getBoundingClientRect();return[e.clientX-i.left-t.clientLeft,e.clientY-i.top-t.clientTop]}}return[e.pageX,e.pageY]}(e),r=i.node(),s=r.offsetWidth,a=r.offsetHeight,o=[null===t.offsetX||void 0===t.offsetX?"-".concat(n[0]/s*100,"%"):"number"==typeof t.offsetX?"calc(-50% + ".concat(t.offsetX,"px)"):t.offsetX,null===t.offsetY||void 0===t.offsetY?a>130&&a-n[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",n[0]+"px").style("top",n[1]+"px").style("transform","translate(".concat(o.join(","),")")),t.content&&t.tooltipEl.style("display","inline")}),i.on("mouseover.".concat(s),function(){t.mouseInside=!0,t.content&&t.tooltipEl.style("display","inline")}),i.on("mouseout.".concat(s),function(){t.mouseInside=!1,t.tooltipEl.style("display","none")})},update:function(e){var t,n;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 BO(bF(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(n=e.tooltipEl.node()).__k,xF(AF(t),n)):e.tooltipEl.text("")}});function CF(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function NF(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,t);if("object"!=typeof r)return r;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:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function PF(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var r,i,s,a,o=[],l=!0,u=!1;try{if(s=(n=n.call(e)).next,0===t);else for(;!(l=(r=s.call(n)).done)&&(o.push(r.value),o.length!==t);l=!0);}catch(e){u=!0,i=e}finally{try{if(!l&&null!=n.return&&(a=n.return(),Object(a)!==a))return}finally{if(u)throw i}}return o}}(e,t)||DF(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 LF(e){return function(e){if(Array.isArray(e))return CF(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||DF(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 DF(e,t){if(e){if("string"==typeof e)return CF(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?CF(e,t):void 0}}!function(e,t){void 0===t&&(t={});var n=t.insertAt;if("undefined"!=typeof document){var r=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");i.type="text/css","top"===n&&r.firstChild?r.insertBefore(i,r.firstChild):r.appendChild(i),i.styleSheet?i.styleSheet.cssText=e:i.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}");var IF=window.THREE?window.THREE:{WebGLRenderer:class{constructor(e={}){const{canvas:t=Gt(),context:n=null,depth:r=!0,stencil:i=!1,alpha:a=!1,antialias:o=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:u=!1,powerPreference:c="default",failIfMajorPerformanceCaveat:h=!1,reverseDepthBuffer:d=!1}=e;let p;if(this.isWebGLRenderer=!0,null!==n){if("undefined"!=typeof WebGLRenderingContext&&n instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");p=n.getContextAttributes().alpha}else p=a;const f=new Uint32Array(4),m=new Int32Array(4);let g=null,_=null;const v=[],y=[];this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=0,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const x=this;let b=!1;this._outputColorSpace=rt;let T=0,S=0,M=null,w=-1,E=null;const A=new an,R=new an;let C=null;const N=new Nr(0);let P=0,L=t.width,D=t.height,I=1,U=null,O=null;const F=new an(0,0,L,D),B=new an(0,0,L,D);let k=!1;const z=new Xi;let V=!1,G=!1;const H=new Bn,j=new Bn,W=new Ut,X=new an,q={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let $=!1;function Y(){return null===M?I:1}let K,Q,Z,J,ee,re,ie,ae,le,pe,fe,me,ge,_e,ve,ye,be,Me,we,Ee,Ae,Re,Ce,Ne,Pe=n;function Le(e,n){return t.getContext(e,n)}try{const e={alpha:!0,depth:r,stencil:i,antialias:o,premultipliedAlpha:l,preserveDrawingBuffer:u,powerPreference:c,failIfMajorPerformanceCaveat:h};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${s}`),t.addEventListener("webglcontextlost",Ue,!1),t.addEventListener("webglcontextrestored",Oe,!1),t.addEventListener("webglcontextcreationerror",Fe,!1),null===Pe){const t="webgl2";if(Pe=Le(t,e),null===Pe)throw Le(t)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(e){throw console.error("THREE.WebGLRenderer: "+e.message),e}function De(){K=new Ja(Pe),K.init(),Re=new Kl(Pe,K),Q=new Pa(Pe,K,e,Re),Z=new $l(Pe,K),Q.reverseDepthBuffer&&d&&Z.buffers.depth.setReversed(!0),J=new no(Pe),ee=new Ul,re=new Yl(Pe,K,Z,ee,Q,Re,J),ie=new Da(x),ae=new Za(x),le=new ba(Pe),Ce=new Ca(Pe,le),pe=new eo(Pe,le,J,Ce),fe=new io(Pe,pe,le,J),we=new ro(Pe,Q,re),ye=new La(ee),me=new Il(x,ie,ae,K,Q,Ce,ye),ge=new tu(x,ee),_e=new kl,ve=new Wl(K),Me=new Ra(x,ie,ae,Z,fe,p,l),be=new Xl(x,fe,Q),Ne=new nu(Pe,J,Q,Z),Ee=new Na(Pe,K,J),Ae=new to(Pe,K,J),J.programs=me.programs,x.capabilities=Q,x.extensions=K,x.properties=ee,x.renderLists=_e,x.shadowMap=be,x.state=Z,x.info=J}De();const Ie=new Zl(x,Pe);function Ue(e){e.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),b=!0}function Oe(){console.log("THREE.WebGLRenderer: Context Restored."),b=!1;const e=J.autoReset,t=be.enabled,n=be.autoUpdate,r=be.needsUpdate,i=be.type;De(),J.autoReset=e,be.enabled=t,be.autoUpdate=n,be.needsUpdate=r,be.type=i}function Fe(e){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",e.statusMessage)}function Be(e){const t=e.target;t.removeEventListener("dispose",Be),function(e){(function(e){const t=ee.get(e).programs;void 0!==t&&(t.forEach(function(e){me.releaseProgram(e)}),e.isShaderMaterial&&me.releaseShaderCache(e))})(e),ee.remove(e)}(t)}function ke(e,t,n){!0===e.transparent&&2===e.side&&!1===e.forceSinglePass?(e.side=1,e.needsUpdate=!0,Ye(e,t,n),e.side=0,e.needsUpdate=!0,Ye(e,t,n),e.side=2):Ye(e,t,n)}this.xr=Ie,this.getContext=function(){return Pe},this.getContextAttributes=function(){return Pe.getContextAttributes()},this.forceContextLoss=function(){const e=K.get("WEBGL_lose_context");e&&e.loseContext()},this.forceContextRestore=function(){const e=K.get("WEBGL_lose_context");e&&e.restoreContext()},this.getPixelRatio=function(){return I},this.setPixelRatio=function(e){void 0!==e&&(I=e,this.setSize(L,D,!1))},this.getSize=function(e){return e.set(L,D)},this.setSize=function(e,n,r=!0){Ie.isPresenting?console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting."):(L=e,D=n,t.width=Math.floor(e*I),t.height=Math.floor(n*I),!0===r&&(t.style.width=e+"px",t.style.height=n+"px"),this.setViewport(0,0,e,n))},this.getDrawingBufferSize=function(e){return e.set(L*I,D*I).floor()},this.setDrawingBufferSize=function(e,n,r){L=e,D=n,I=r,t.width=Math.floor(e*r),t.height=Math.floor(n*r),this.setViewport(0,0,e,n)},this.getCurrentViewport=function(e){return e.copy(A)},this.getViewport=function(e){return e.copy(F)},this.setViewport=function(e,t,n,r){e.isVector4?F.set(e.x,e.y,e.z,e.w):F.set(e,t,n,r),Z.viewport(A.copy(F).multiplyScalar(I).round())},this.getScissor=function(e){return e.copy(B)},this.setScissor=function(e,t,n,r){e.isVector4?B.set(e.x,e.y,e.z,e.w):B.set(e,t,n,r),Z.scissor(R.copy(B).multiplyScalar(I).round())},this.getScissorTest=function(){return k},this.setScissorTest=function(e){Z.setScissorTest(k=e)},this.setOpaqueSort=function(e){U=e},this.setTransparentSort=function(e){O=e},this.getClearColor=function(e){return e.copy(Me.getClearColor())},this.setClearColor=function(){Me.setClearColor(...arguments)},this.getClearAlpha=function(){return Me.getClearAlpha()},this.setClearAlpha=function(){Me.setClearAlpha(...arguments)},this.clear=function(e=!0,t=!0,n=!0){let r=0;if(e){let e=!1;if(null!==M){const t=M.texture.format;e=t===Se||t===Te||t===xe}if(e){const e=M.texture.type,t=e===ne||e===oe||e===se||e===de||e===ce||e===he,n=Me.getClearColor(),r=Me.getClearAlpha(),i=n.r,s=n.g,a=n.b;t?(f[0]=i,f[1]=s,f[2]=a,f[3]=r,Pe.clearBufferuiv(Pe.COLOR,0,f)):(m[0]=i,m[1]=s,m[2]=a,m[3]=r,Pe.clearBufferiv(Pe.COLOR,0,m))}else r|=Pe.COLOR_BUFFER_BIT}t&&(r|=Pe.DEPTH_BUFFER_BIT),n&&(r|=Pe.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),Pe.clear(r)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){t.removeEventListener("webglcontextlost",Ue,!1),t.removeEventListener("webglcontextrestored",Oe,!1),t.removeEventListener("webglcontextcreationerror",Fe,!1),Me.dispose(),_e.dispose(),ve.dispose(),ee.dispose(),ie.dispose(),ae.dispose(),fe.dispose(),Ce.dispose(),Ne.dispose(),me.dispose(),Ie.dispose(),Ie.removeEventListener("sessionstart",Ve),Ie.removeEventListener("sessionend",Ge),He.stop()},this.renderBufferDirect=function(e,t,n,r,i,s){null===t&&(t=q);const a=i.isMesh&&i.matrixWorld.determinant()<0,o=function(e,t,n,r,i){!0!==t.isScene&&(t=q);re.resetTextureUnits();const s=t.fog,a=r.isMeshStandardMaterial?t.environment:null,o=null===M?x.outputColorSpace:!0===M.isXRRenderTarget?M.texture.colorSpace:it,l=(r.isMeshStandardMaterial?ae:ie).get(r.envMap||a),u=!0===r.vertexColors&&!!n.attributes.color&&4===n.attributes.color.itemSize,c=!!n.attributes.tangent&&(!!r.normalMap||r.anisotropy>0),h=!!n.morphAttributes.position,d=!!n.morphAttributes.normal,p=!!n.morphAttributes.color;let f=0;r.toneMapped&&(null!==M&&!0!==M.isXRRenderTarget||(f=x.toneMapping));const m=n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color,g=void 0!==m?m.length:0,v=ee.get(r),y=_.state.lights;if(!0===V&&(!0===G||e!==E)){const t=e===E&&r.id===w;ye.setState(r,e,t)}let b=!1;r.version===v.__version?v.needsLights&&v.lightsStateVersion!==y.state.version||v.outputColorSpace!==o||i.isBatchedMesh&&!1===v.batching?b=!0:i.isBatchedMesh||!0!==v.batching?i.isBatchedMesh&&!0===v.batchingColor&&null===i.colorTexture||i.isBatchedMesh&&!1===v.batchingColor&&null!==i.colorTexture||i.isInstancedMesh&&!1===v.instancing?b=!0:i.isInstancedMesh||!0!==v.instancing?i.isSkinnedMesh&&!1===v.skinning?b=!0:i.isSkinnedMesh||!0!==v.skinning?i.isInstancedMesh&&!0===v.instancingColor&&null===i.instanceColor||i.isInstancedMesh&&!1===v.instancingColor&&null!==i.instanceColor||i.isInstancedMesh&&!0===v.instancingMorph&&null===i.morphTexture||i.isInstancedMesh&&!1===v.instancingMorph&&null!==i.morphTexture||v.envMap!==l||!0===r.fog&&v.fog!==s?b=!0:void 0===v.numClippingPlanes||v.numClippingPlanes===ye.numPlanes&&v.numIntersection===ye.numIntersection?(v.vertexAlphas!==u||v.vertexTangents!==c||v.morphTargets!==h||v.morphNormals!==d||v.morphColors!==p||v.toneMapping!==f||v.morphTargetsCount!==g)&&(b=!0):b=!0:b=!0:b=!0:b=!0:(b=!0,v.__version=r.version);let T=v.currentProgram;!0===b&&(T=Ye(r,t,i));let S=!1,A=!1,R=!1;const C=T.getUniforms(),N=v.uniforms;Z.useProgram(T.program)&&(S=!0,A=!0,R=!0);r.id!==w&&(w=r.id,A=!0);if(S||E!==e){Z.buffers.depth.getReversed()?(H.copy(e.projectionMatrix),function(e){const t=e.elements;t[2]=.5*t[2]+.5*t[3],t[6]=.5*t[6]+.5*t[7],t[10]=.5*t[10]+.5*t[11],t[14]=.5*t[14]+.5*t[15]}(H),function(e){const t=e.elements;-1===t[11]?(t[10]=-t[10]-1,t[14]=-t[14]):(t[10]=-t[10],t[14]=1-t[14])}(H),C.setValue(Pe,"projectionMatrix",H)):C.setValue(Pe,"projectionMatrix",e.projectionMatrix),C.setValue(Pe,"viewMatrix",e.matrixWorldInverse);const t=C.map.cameraPosition;void 0!==t&&t.setValue(Pe,W.setFromMatrixPosition(e.matrixWorld)),Q.logarithmicDepthBuffer&&C.setValue(Pe,"logDepthBufFC",2/(Math.log(e.far+1)/Math.LN2)),(r.isMeshPhongMaterial||r.isMeshToonMaterial||r.isMeshLambertMaterial||r.isMeshBasicMaterial||r.isMeshStandardMaterial||r.isShaderMaterial)&&C.setValue(Pe,"isOrthographic",!0===e.isOrthographicCamera),E!==e&&(E=e,A=!0,R=!0)}if(i.isSkinnedMesh){C.setOptional(Pe,i,"bindMatrix"),C.setOptional(Pe,i,"bindMatrixInverse");const e=i.skeleton;e&&(null===e.boneTexture&&e.computeBoneTexture(),C.setValue(Pe,"boneTexture",e.boneTexture,re))}i.isBatchedMesh&&(C.setOptional(Pe,i,"batchingTexture"),C.setValue(Pe,"batchingTexture",i._matricesTexture,re),C.setOptional(Pe,i,"batchingIdTexture"),C.setValue(Pe,"batchingIdTexture",i._indirectTexture,re),C.setOptional(Pe,i,"batchingColorTexture"),null!==i._colorsTexture&&C.setValue(Pe,"batchingColorTexture",i._colorsTexture,re));const P=n.morphAttributes;void 0===P.position&&void 0===P.normal&&void 0===P.color||we.update(i,n,T);(A||v.receiveShadow!==i.receiveShadow)&&(v.receiveShadow=i.receiveShadow,C.setValue(Pe,"receiveShadow",i.receiveShadow));r.isMeshGouraudMaterial&&null!==r.envMap&&(N.envMap.value=l,N.flipEnvMap.value=l.isCubeTexture&&!1===l.isRenderTargetTexture?-1:1);r.isMeshStandardMaterial&&null===r.envMap&&null!==t.environment&&(N.envMapIntensity.value=t.environmentIntensity);A&&(C.setValue(Pe,"toneMappingExposure",x.toneMappingExposure),v.needsLights&&(U=R,(L=N).ambientLightColor.needsUpdate=U,L.lightProbe.needsUpdate=U,L.directionalLights.needsUpdate=U,L.directionalLightShadows.needsUpdate=U,L.pointLights.needsUpdate=U,L.pointLightShadows.needsUpdate=U,L.spotLights.needsUpdate=U,L.spotLightShadows.needsUpdate=U,L.rectAreaLights.needsUpdate=U,L.hemisphereLights.needsUpdate=U),s&&!0===r.fog&&ge.refreshFogUniforms(N,s),ge.refreshMaterialUniforms(N,r,I,D,_.state.transmissionRenderTarget[e.id]),cl.upload(Pe,Ke(v),N,re));var L,U;r.isShaderMaterial&&!0===r.uniformsNeedUpdate&&(cl.upload(Pe,Ke(v),N,re),r.uniformsNeedUpdate=!1);r.isSpriteMaterial&&C.setValue(Pe,"center",i.center);if(C.setValue(Pe,"modelViewMatrix",i.modelViewMatrix),C.setValue(Pe,"normalMatrix",i.normalMatrix),C.setValue(Pe,"modelMatrix",i.matrixWorld),r.isShaderMaterial||r.isRawShaderMaterial){const e=r.uniformsGroups;for(let t=0,n=e.length;t<n;t++){const n=e[t];Ne.update(n,T),Ne.bind(n,T)}}return T}(e,t,n,r,i);Z.setMaterial(r,a);let l=n.index,u=1;if(!0===r.wireframe){if(l=pe.getWireframeAttribute(n),void 0===l)return;u=2}const c=n.drawRange,h=n.attributes.position;let d=c.start*u,p=(c.start+c.count)*u;null!==s&&(d=Math.max(d,s.start*u),p=Math.min(p,(s.start+s.count)*u)),null!==l?(d=Math.max(d,0),p=Math.min(p,l.count)):null!=h&&(d=Math.max(d,0),p=Math.min(p,h.count));const f=p-d;if(f<0||f===1/0)return;let m;Ce.setup(i,r,o,n,l);let g=Ee;if(null!==l&&(m=le.get(l),g=Ae,g.setIndex(m)),i.isMesh)!0===r.wireframe?(Z.setLineWidth(r.wireframeLinewidth*Y()),g.setMode(Pe.LINES)):g.setMode(Pe.TRIANGLES);else if(i.isLine){let e=r.linewidth;void 0===e&&(e=1),Z.setLineWidth(e*Y()),i.isLineSegments?g.setMode(Pe.LINES):i.isLineLoop?g.setMode(Pe.LINE_LOOP):g.setMode(Pe.LINE_STRIP)}else i.isPoints?g.setMode(Pe.POINTS):i.isSprite&&g.setMode(Pe.TRIANGLES);if(i.isBatchedMesh)if(null!==i._multiDrawInstances)jt("THREE.WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),g.renderMultiDrawInstances(i._multiDrawStarts,i._multiDrawCounts,i._multiDrawCount,i._multiDrawInstances);else if(K.get("WEBGL_multi_draw"))g.renderMultiDraw(i._multiDrawStarts,i._multiDrawCounts,i._multiDrawCount);else{const e=i._multiDrawStarts,t=i._multiDrawCounts,n=i._multiDrawCount,s=l?le.get(l).bytesPerElement:1,a=ee.get(r).currentProgram.getUniforms();for(let r=0;r<n;r++)a.setValue(Pe,"_gl_DrawID",r),g.render(e[r]/s,t[r])}else if(i.isInstancedMesh)g.renderInstances(d,f,i.count);else if(n.isInstancedBufferGeometry){const e=void 0!==n._maxInstanceCount?n._maxInstanceCount:1/0,t=Math.min(n.instanceCount,e);g.renderInstances(d,f,t)}else g.render(d,f)},this.compile=function(e,t,n=null){null===n&&(n=e),_=ve.get(n),_.init(t),y.push(_),n.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(_.pushLight(e),e.castShadow&&_.pushShadow(e))}),e!==n&&e.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&(_.pushLight(e),e.castShadow&&_.pushShadow(e))}),_.setupLights();const r=new Set;return e.traverse(function(e){if(!(e.isMesh||e.isPoints||e.isLine||e.isSprite))return;const t=e.material;if(t)if(Array.isArray(t))for(let i=0;i<t.length;i++){const s=t[i];ke(s,n,e),r.add(s)}else ke(t,n,e),r.add(t)}),_=y.pop(),r},this.compileAsync=function(e,t,n=null){const r=this.compile(e,t,n);return new Promise(t=>{function n(){r.forEach(function(e){ee.get(e).currentProgram.isReady()&&r.delete(e)}),0!==r.size?setTimeout(n,10):t(e)}null!==K.get("KHR_parallel_shader_compile")?n():setTimeout(n,10)})};let ze=null;function Ve(){He.stop()}function Ge(){He.start()}const He=new xa;function je(e,t,n,r){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)n=e.renderOrder;else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)_.pushLight(e),e.castShadow&&_.pushShadow(e);else if(e.isSprite){if(!e.frustumCulled||z.intersectsSprite(e)){r&&X.setFromMatrixPosition(e.matrixWorld).applyMatrix4(j);const t=fe.update(e),i=e.material;i.visible&&g.push(e,t,i,n,X.z,null)}}else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||z.intersectsObject(e))){const t=fe.update(e),i=e.material;if(r&&(void 0!==e.boundingSphere?(null===e.boundingSphere&&e.computeBoundingSphere(),X.copy(e.boundingSphere.center)):(null===t.boundingSphere&&t.computeBoundingSphere(),X.copy(t.boundingSphere.center)),X.applyMatrix4(e.matrixWorld).applyMatrix4(j)),Array.isArray(i)){const r=t.groups;for(let s=0,a=r.length;s<a;s++){const a=r[s],o=i[a.materialIndex];o&&o.visible&&g.push(e,t,o,n,X.z,a)}}else i.visible&&g.push(e,t,i,n,X.z,null)}const i=e.children;for(let e=0,s=i.length;e<s;e++)je(i[e],t,n,r)}function We(e,t,n,r){const i=e.opaque,s=e.transmissive,a=e.transparent;_.setupLightsView(n),!0===V&&ye.setGlobalState(x.clippingPlanes,n),r&&Z.viewport(A.copy(r)),i.length>0&&qe(i,t,n),s.length>0&&qe(s,t,n),a.length>0&&qe(a,t,n),Z.buffers.depth.setTest(!0),Z.buffers.depth.setMask(!0),Z.buffers.color.setMask(!0),Z.setPolygonOffset(!1)}function Xe(e,t,n,r){if(null!==(!0===n.isScene?n.overrideMaterial:null))return;void 0===_.state.transmissionRenderTarget[r.id]&&(_.state.transmissionRenderTarget[r.id]=new ln(1,1,{generateMipmaps:!0,type:K.has("EXT_color_buffer_half_float")||K.has("EXT_color_buffer_float")?ue:ne,minFilter:te,samples:4,stencilBuffer:i,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:$t.workingColorSpace}));const s=_.state.transmissionRenderTarget[r.id],a=r.viewport||A;s.setSize(a.z*x.transmissionResolutionScale,a.w*x.transmissionResolutionScale);const o=x.getRenderTarget(),l=x.getActiveCubeFace(),u=x.getActiveMipmapLevel();x.setRenderTarget(s),x.getClearColor(N),P=x.getClearAlpha(),P<1&&x.setClearColor(16777215,.5),x.clear(),$&&Me.render(n);const c=x.toneMapping;x.toneMapping=0;const h=r.viewport;if(void 0!==r.viewport&&(r.viewport=void 0),_.setupLightsView(r),!0===V&&ye.setGlobalState(x.clippingPlanes,r),qe(e,n,r),re.updateMultisampleRenderTarget(s),re.updateRenderTargetMipmap(s),!1===K.has("WEBGL_multisampled_render_to_texture")){let e=!1;for(let i=0,s=t.length;i<s;i++){const s=t[i],a=s.object,o=s.geometry,l=s.material,u=s.group;if(2===l.side&&a.layers.test(r.layers)){const t=l.side;l.side=1,l.needsUpdate=!0,$e(a,n,r,o,l,u),l.side=t,l.needsUpdate=!0,e=!0}}!0===e&&(re.updateMultisampleRenderTarget(s),re.updateRenderTargetMipmap(s))}x.setRenderTarget(o,l,u),x.setClearColor(N,P),void 0!==h&&(r.viewport=h),x.toneMapping=c}function qe(e,t,n){const r=!0===t.isScene?t.overrideMaterial:null;for(let i=0,s=e.length;i<s;i++){const s=e[i],a=s.object,o=s.geometry,l=s.group;let u=s.material;!0===u.allowOverride&&null!==r&&(u=r),a.layers.test(n.layers)&&$e(a,t,n,o,u,l)}}function $e(e,t,n,r,i,s){e.onBeforeRender(x,t,n,r,i,s),e.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix),i.onBeforeRender(x,t,n,r,e,s),!0===i.transparent&&2===i.side&&!1===i.forceSinglePass?(i.side=1,i.needsUpdate=!0,x.renderBufferDirect(n,t,r,i,e,s),i.side=0,i.needsUpdate=!0,x.renderBufferDirect(n,t,r,i,e,s),i.side=2):x.renderBufferDirect(n,t,r,i,e,s),e.onAfterRender(x,t,n,r,i,s)}function Ye(e,t,n){!0!==t.isScene&&(t=q);const r=ee.get(e),i=_.state.lights,s=_.state.shadowsArray,a=i.state.version,o=me.getParameters(e,i.state,s,t,n),l=me.getProgramCacheKey(o);let u=r.programs;r.environment=e.isMeshStandardMaterial?t.environment:null,r.fog=t.fog,r.envMap=(e.isMeshStandardMaterial?ae:ie).get(e.envMap||r.environment),r.envMapRotation=null!==r.environment&&null===e.envMap?t.environmentRotation:e.envMapRotation,void 0===u&&(e.addEventListener("dispose",Be),u=new Map,r.programs=u);let c=u.get(l);if(void 0!==c){if(r.currentProgram===c&&r.lightsStateVersion===a)return Qe(e,o),c}else o.uniforms=me.getUniforms(e),e.onBeforeCompile(o,x),c=me.acquireProgram(o,l),u.set(l,c),r.uniforms=o.uniforms;const h=r.uniforms;return(e.isShaderMaterial||e.isRawShaderMaterial)&&!0!==e.clipping||(h.clippingPlanes=ye.uniform),Qe(e,o),r.needsLights=function(e){return e.isMeshLambertMaterial||e.isMeshToonMaterial||e.isMeshPhongMaterial||e.isMeshStandardMaterial||e.isShadowMaterial||e.isShaderMaterial&&!0===e.lights}(e),r.lightsStateVersion=a,r.needsLights&&(h.ambientLightColor.value=i.state.ambient,h.lightProbe.value=i.state.probe,h.directionalLights.value=i.state.directional,h.directionalLightShadows.value=i.state.directionalShadow,h.spotLights.value=i.state.spot,h.spotLightShadows.value=i.state.spotShadow,h.rectAreaLights.value=i.state.rectArea,h.ltc_1.value=i.state.rectAreaLTC1,h.ltc_2.value=i.state.rectAreaLTC2,h.pointLights.value=i.state.point,h.pointLightShadows.value=i.state.pointShadow,h.hemisphereLights.value=i.state.hemi,h.directionalShadowMap.value=i.state.directionalShadowMap,h.directionalShadowMatrix.value=i.state.directionalShadowMatrix,h.spotShadowMap.value=i.state.spotShadowMap,h.spotLightMatrix.value=i.state.spotLightMatrix,h.spotLightMap.value=i.state.spotLightMap,h.pointShadowMap.value=i.state.pointShadowMap,h.pointShadowMatrix.value=i.state.pointShadowMatrix),r.currentProgram=c,r.uniformsList=null,c}function Ke(e){if(null===e.uniformsList){const t=e.currentProgram.getUniforms();e.uniformsList=cl.seqWithValue(t.seq,e.uniforms)}return e.uniformsList}function Qe(e,t){const n=ee.get(e);n.outputColorSpace=t.outputColorSpace,n.batching=t.batching,n.batchingColor=t.batchingColor,n.instancing=t.instancing,n.instancingColor=t.instancingColor,n.instancingMorph=t.instancingMorph,n.skinning=t.skinning,n.morphTargets=t.morphTargets,n.morphNormals=t.morphNormals,n.morphColors=t.morphColors,n.morphTargetsCount=t.morphTargetsCount,n.numClippingPlanes=t.numClippingPlanes,n.numIntersection=t.numClipIntersection,n.vertexAlphas=t.vertexAlphas,n.vertexTangents=t.vertexTangents,n.toneMapping=t.toneMapping}He.setAnimationLoop(function(e){ze&&ze(e)}),"undefined"!=typeof self&&He.setContext(self),this.setAnimationLoop=function(e){ze=e,Ie.setAnimationLoop(e),null===e?He.stop():He.start()},Ie.addEventListener("sessionstart",Ve),Ie.addEventListener("sessionend",Ge),this.render=function(e,t){if(void 0!==t&&!0!==t.isCamera)return void console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");if(!0===b)return;if(!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&!0===t.matrixWorldAutoUpdate&&t.updateMatrixWorld(),!0===Ie.enabled&&!0===Ie.isPresenting&&(!0===Ie.cameraAutoUpdate&&Ie.updateCamera(t),t=Ie.getCamera()),!0===e.isScene&&e.onBeforeRender(x,e,t,M),_=ve.get(e,y.length),_.init(t),y.push(_),j.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),z.setFromProjectionMatrix(j),G=this.localClippingEnabled,V=ye.init(this.clippingPlanes,G),g=_e.get(e,v.length),g.init(),v.push(g),!0===Ie.enabled&&!0===Ie.isPresenting){const e=x.xr.getDepthSensingMesh();null!==e&&je(e,t,-1/0,x.sortObjects)}je(e,t,0,x.sortObjects),g.finish(),!0===x.sortObjects&&g.sort(U,O),$=!1===Ie.enabled||!1===Ie.isPresenting||!1===Ie.hasDepthSensing(),$&&Me.addToRenderList(g,e),this.info.render.frame++,!0===V&&ye.beginShadows();const n=_.state.shadowsArray;be.render(n,e,t),!0===V&&ye.endShadows(),!0===this.info.autoReset&&this.info.reset();const r=g.opaque,i=g.transmissive;if(_.setupLights(),t.isArrayCamera){const n=t.cameras;if(i.length>0)for(let t=0,s=n.length;t<s;t++){Xe(r,i,e,n[t])}$&&Me.render(e);for(let t=0,r=n.length;t<r;t++){const r=n[t];We(g,e,r,r.viewport)}}else i.length>0&&Xe(r,i,e,t),$&&Me.render(e),We(g,e,t);null!==M&&0===S&&(re.updateMultisampleRenderTarget(M),re.updateRenderTargetMipmap(M)),!0===e.isScene&&e.onAfterRender(x,e,t),Ce.resetDefaultState(),w=-1,E=null,y.pop(),y.length>0?(_=y[y.length-1],!0===V&&ye.setGlobalState(x.clippingPlanes,_.state.camera)):_=null,v.pop(),g=v.length>0?v[v.length-1]:null},this.getActiveCubeFace=function(){return T},this.getActiveMipmapLevel=function(){return S},this.getRenderTarget=function(){return M},this.setRenderTargetTextures=function(e,t,n){const r=ee.get(e);r.__autoAllocateDepthBuffer=!1===e.resolveDepthBuffer,!1===r.__autoAllocateDepthBuffer&&(r.__useRenderToTexture=!1),ee.get(e.texture).__webglTexture=t,ee.get(e.depthTexture).__webglTexture=r.__autoAllocateDepthBuffer?void 0:n,r.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(e,t){const n=ee.get(e);n.__webglFramebuffer=t,n.__useDefaultFramebuffer=void 0===t};const Ze=Pe.createFramebuffer();this.setRenderTarget=function(e,t=0,n=0){M=e,T=t,S=n;let r=!0,i=null,s=!1,a=!1;if(e){const o=ee.get(e);if(void 0!==o.__useDefaultFramebuffer)Z.bindFramebuffer(Pe.FRAMEBUFFER,null),r=!1;else if(void 0===o.__webglFramebuffer)re.setupRenderTarget(e);else if(o.__hasExternalTextures)re.rebindTextures(e,ee.get(e.texture).__webglTexture,ee.get(e.depthTexture).__webglTexture);else if(e.depthBuffer){const t=e.depthTexture;if(o.__boundDepthTexture!==t){if(null!==t&&ee.has(t)&&(e.width!==t.image.width||e.height!==t.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");re.setupDepthRenderbuffer(e)}}const l=e.texture;(l.isData3DTexture||l.isDataArrayTexture||l.isCompressedArrayTexture)&&(a=!0);const u=ee.get(e).__webglFramebuffer;e.isWebGLCubeRenderTarget?(i=Array.isArray(u[t])?u[t][n]:u[t],s=!0):i=e.samples>0&&!1===re.useMultisampledRTT(e)?ee.get(e).__webglMultisampledFramebuffer:Array.isArray(u)?u[n]:u,A.copy(e.viewport),R.copy(e.scissor),C=e.scissorTest}else A.copy(F).multiplyScalar(I).floor(),R.copy(B).multiplyScalar(I).floor(),C=k;0!==n&&(i=Ze);if(Z.bindFramebuffer(Pe.FRAMEBUFFER,i)&&r&&Z.drawBuffers(e,i),Z.viewport(A),Z.scissor(R),Z.setScissorTest(C),s){const r=ee.get(e.texture);Pe.framebufferTexture2D(Pe.FRAMEBUFFER,Pe.COLOR_ATTACHMENT0,Pe.TEXTURE_CUBE_MAP_POSITIVE_X+t,r.__webglTexture,n)}else if(a){const r=ee.get(e.texture),i=t;Pe.framebufferTextureLayer(Pe.FRAMEBUFFER,Pe.COLOR_ATTACHMENT0,r.__webglTexture,n,i)}else if(null!==e&&0!==n){const t=ee.get(e.texture);Pe.framebufferTexture2D(Pe.FRAMEBUFFER,Pe.COLOR_ATTACHMENT0,Pe.TEXTURE_2D,t.__webglTexture,n)}w=-1},this.readRenderTargetPixels=function(e,t,n,r,i,s,a,o=0){if(!e||!e.isWebGLRenderTarget)return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let l=ee.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&void 0!==a&&(l=l[a]),l){Z.bindFramebuffer(Pe.FRAMEBUFFER,l);try{const a=e.textures[o],l=a.format,u=a.type;if(!Q.textureFormatReadable(l))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");if(!Q.textureTypeReadable(u))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i&&(e.textures.length>1&&Pe.readBuffer(Pe.COLOR_ATTACHMENT0+o),Pe.readPixels(t,n,r,i,Re.convert(l),Re.convert(u),s))}finally{const e=null!==M?ee.get(M).__webglFramebuffer:null;Z.bindFramebuffer(Pe.FRAMEBUFFER,e)}}},this.readRenderTargetPixelsAsync=async function(e,t,n,r,i,s,a,o=0){if(!e||!e.isWebGLRenderTarget)throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let l=ee.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&void 0!==a&&(l=l[a]),l){if(t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i){Z.bindFramebuffer(Pe.FRAMEBUFFER,l);const a=e.textures[o],u=a.format,c=a.type;if(!Q.textureFormatReadable(u))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!Q.textureTypeReadable(c))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const h=Pe.createBuffer();Pe.bindBuffer(Pe.PIXEL_PACK_BUFFER,h),Pe.bufferData(Pe.PIXEL_PACK_BUFFER,s.byteLength,Pe.STREAM_READ),e.textures.length>1&&Pe.readBuffer(Pe.COLOR_ATTACHMENT0+o),Pe.readPixels(t,n,r,i,Re.convert(u),Re.convert(c),0);const d=null!==M?ee.get(M).__webglFramebuffer:null;Z.bindFramebuffer(Pe.FRAMEBUFFER,d);const p=Pe.fenceSync(Pe.SYNC_GPU_COMMANDS_COMPLETE,0);return Pe.flush(),await function(e,t,n){return new Promise(function(r,i){setTimeout(function s(){switch(e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0)){case e.WAIT_FAILED:i();break;case e.TIMEOUT_EXPIRED:setTimeout(s,n);break;default:r()}},n)})}(Pe,p,4),Pe.bindBuffer(Pe.PIXEL_PACK_BUFFER,h),Pe.getBufferSubData(Pe.PIXEL_PACK_BUFFER,0,s),Pe.deleteBuffer(h),Pe.deleteSync(p),s}throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")}},this.copyFramebufferToTexture=function(e,t=null,n=0){const r=Math.pow(2,-n),i=Math.floor(e.image.width*r),s=Math.floor(e.image.height*r),a=null!==t?t.x:0,o=null!==t?t.y:0;re.setTexture2D(e,0),Pe.copyTexSubImage2D(Pe.TEXTURE_2D,n,0,0,a,o,i,s),Z.unbindTexture()};const Je=Pe.createFramebuffer(),et=Pe.createFramebuffer();this.copyTextureToTexture=function(e,t,n=null,r=null,i=0,s=null){let a,o,l,u,c,h,d,p,f;null===s&&(0!==i?(jt("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),s=i,i=0):s=0);const m=e.isCompressedTexture?e.mipmaps[s]:e.image;if(null!==n)a=n.max.x-n.min.x,o=n.max.y-n.min.y,l=n.isBox3?n.max.z-n.min.z:1,u=n.min.x,c=n.min.y,h=n.isBox3?n.min.z:0;else{const t=Math.pow(2,-i);a=Math.floor(m.width*t),o=Math.floor(m.height*t),l=e.isDataArrayTexture?m.depth:e.isData3DTexture?Math.floor(m.depth*t):1,u=0,c=0,h=0}null!==r?(d=r.x,p=r.y,f=r.z):(d=0,p=0,f=0);const g=Re.convert(t.format),_=Re.convert(t.type);let v;t.isData3DTexture?(re.setTexture3D(t,0),v=Pe.TEXTURE_3D):t.isDataArrayTexture||t.isCompressedArrayTexture?(re.setTexture2DArray(t,0),v=Pe.TEXTURE_2D_ARRAY):(re.setTexture2D(t,0),v=Pe.TEXTURE_2D),Pe.pixelStorei(Pe.UNPACK_FLIP_Y_WEBGL,t.flipY),Pe.pixelStorei(Pe.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),Pe.pixelStorei(Pe.UNPACK_ALIGNMENT,t.unpackAlignment);const y=Pe.getParameter(Pe.UNPACK_ROW_LENGTH),x=Pe.getParameter(Pe.UNPACK_IMAGE_HEIGHT),b=Pe.getParameter(Pe.UNPACK_SKIP_PIXELS),T=Pe.getParameter(Pe.UNPACK_SKIP_ROWS),S=Pe.getParameter(Pe.UNPACK_SKIP_IMAGES);Pe.pixelStorei(Pe.UNPACK_ROW_LENGTH,m.width),Pe.pixelStorei(Pe.UNPACK_IMAGE_HEIGHT,m.height),Pe.pixelStorei(Pe.UNPACK_SKIP_PIXELS,u),Pe.pixelStorei(Pe.UNPACK_SKIP_ROWS,c),Pe.pixelStorei(Pe.UNPACK_SKIP_IMAGES,h);const M=e.isDataArrayTexture||e.isData3DTexture,w=t.isDataArrayTexture||t.isData3DTexture;if(e.isDepthTexture){const n=ee.get(e),r=ee.get(t),m=ee.get(n.__renderTarget),g=ee.get(r.__renderTarget);Z.bindFramebuffer(Pe.READ_FRAMEBUFFER,m.__webglFramebuffer),Z.bindFramebuffer(Pe.DRAW_FRAMEBUFFER,g.__webglFramebuffer);for(let n=0;n<l;n++)M&&(Pe.framebufferTextureLayer(Pe.READ_FRAMEBUFFER,Pe.COLOR_ATTACHMENT0,ee.get(e).__webglTexture,i,h+n),Pe.framebufferTextureLayer(Pe.DRAW_FRAMEBUFFER,Pe.COLOR_ATTACHMENT0,ee.get(t).__webglTexture,s,f+n)),Pe.blitFramebuffer(u,c,a,o,d,p,a,o,Pe.DEPTH_BUFFER_BIT,Pe.NEAREST);Z.bindFramebuffer(Pe.READ_FRAMEBUFFER,null),Z.bindFramebuffer(Pe.DRAW_FRAMEBUFFER,null)}else if(0!==i||e.isRenderTargetTexture||ee.has(e)){const n=ee.get(e),r=ee.get(t);Z.bindFramebuffer(Pe.READ_FRAMEBUFFER,Je),Z.bindFramebuffer(Pe.DRAW_FRAMEBUFFER,et);for(let e=0;e<l;e++)M?Pe.framebufferTextureLayer(Pe.READ_FRAMEBUFFER,Pe.COLOR_ATTACHMENT0,n.__webglTexture,i,h+e):Pe.framebufferTexture2D(Pe.READ_FRAMEBUFFER,Pe.COLOR_ATTACHMENT0,Pe.TEXTURE_2D,n.__webglTexture,i),w?Pe.framebufferTextureLayer(Pe.DRAW_FRAMEBUFFER,Pe.COLOR_ATTACHMENT0,r.__webglTexture,s,f+e):Pe.framebufferTexture2D(Pe.DRAW_FRAMEBUFFER,Pe.COLOR_ATTACHMENT0,Pe.TEXTURE_2D,r.__webglTexture,s),0!==i?Pe.blitFramebuffer(u,c,a,o,d,p,a,o,Pe.COLOR_BUFFER_BIT,Pe.NEAREST):w?Pe.copyTexSubImage3D(v,s,d,p,f+e,u,c,a,o):Pe.copyTexSubImage2D(v,s,d,p,u,c,a,o);Z.bindFramebuffer(Pe.READ_FRAMEBUFFER,null),Z.bindFramebuffer(Pe.DRAW_FRAMEBUFFER,null)}else w?e.isDataTexture||e.isData3DTexture?Pe.texSubImage3D(v,s,d,p,f,a,o,l,g,_,m.data):t.isCompressedArrayTexture?Pe.compressedTexSubImage3D(v,s,d,p,f,a,o,l,g,m.data):Pe.texSubImage3D(v,s,d,p,f,a,o,l,g,_,m):e.isDataTexture?Pe.texSubImage2D(Pe.TEXTURE_2D,s,d,p,a,o,g,_,m.data):e.isCompressedTexture?Pe.compressedTexSubImage2D(Pe.TEXTURE_2D,s,d,p,m.width,m.height,g,m.data):Pe.texSubImage2D(Pe.TEXTURE_2D,s,d,p,a,o,g,_,m);Pe.pixelStorei(Pe.UNPACK_ROW_LENGTH,y),Pe.pixelStorei(Pe.UNPACK_IMAGE_HEIGHT,x),Pe.pixelStorei(Pe.UNPACK_SKIP_PIXELS,b),Pe.pixelStorei(Pe.UNPACK_SKIP_ROWS,T),Pe.pixelStorei(Pe.UNPACK_SKIP_IMAGES,S),0===s&&t.generateMipmaps&&Pe.generateMipmap(v),Z.unbindTexture()},this.copyTextureToTexture3D=function(e,t,n=null,r=null,i=0){return jt('WebGLRenderer: copyTextureToTexture3D function has been deprecated. Use "copyTextureToTexture" instead.'),this.copyTextureToTexture(e,t,n,r,i)},this.initRenderTarget=function(e){void 0===ee.get(e).__webglFramebuffer&&re.setupRenderTarget(e)},this.initTexture=function(e){e.isCubeTexture?re.setTextureCube(e,0):e.isData3DTexture?re.setTexture3D(e,0):e.isDataArrayTexture||e.isCompressedArrayTexture?re.setTexture2DArray(e,0):re.setTexture2D(e,0),Z.unbindTexture()},this.resetState=function(){T=0,S=0,M=null,Z.reset(),Ce.reset()},"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return yt}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const t=this.getContext();t.drawingBufferColorSpace=$t._getDrawingBufferColorSpace(e),t.unpackColorSpace=$t._getUnpackColorSpace()}},Scene:Li,PerspectiveCamera:Mi,Raycaster:pa,SRGBColorSpace:rt,TextureLoader:class extends zs{constructor(e){super(e)}load(e,t,n,r){const i=new sn,s=new Gs(this.manager);return s.setCrossOrigin(this.crossOrigin),s.setPath(this.path),s.load(e,function(e){i.image=e,i.needsUpdate=!0,void 0!==t&&t(i)},n,r),i}},Vector2:Dt,Vector3:Ut,Box3:hn,Color:Nr,Mesh:di,SphereGeometry:Ms,MeshBasicMaterial:Ir,BackSide:1,Clock:ca},UF=Wh({props:{width:{default:window.innerWidth,onChange:function(e,t,n){isNaN(e)&&(t.width=n)}},height:{default:window.innerHeight,onChange:function(e,t,n){isNaN(e)&&(t.height=n)}},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.clock.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 n=null;if(e.hoverDuringDrag||!e.isPointerDragging){var r=this.intersectingObjects(e.pointerPos.x,e.pointerPos.y);e.hoverOrderComparator&&r.sort(function(t,n){return e.hoverOrderComparator(t.object,n.object)});var i=r.find(function(t){return e.hoverFilter(t.object)})||null;n=i?i.object:null,e.intersection=i||null}n!==e.hoverObj&&(e.onHover(n,e.hoverObj,e.intersection),e.tooltip.content(n&&Xh(e.tooltipContent)(n,e.intersection)||null),e.hoverObj=n)}e.tweenGroup.update()}return this},getPointerPos:function(e){var t=e.pointerPos;return{x:t.x,y:t.y}},cameraPosition:function(e,t,n,r){var i=e.camera;if(t&&e.initialised){var s=t,a=n||{x:0,y:0,z:0};if(r){var o=Object.assign({},i.position),l=h();e.tweenGroup.add(new wU(o).to(s,r).easing(yU.Quadratic.Out).onUpdate(u).start()),e.tweenGroup.add(new wU(l).to(a,r/3).easing(yU.Quadratic.Out).onUpdate(c).start())}else u(s),c(a);return this}return Object.assign({},i.position,{lookAt:h()});function u(e){var t=e.x,n=e.y,r=e.z;void 0!==t&&(i.position.x=t),void 0!==n&&(i.position.y=n),void 0!==r&&(i.position.z=r)}function c(t){var n=new IF.Vector3(t.x,t.y,t.z);e.controls.enabled&&e.controls.target?e.controls.target=n:i.lookAt(n)}function h(){return Object.assign(new IF.Vector3(0,0,-1e3).applyQuaternion(i.quaternion).add(i.position))}},zoomToFit:function(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:10,r=arguments.length,i=new Array(r>3?r-3:0),s=3;s<r;s++)i[s-3]=arguments[s];return this.fitToBbox(this.getBbox.apply(this,i),t,n)},fitToBbox:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:10,i=e.camera;if(t){var s=new IF.Vector3(0,0,0),a=2*Math.max.apply(Math,LF(Object.entries(t).map(function(e){var t=PF(e,2),n=t[0],r=t[1];return Math.max.apply(Math,LF(r.map(function(e){return Math.abs(s[n]-e)})))}))),o=(1-2*r/e.height)*i.fov,l=a/Math.atan(o*Math.PI/180),u=l/i.aspect,c=Math.max(l,u);if(c>0){var h=s.clone().sub(i.position).normalize().multiplyScalar(-c);this.cameraPosition(h,s,n)}}return this},getBbox:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(){return!0},n=new IF.Box3(new IF.Vector3(0,0,0),new IF.Vector3(0,0,0)),r=e.objects.filter(t);return r.length?(r.forEach(function(e){return n.expandByObject(e)}),Object.assign.apply(Object,LF(["x","y","z"].map(function(e){return NF({},e,[n.min[e],n.max[e]])})))):null},getScreenCoords:function(e,t,n,r){var i=new IF.Vector3(t,n,r);return i.project(this.camera()),{x:(i.x+1)*e.width/2,y:-(i.y-1)*e.height/2}},getSceneCoords:function(e,t,n){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,i=new IF.Vector2(t/e.width*2-1,-n/e.height*2+1),s=new IF.Raycaster;return s.setFromCamera(i,e.camera),Object.assign({},s.ray.at(r,new IF.Vector3))},intersectingObjects:function(e,t,n){var r=new IF.Vector2(t/e.width*2-1,-n/e.height*2+1),i=new IF.Raycaster;return i.params.Line.threshold=e.lineHoverPrecision,i.params.Points.threshold=e.pointsHoverPrecision,i.setFromCamera(r,e.camera),i.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}},stateInit:function(){return{scene:new IF.Scene,camera:new IF.PerspectiveCamera,clock:new IF.Clock,tweenGroup:new bU,lastRaycasterCheck:0}},init:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=n.controlType,i=void 0===r?"trackball":r,s=n.useWebGPU,a=void 0!==s&&s,o=n.rendererConfig,l=void 0===o?{}:o,u=n.extraRenderers,c=void 0===u?[]:u,h=n.waitForLoadComplete,d=void 0===h||h;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"}[i]||"",t.navInfo.style.display=t.showNavInfo?null:"none",t.tooltip=new RF(t.container),t.pointerPos=new IF.Vector2,t.pointerPos.x=-2,t.pointerPos.y=-2,["pointermove","pointerdown"].forEach(function(e){return t.container.addEventListener(e,function(n){if("pointerdown"===e&&(t.isPointerPressed=!0),!t.isPointerDragging&&"pointermove"===n.type&&(n.pressure>0||t.isPointerPressed)&&("touch"!==n.pointerType||void 0===n.movementX||[n.movementX,n.movementY].some(function(e){return Math.abs(e)>1}))&&(t.isPointerDragging=!0),t.enablePointerInteraction){var r=(i=t.container,s=i.getBoundingClientRect(),a=window.pageXOffset||document.documentElement.scrollLeft,o=window.pageYOffset||document.documentElement.scrollTop,{top:s.top+o,left:s.left+a});t.pointerPos.x=n.pageX-r.left,t.pointerPos.y=n.pageY-r.top}var i,s,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(a?rD:IF.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 II(t.renderer),t.postProcessingComposer.addPass(new UI(t.scene,t.camera)),t.controls=new{trackball:MD,orbit:nI,fly:vI}[i](t.camera,t.renderer.domElement),"fly"===i&&(t.controls.movementSpeed=300,t.controls.rollSpeed=Math.PI/6,t.controls.dragToLook=!0),"trackball"!==i&&"orbit"!==i||(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(LF(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 IF.Mesh),t.skysphere.visible=!1,t.loadComplete=t.scene.visible=!d,window.scene=t.scene},update:function(e,t){if(e.width&&e.height&&(t.hasOwnProperty("width")||t.hasOwnProperty("height"))){var n,r=e.width,i=e.height;e.container.style.width="".concat(r,"px"),e.container.style.height="".concat(i,"px"),[e.renderer,e.postProcessingComposer].concat(LF(e.extraRenderers)).forEach(function(e){return e.setSize(r,i)}),e.camera.aspect=r/i;var s=e.viewOffset.slice(0,2);s.some(function(e){return e})&&(n=e.camera).setViewOffset.apply(n,[r,i].concat(LF(s),[r,i])),e.camera.updateProjectionMatrix()}if(t.hasOwnProperty("viewOffset")){var a,o=e.width,l=e.height,u=e.viewOffset.slice(0,2);u.some(function(e){return e})?(a=e.camera).setViewOffset.apply(a,[o,l].concat(LF(u),[o,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 IF.SphereGeometry(e.skyRadius)),t.hasOwnProperty("backgroundColor")){var c=nU(e.backgroundColor).alpha;void 0===c&&(c=1),e.renderer.setClearColor(new IF.Color(vU(1,e.backgroundColor)),c)}function h(){e.loadComplete=e.scene.visible=!0}t.hasOwnProperty("backgroundImageUrl")&&(e.backgroundImageUrl?(new IF.TextureLoader).load(e.backgroundImageUrl,function(t){t.colorSpace=IF.SRGBColorSpace,e.skysphere.material=new IF.MeshBasicMaterial({map:t,side:IF.BackSide}),e.skysphere.visible=!0,e.onBackgroundImageLoaded&&setTimeout(e.onBackgroundImageLoaded),!e.loadComplete&&h()}):(e.skysphere.visible=!1,e.skysphere.material.map=null,!e.loadComplete&&h())),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)}))}});function OF(e,t){var n=new t;return n._destructor&&n._destructor(),{linkProp:function(t){return{default:n[t](),onChange:function(n,r){r[e][t](n)},triggerUpdate:!1}},linkMethod:function(t){return function(n){for(var r=n[e],i=arguments.length,s=new Array(i>1?i-1:0),a=1;a<i;a++)s[a-1]=arguments[a];var o=r[t].apply(r,s);return o===r?this:o}}}}var FF=window.THREE?window.THREE:{AmbientLight:sa,DirectionalLight:ia,REVISION:s},BF=OF("forceGraph",Op),kF=Object.assign.apply(Object,i(["jsonUrl","graphData","numDimensions","dagMode","dagLevelDistance","dagNodeFilter","onDagError","nodeRelSize","nodeId","nodeVal","nodeResolution","nodeColor","nodeAutoColorBy","nodeOpacity","nodeVisibility","nodeThreeObject","nodeThreeObjectExtend","nodePositionUpdate","linkSource","linkTarget","linkVisibility","linkColor","linkAutoColorBy","linkOpacity","linkWidth","linkResolution","linkCurvature","linkCurveRotation","linkMaterial","linkThreeObject","linkThreeObjectExtend","linkPositionUpdate","linkDirectionalArrowLength","linkDirectionalArrowColor","linkDirectionalArrowRelPos","linkDirectionalArrowResolution","linkDirectionalParticles","linkDirectionalParticleSpeed","linkDirectionalParticleOffset","linkDirectionalParticleWidth","linkDirectionalParticleColor","linkDirectionalParticleResolution","linkDirectionalParticleThreeObject","forceEngine","d3AlphaDecay","d3VelocityDecay","d3AlphaMin","ngraphPhysics","warmupTicks","cooldownTicks","cooldownTime","onEngineTick","onEngineStop"].map(function(e){return t({},e,BF.linkProp(e))}))),zF=Object.assign.apply(Object,i(["refresh","getGraphBbox","d3Force","d3ReheatSimulation","emitParticle"].map(function(e){return t({},e,BF.linkMethod(e))}))),VF=OF("renderObjs",UF),GF=Object.assign.apply(Object,i(["width","height","backgroundColor","showNavInfo","enablePointerInteraction"].map(function(e){return t({},e,VF.linkProp(e))}))),HF=Object.assign.apply(Object,i(["lights","cameraPosition","postProcessingComposer"].map(function(e){return t({},e,VF.linkMethod(e))})).concat([{graph2ScreenCoords:VF.linkMethod("getScreenCoords"),screen2GraphCoords:VF.linkMethod("getSceneCoords")}])),jF=Wh({props:r(r({nodeLabel:{default:"name",triggerUpdate:!1},linkLabel:{default:"name",triggerUpdate:!1},linkHoverPrecision:{default:1,onChange:function(e,t){return t.renderObjs.lineHoverPrecision(e)},triggerUpdate:!1},enableNavigationControls:{default:!0,onChange:function(e,t){var n=t.renderObjs.controls();n&&(n.enabled=e,e&&n.domElement&&n.domElement.dispatchEvent(new PointerEvent("pointerup")))},triggerUpdate:!1},enableNodeDrag:{default:!0,triggerUpdate:!1},onNodeDrag:{default:function(){},triggerUpdate:!1},onNodeDragEnd:{default:function(){},triggerUpdate:!1},onNodeClick:{triggerUpdate:!1},onNodeRightClick:{triggerUpdate:!1},onNodeHover:{triggerUpdate:!1},onLinkClick:{triggerUpdate:!1},onLinkRightClick:{triggerUpdate:!1},onLinkHover:{triggerUpdate:!1},onBackgroundClick:{triggerUpdate:!1},onBackgroundRightClick:{triggerUpdate:!1}},kF),GF),methods:r(r({zoomToFit:function(e,t,n){for(var r,i=arguments.length,s=new Array(i>3?i-3:0),a=3;a<i;a++)s[a-3]=arguments[a];return e.renderObjs.fitToBbox((r=e.forceGraph).getGraphBbox.apply(r,s),t,n),this},pauseAnimation:function(e){return null!==e.animationFrameRequestId&&(cancelAnimationFrame(e.animationFrameRequestId),e.animationFrameRequestId=null),this},resumeAnimation:function(e){return null===e.animationFrameRequestId&&this._animationCycle(),this},_animationCycle:function(e){e.enablePointerInteraction&&(this.renderer().domElement.style.cursor=null),e.forceGraph.tickFrame(),e.renderObjs.tick(),e.animationFrameRequestId=requestAnimationFrame(this._animationCycle)},scene:function(e){return e.renderObjs.scene()},camera:function(e){return e.renderObjs.camera()},renderer:function(e){return e.renderObjs.renderer()},controls:function(e){return e.renderObjs.controls()},tbControls:function(e){return e.renderObjs.tbControls()},_destructor:function(){this.pauseAnimation(),this.graphData({nodes:[],links:[]})}},zF),HF),stateInit:function(e){var t=e.controlType,n=e.rendererConfig,r=e.extraRenderers,i=new Op;return{forceGraph:i,renderObjs:UF({controlType:t,rendererConfig:n,extraRenderers:r}).objects([i]).lights([new FF.AmbientLight(13421772,Math.PI),new FF.DirectionalLight(16777215,.6*Math.PI)])}},init:function(e,t){e.innerHTML="",e.appendChild(t.container=document.createElement("div")),t.container.style.position="relative";var n=document.createElement("div");t.container.appendChild(n),t.renderObjs(n);var r,i=t.renderObjs.camera(),s=t.renderObjs.renderer(),a=t.renderObjs.controls();a.enabled=!!t.enableNavigationControls,t.lastSetCameraZ=i.position.z,t.container.appendChild(r=document.createElement("div")),r.className="graph-info-msg",r.textContent="",t.forceGraph.onLoading(function(){r.textContent="Loading..."}).onFinishLoading(function(){r.textContent=""}).onUpdate(function(){t.graphData=t.forceGraph.graphData(),0===i.position.x&&0===i.position.y&&i.position.z===t.lastSetCameraZ&&t.graphData.nodes.length&&(i.lookAt(t.forceGraph.position),t.lastSetCameraZ=i.position.z=170*Math.cbrt(t.graphData.nodes.length))}).onFinishUpdate(function(){if(t._dragControls){var e=t.graphData.nodes.find(function(e){return e.__initialFixedPos&&!e.__disposeControlsAfterDrag});e?e.__disposeControlsAfterDrag=!0:t._dragControls.dispose(),t._dragControls=void 0}if(t.enableNodeDrag&&t.enablePointerInteraction&&"d3"===t.forceEngine){var n=t._dragControls=new yu(t.graphData.nodes.map(function(e){return e.__threeObj}).filter(function(e){return e}),i,s.domElement);n.addEventListener("dragstart",function(e){var t=WF(e.object);if(t){a.enabled=!1,e.object.__initialPos=e.object.position.clone(),e.object.__prevPos=e.object.position.clone();var n=t.__data;!n.__initialFixedPos&&(n.__initialFixedPos={fx:n.fx,fy:n.fy,fz:n.fz}),!n.__initialPos&&(n.__initialPos={x:n.x,y:n.y,z:n.z}),["x","y","z"].forEach(function(e){return n["f".concat(e)]=n[e]}),s.domElement.classList.add("grabbable")}}),n.addEventListener("drag",function(e){var n=WF(e.object);if(n){if(!e.object.hasOwnProperty("__graphObjType")){var r=e.object.__initialPos,i=e.object.__prevPos,s=e.object.position;n.position.add(s.clone().sub(i)),i.copy(s),s.copy(r)}var a=n.__data,o=n.position,l={x:o.x-a.x,y:o.y-a.y,z:o.z-a.z};["x","y","z"].forEach(function(e){return a["f".concat(e)]=a[e]=o[e]}),t.forceGraph.d3AlphaTarget(.3).resetCountdown(),a.__dragged=!0,t.onNodeDrag(a,l)}}),n.addEventListener("dragend",function(e){var r=WF(e.object);if(r){delete e.object.__initialPos,delete e.object.__prevPos;var i=r.__data;i.__disposeControlsAfterDrag&&(n.dispose(),delete i.__disposeControlsAfterDrag);var o=i.__initialFixedPos,l=i.__initialPos,u={x:l.x-i.x,y:l.y-i.y,z:l.z-i.z};o&&(["x","y","z"].forEach(function(e){var t="f".concat(e);void 0===o[t]&&delete i[t]}),delete i.__initialFixedPos,delete i.__initialPos,i.__dragged&&(delete i.__dragged,t.onNodeDragEnd(i,u))),t.forceGraph.d3AlphaTarget(0).resetCountdown(),t.enableNavigationControls&&(a.enabled=!0,a.domElement&&a.domElement.ownerDocument&&a.domElement.ownerDocument.dispatchEvent(new PointerEvent("pointerup",{pointerType:"touch"}))),s.domElement.classList.remove("grabbable")}})}}),FF.REVISION<155&&(t.renderObjs.renderer().useLegacyLights=!1),t.renderObjs.hoverOrderComparator(function(e,t){var n=WF(e);if(!n)return 1;var r=WF(t);if(!r)return-1;var i=function(e){return"node"===e.__graphObjType};return i(r)-i(n)}).tooltipContent(function(e){var n=WF(e);return n&&Xh(t["".concat(n.__graphObjType,"Label")])(n.__data)||""}).hoverDuringDrag(!1).onHover(function(e){var n=WF(e);if(n!==t.hoverObj){var r=t.hoverObj?t.hoverObj.__graphObjType:null,i=t.hoverObj?t.hoverObj.__data:null,a=n?n.__graphObjType:null,o=n?n.__data:null;if(r&&r!==a){var l=t["on".concat("node"===r?"Node":"Link","Hover")];l&&l(null,i)}if(a){var u=t["on".concat("node"===a?"Node":"Link","Hover")];u&&u(o,r===a?i:null)}s.domElement.classList[n&&t["on".concat("node"===a?"Node":"Link","Click")]||!n&&t.onBackgroundClick?"add":"remove"]("clickable"),t.hoverObj=n}}).clickAfterDrag(!1).onClick(function(e,n){var r=WF(e);if(r){var i=t["on".concat("node"===r.__graphObjType?"Node":"Link","Click")];i&&i(r.__data,n)}else t.onBackgroundClick&&t.onBackgroundClick(n)}).onRightClick(function(e,n){var r=WF(e);if(r){var i=t["on".concat("node"===r.__graphObjType?"Node":"Link","RightClick")];i&&i(r.__data,n)}else t.onBackgroundRightClick&&t.onBackgroundRightClick(n)}),this._animationCycle()}});function WF(e){for(var t=e;t&&!t.hasOwnProperty("__graphObjType");)t=t.parent;return t}return jF});
|