// Version 1.29.1 react-force-graph-3d - https://github.com/vasturiano/react-force-graph !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("react")):"function"==typeof define&&define.amd?define(["react"],t):(e="undefined"!=typeof globalThis?globalThis:e||self).ForceGraph3D=t(e.React)}(this,function(e){"use strict";function t(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===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:String(t)}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function n(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){if(Object(n)!==n)return;l=!1}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)||i(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function r(e){return function(e){if(Array.isArray(e))return s(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||i(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 i(e,t){if(e){if("string"==typeof e)return s(e,t);var n=Object.prototype.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)?s(e,t):void 0}}function s(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);ne.length)&&(t=e.length);for(var n=0,r=Array(t);n1&&void 0!==arguments[1]?arguments[1]:e.useEffect,r=e.useRef(),i=e.useRef(!1),s=e.useRef(!1),a=o(e.useState(0),2);a[0];var l=a[1];i.current&&(s.current=!0),n(function(){return i.current||(r.current=t(),i.current=!0),l(function(e){return e+1}),function(){s.current&&r.current&&r.current()}},[])}const h="182",d=0,p=1,f=2,m=0,g=1,_=2,v=3,y=1,b=3,x=0,T=1,S=2,M=100,w=101,E=102,A=200,R=201,C=202,N=203,P=204,L=205,D=206,I=207,U=208,O=209,F=210,B=211,k=212,z=213,V=214,G=0,H=1,j=2,W=3,$=4,X=5,q=6,Y=7,K=0,Z=1,Q=2,J=1,ee=2,te=3,ne=4,re=5,ie=6,se=7,ae=301,oe=302,le=303,ue=304,ce=306,he=1e3,de=1001,pe=1002,fe=1003,me=1004,ge=1005,_e=1006,ve=1007,ye=1008,be=1009,xe=1010,Te=1011,Se=1012,Me=1013,we=1014,Ee=1015,Ae=1016,Re=1017,Ce=1018,Ne=1020,Pe=35902,Le=35899,De=1021,Ie=1022,Ue=1023,Oe=1026,Fe=1027,Be=1028,ke=1029,ze=1030,Ve=1031,Ge=1033,He=33776,je=33777,We=33778,$e=33779,Xe=35840,qe=35841,Ye=35842,Ke=35843,Ze=36196,Qe=37492,Je=37496,et=37488,tt=37489,nt=37490,rt=37491,it=37808,st=37809,at=37810,ot=37811,lt=37812,ut=37813,ct=37814,ht=37815,dt=37816,pt=37817,ft=37818,mt=37819,gt=37820,_t=37821,vt=36492,yt=36494,bt=36495,xt=36283,Tt=36284,St=36285,Mt=36286,wt="",Et="srgb",At="srgb-linear",Rt="linear",Ct="srgb",Nt=7680,Pt=512,Lt=513,Dt=514,It=515,Ut=516,Ot=517,Ft=518,Bt=519,kt=35044,zt=35048,Vt="300 es",Gt=2e3,Ht=2001,jt="compute",Wt="render";function $t(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}function Xt(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function qt(e){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}function Yt(){const e=qt("canvas");return e.style.display="block",e}const Kt={};function Zt(...e){const t="THREE."+e.shift();console.log(t,...e)}function Qt(...e){const t="THREE."+e.shift();console.warn(t,...e)}function Jt(...e){const t="THREE."+e.shift();console.error(t,...e)}function en(...e){const t=e.join(" ");t in Kt||(Kt[t]=!0,Qt(...e))}class tn{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>8&255]+nn[e>>16&255]+nn[e>>24&255]+"-"+nn[255&t]+nn[t>>8&255]+"-"+nn[t>>16&15|64]+nn[t>>24&255]+"-"+nn[63&n|128]+nn[n>>8&255]+"-"+nn[n>>16&255]+nn[n>>24&255]+nn[255&r]+nn[r>>8&255]+nn[r>>16&255]+nn[r>>24&255]).toLowerCase()}function ln(e,t,n){return Math.max(t,Math.min(n,e))}function un(e,t){return(e%t+t)%t}function cn(e,t,n){return(1-n)*e+n*t}function hn(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 dn(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 pn={DEG2RAD:sn,RAD2DEG:an,generateUUID:on,clamp:ln,euclideanModulo:un,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:cn,damp:function(e,t,n,r){return cn(e,t,1-Math.exp(-n*r))},pingpong:function(e,t=1){return t-Math.abs(un(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&&(rn=e);let t=rn+=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*sn},radToDeg:function(e){return e*an},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:Qt("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+i)}},normalize:dn,denormalize:hn};class fn{constructor(e=0,t=0){fn.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=ln(this.x,e.x,t.x),this.y=ln(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=ln(this.x,e,t),this.y=ln(this.y,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(ln(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(ln(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 mn{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],h=i[s+0],d=i[s+1],p=i[s+2],f=i[s+3];if(a<=0)return e[t+0]=o,e[t+1]=l,e[t+2]=u,void(e[t+3]=c);if(a>=1)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=o*h+l*d+u*p+c*f;e<0&&(h=-h,d=-d,p=-p,f=-f,e=-e);let t=1-a;if(e<.9995){const n=Math.acos(e),r=Math.sin(n);t=Math.sin(t*n)/r,o=o*t+h*(a=Math.sin(a*n)/r),l=l*t+d*a,u=u*t+p*a,c=c*t+f*a}else{o=o*t+h*a,l=l*t+d*a,u=u*t+p*a,c=c*t+f*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:Qt("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(ln(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(t<=0)return this;if(t>=1)return this.copy(e);let n=e._x,r=e._y,i=e._z,s=e._w,a=this.dot(e);a<0&&(n=-n,r=-r,i=-i,s=-s,a=-a);let o=1-t;if(a<.9995){const e=Math.acos(a),l=Math.sin(e);o=Math.sin(o*e)/l,t=Math.sin(t*e)/l,this._x=this._x*o+n*t,this._y=this._y*o+r*t,this._z=this._z*o+i*t,this._w=this._w*o+s*t,this._onChangeCallback()}else this._x=this._x*o+n*t,this._y=this._y*o+r*t,this._z=this._z*o+i*t,this._w=this._w*o+s*t,this.normalize();return 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 gn{constructor(e=0,t=0,n=0){gn.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(vn.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(vn.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=ln(this.x,e.x,t.x),this.y=ln(this.y,e.y,t.y),this.z=ln(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=ln(this.x,e,t),this.y=ln(this.y,e,t),this.z=ln(this.z,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(ln(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 _n.copy(this).projectOnVector(e),this.sub(_n)}reflect(e){return this.sub(_n.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(ln(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 _n=new gn,vn=new mn;class yn{constructor(e,t,n,r,i,s,a,o,l){yn.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],b=r[2],x=r[5],T=r[8];return i[0]=s*f+a*_+o*b,i[3]=s*m+a*v+o*x,i[6]=s*g+a*y+o*T,i[1]=l*f+u*_+c*b,i[4]=l*m+u*v+c*x,i[7]=l*g+u*y+c*T,i[2]=h*f+d*_+p*b,i[5]=h*m+d*v+p*x,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(bn.makeScale(e,t)),this}rotate(e){return this.premultiply(bn.makeRotation(-e)),this}translate(e,t){return this.premultiply(bn.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 bn=new yn,xn=(new yn).set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),Tn=(new yn).set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function Sn(){const e={enabled:!0,workingColorSpace:At,spaces:{},convert:function(e,t,n){return!1!==this.enabled&&t!==n&&t&&n?(this.spaces[t].transfer===Ct&&(e.r=wn(e.r),e.g=wn(e.g),e.b=wn(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===Ct&&(e.r=En(e.r),e.g=En(e.g),e.b=En(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===wt?Rt:this.spaces[e].transfer},getToneMappingMode:function(e){return this.spaces[e].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(e,t=this.workingColorSpace){return e.fromArray(this.spaces[t].luminanceCoefficients)},define:function(e){Object.assign(this.spaces,e)},_getMatrix:function(e,t,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 en("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),e.workingToColorSpace(t,n)},toWorkingColorSpace:function(t,n){return en("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({[At]:{primaries:t,whitePoint:r,transfer:Rt,toXYZ:xn,fromXYZ:Tn,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:Et},outputColorSpaceConfig:{drawingBufferColorSpace:Et}},[Et]:{primaries:t,whitePoint:r,transfer:Ct,toXYZ:xn,fromXYZ:Tn,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:Et}}}),e}const Mn=Sn();function wn(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}function En(e){return e<.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}let An;class Rn{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===An&&(An=qt("canvas")),An.width=e.width,An.height=e.height;const t=An.getContext("2d");e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),n=An}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=qt("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;e1),this.pmremVersion=0}get width(){return this.source.getSize(Dn).x}get height(){return this.source.getSize(Dn).y}get depth(){return this.source.getSize(Dn).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){Qt(`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:Qt(`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 he:e.x=e.x-Math.floor(e.x);break;case de:e.x=e.x<0?0:1;break;case pe: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 he:e.y=e.y-Math.floor(e.y);break;case de:e.y=e.y<0?0:1;break;case pe: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++}}In.DEFAULT_IMAGE=null,In.DEFAULT_MAPPING=300,In.DEFAULT_ANISOTROPY=1;class Un{constructor(e=0,t=0,n=0,r=1){Un.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)o&&e>_?e_?o1);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=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,Gn),Gn.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(Kn),Zn.subVectors(this.max,Kn),jn.subVectors(e.a,Kn),Wn.subVectors(e.b,Kn),$n.subVectors(e.c,Kn),Xn.subVectors(Wn,jn),qn.subVectors($n,Wn),Yn.subVectors(jn,$n);let t=[0,-Xn.z,Xn.y,0,-qn.z,qn.y,0,-Yn.z,Yn.y,Xn.z,0,-Xn.x,qn.z,0,-qn.x,Yn.z,0,-Yn.x,-Xn.y,Xn.x,0,-qn.y,qn.x,0,-Yn.y,Yn.x,0];return!!er(t,jn,Wn,$n,Zn)&&(t=[1,0,0,0,1,0,0,0,1],!!er(t,jn,Wn,$n,Zn)&&(Qn.crossVectors(Xn,qn),t=[Qn.x,Qn.y,Qn.z],er(t,jn,Wn,$n,Zn)))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Gn).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=.5*this.getSize(Gn).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()||(Vn[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Vn[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Vn[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Vn[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Vn[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Vn[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Vn[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Vn[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Vn)),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 Vn=[new gn,new gn,new gn,new gn,new gn,new gn,new gn,new gn],Gn=new gn,Hn=new zn,jn=new gn,Wn=new gn,$n=new gn,Xn=new gn,qn=new gn,Yn=new gn,Kn=new gn,Zn=new gn,Qn=new gn,Jn=new gn;function er(e,t,n,r,i){for(let s=0,a=e.length-3;s<=a;s+=3){Jn.fromArray(e,s);const a=i.x*Math.abs(Jn.x)+i.y*Math.abs(Jn.y)+i.z*Math.abs(Jn.z),o=t.dot(Jn),l=n.dot(Jn),u=r.dot(Jn);if(Math.max(-Math.max(o,l,u),Math.min(o,l,u))>a)return!1}return!0}const tr=new zn,nr=new gn,rr=new gn;class ir{constructor(e=new gn,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):tr.setFromPoints(e).getCenter(n);let r=0;for(let t=0,i=e.length;tthis.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;nr.subVectors(e,this.center);const t=nr.lengthSq();if(t>this.radius*this.radius){const e=Math.sqrt(t),n=.5*(e-this.radius);this.center.addScaledVector(nr,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):(rr.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(nr.copy(e.center).add(rr)),this.expandByPoint(nr.copy(e.center).sub(rr))),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 sr=new gn,ar=new gn,or=new gn,lr=new gn,ur=new gn,cr=new gn,hr=new gn;class dr{constructor(e=new gn,t=new gn(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,sr)),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=sr.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(sr.copy(this.origin).addScaledVector(this.direction,t),sr.distanceToSquared(e))}distanceSqToSegment(e,t,n,r){ar.copy(e).add(t).multiplyScalar(.5),or.copy(t).sub(e).normalize(),lr.copy(this.origin).sub(ar);const i=.5*e.distanceTo(t),s=-this.direction.dot(or),a=lr.dot(this.direction),o=-lr.dot(or),l=lr.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(ar).addScaledVector(or,h),d}intersectSphere(e,t){sr.subVectors(e.center,this.origin);const n=sr.dot(this.direction),r=sr.dot(sr)-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=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=0?n:r,t)))}intersectsBox(e){return null!==this.intersectBox(e,sr)}intersectTriangle(e,t,n,r,i){ur.subVectors(t,e),cr.subVectors(n,e),hr.crossVectors(ur,cr);let s,a=this.direction.dot(hr);if(a>0){if(r)return null;s=1}else{if(!(a<0))return null;s=-1,a=-a}lr.subVectors(this.origin,e);const o=s*this.direction.dot(cr.crossVectors(lr,cr));if(o<0)return null;const l=s*this.direction.dot(ur.cross(lr));if(l<0)return null;if(o+l>a)return null;const u=-s*lr.dot(hr);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 pr{constructor(e,t,n,r,i,s,a,o,l,u,c,h,d,p,f,m){pr.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 pr).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 0===this.determinant()?(e.set(1,0,0),t.set(0,1,0),n.set(0,0,1),this):(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){if(0===e.determinant())return this.identity();const t=this.elements,n=e.elements,r=1/fr.setFromMatrixColumn(e,0).length(),i=1/fr.setFromMatrixColumn(e,1).length(),s=1/fr.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(gr,e,_r)}lookAt(e,t,n){const r=this.elements;return br.subVectors(e,t),0===br.lengthSq()&&(br.z=1),br.normalize(),vr.crossVectors(n,br),0===vr.lengthSq()&&(1===Math.abs(n.z)?br.x+=1e-4:br.z+=1e-4,br.normalize(),vr.crossVectors(n,br)),vr.normalize(),yr.crossVectors(br,vr),r[0]=vr.x,r[4]=yr.x,r[8]=br.x,r[1]=vr.y,r[5]=yr.y,r[9]=br.y,r[2]=vr.z,r[6]=yr.z,r[10]=br.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],b=n[15],x=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*x+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*x+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*x+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]=_*x+v*w+y*C+b*D,i[7]=_*T+v*E+y*N+b*I,i[11]=_*S+v*A+y*P+b*U,i[15]=_*M+v*R+y*L+b*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],p=e[3],f=e[7],m=e[11],g=e[15],_=o*d-l*h,v=a*d-l*c,y=a*h-o*c,b=s*d-l*u,x=s*h-o*u,T=s*c-a*u;return t*(f*_-m*v+g*y)-n*(p*_-m*b+g*x)+r*(p*v-f*b+g*T)-i*(p*y-f*x+m*T)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,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,b=p*c*o-u*f*o-p*a*h+s*f*h+u*a*m-s*c*m,x=t*_+n*v+r*y+i*b;if(0===x)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const T=1/x;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]=b*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,b=n.x,x=n.y,T=n.z;return r[0]=(1-(f+g))*b,r[1]=(d+y)*b,r[2]=(p-v)*b,r[3]=0,r[4]=(d-y)*x,r[5]=(1-(h+g))*x,r[6]=(m+_)*x,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;if(e.x=r[12],e.y=r[13],e.z=r[14],0===this.determinant())return n.set(1,1,1),t.identity(),this;let i=fr.set(r[0],r[1],r[2]).length();const s=fr.set(r[4],r[5],r[6]).length(),a=fr.set(r[8],r[9],r[10]).length();this.determinant()<0&&(i=-i),mr.copy(this);const o=1/i,l=1/s,u=1/a;return mr.elements[0]*=o,mr.elements[1]*=o,mr.elements[2]*=o,mr.elements[4]*=l,mr.elements[5]*=l,mr.elements[6]*=l,mr.elements[8]*=u,mr.elements[9]*=u,mr.elements[10]*=u,t.setFromRotationMatrix(mr),n.x=i,n.y=s,n.z=a,this}makePerspective(e,t,n,r,i,s,a=2e3,o=!1){const l=this.elements,u=2*i/(t-e),c=2*i/(n-r),h=(t+e)/(t-e),d=(n+r)/(n-r);let p,f;if(o)p=i/(s-i),f=s*i/(s-i);else if(a===Gt)p=-(s+i)/(s-i),f=-2*s*i/(s-i);else{if(a!==Ht)throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);p=-s/(s-i),f=-s*i/(s-i)}return l[0]=u,l[4]=0,l[8]=h,l[12]=0,l[1]=0,l[5]=c,l[9]=d,l[13]=0,l[2]=0,l[6]=0,l[10]=p,l[14]=f,l[3]=0,l[7]=0,l[11]=-1,l[15]=0,this}makeOrthographic(e,t,n,r,i,s,a=2e3,o=!1){const l=this.elements,u=2/(t-e),c=2/(n-r),h=-(t+e)/(t-e),d=-(n+r)/(n-r);let p,f;if(o)p=1/(s-i),f=s/(s-i);else if(a===Gt)p=-2/(s-i),f=-(s+i)/(s-i);else{if(a!==Ht)throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);p=-1/(s-i),f=-i/(s-i)}return l[0]=u,l[4]=0,l[8]=0,l[12]=h,l[1]=0,l[5]=c,l[9]=0,l[13]=d,l[2]=0,l[6]=0,l[10]=p,l[14]=f,l[3]=0,l[7]=0,l[11]=0,l[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 fr=new gn,mr=new pr,gr=new gn(0,0,0),_r=new gn(1,1,1),vr=new gn,yr=new gn,br=new gn,xr=new pr,Tr=new mn;class Sr{constructor(e=0,t=0,n=0,r=Sr.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(ln(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(-ln(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(ln(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(-ln(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(ln(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(-ln(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:Qt("Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,!0===n&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return xr.makeRotationFromQuaternion(e),this.setFromRotationMatrix(xr,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return Tr.setFromEuler(this),this.setFromQuaternion(Tr,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}}Sr.DEFAULT_ORDER="XYZ";class Mr{constructor(){this.mask=1}set(e){this.mask=1<>>0}enable(e){this.mask|=1<1){for(let e=0;e1){for(let e=0;e0&&(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;t0){r.children=[];for(let t=0;t0){r.animations=[];for(let t=0;t0&&(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;t0?r.multiplyScalar(1/Math.sqrt(i)):r.set(0,0,0)}static getBarycoord(e,t,n,r,i){Vr.subVectors(r,t),Gr.subVectors(n,t),Hr.subVectors(e,t);const s=Vr.dot(Vr),a=Vr.dot(Gr),o=Vr.dot(Hr),l=Gr.dot(Gr),u=Gr.dot(Hr),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,jr)&&(jr.x>=0&&jr.y>=0&&jr.x+jr.y<=1)}static getInterpolation(e,t,n,r,i,s,a,o){return null===this.getBarycoord(e,t,n,r,jr)?(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,jr.x),o.addScaledVector(s,jr.y),o.addScaledVector(a,jr.z),o)}static getInterpolatedAttribute(e,t,n,r,i,s){return Zr.setScalar(0),Qr.setScalar(0),Jr.setScalar(0),Zr.fromBufferAttribute(e,t),Qr.fromBufferAttribute(e,n),Jr.fromBufferAttribute(e,r),s.setScalar(0),s.addScaledVector(Zr,i.x),s.addScaledVector(Qr,i.y),s.addScaledVector(Jr,i.z),s}static isFrontFacing(e,t,n,r){return Vr.subVectors(n,t),Gr.subVectors(e,t),Vr.cross(Gr).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 Vr.subVectors(this.c,this.b),Gr.subVectors(this.a,this.b),.5*Vr.cross(Gr).length()}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return ei.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return ei.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,r,i){return ei.getInterpolation(e,this.a,this.b,this.c,t,n,r,i)}containsPoint(e){return ei.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return ei.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;Wr.subVectors(r,n),$r.subVectors(i,n),qr.subVectors(e,n);const o=Wr.dot(qr),l=$r.dot(qr);if(o<=0&&l<=0)return t.copy(n);Yr.subVectors(e,r);const u=Wr.dot(Yr),c=$r.dot(Yr);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(Wr,s);Kr.subVectors(e,i);const d=Wr.dot(Kr),p=$r.dot(Kr);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 Xr.subVectors(i,r),a=(c-u)/(c-u+(d-p)),t.copy(r).addScaledVector(Xr,a);const g=1/(m+f+h);return s=f*g,a=h*g,t.copy(n).addScaledVector(Wr,s).addScaledVector($r,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const ti={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},ni={h:0,s:0,l:0},ri={h:0,s:0,l:0};function ii(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 si{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=Et){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(255&e)/255,Mn.colorSpaceToWorking(this,t),this}setRGB(e,t,n,r=Mn.workingColorSpace){return this.r=e,this.g=t,this.b=n,Mn.colorSpaceToWorking(this,r),this}setHSL(e,t,n,r=Mn.workingColorSpace){if(e=un(e,1),t=ln(t,0,1),n=ln(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=ii(i,r,e+1/3),this.g=ii(i,r,e),this.b=ii(i,r,e-1/3)}return Mn.colorSpaceToWorking(this,r),this}setStyle(e,t=Et){function n(t){void 0!==t&&parseFloat(t)<1&&Qt("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:Qt("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);Qt("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Et){const n=ti[e.toLowerCase()];return void 0!==n?this.setHex(n,t):Qt("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=wn(e.r),this.g=wn(e.g),this.b=wn(e.b),this}copyLinearToSRGB(e){return this.r=En(e.r),this.g=En(e.g),this.b=En(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Et){return Mn.workingToColorSpace(ai.copy(this),e),65536*Math.round(ln(255*ai.r,0,255))+256*Math.round(ln(255*ai.g,0,255))+Math.round(ln(255*ai.b,0,255))}getHexString(e=Et){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Mn.workingColorSpace){Mn.workingToColorSpace(ai.copy(this),t);const n=ai.r,r=ai.g,i=ai.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+(r0!=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){Qt(`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:Qt(`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()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),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!==P&&(n.blendSrc=this.blendSrc),this.blendDst!==L&&(n.blendDst=this.blendDst),this.blendEquation!==M&&(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!==Nt&&(n.stencilFail=this.stencilFail),this.stencilZFail!==Nt&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==Nt&&(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),!1===this.allowOverride&&(n.allowOverride=!1),!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.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){!0===e&&this.version++}}class ui extends li{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new si(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 Sr,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 ci=hi();function hi(){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 di(e){Math.abs(e)>65504&&Qt("DataUtils.toHalfFloat(): Value out of range."),e=ln(e,-65504,65504),ci.floatView[0]=e;const t=ci.uint32View[0],n=t>>23&511;return ci.baseTable[n]+((8388607&t)>>ci.shiftTable[n])}function pi(e){const t=e>>10;return ci.uint32View[0]=ci.mantissaTable[ci.offsetTable[t]+(1023&e)]+ci.exponentTable[t],ci.floatView[0]}const fi=new gn,mi=new fn;let gi=0;class _i{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:gi++}),this.name="",this.array=e,this.itemSize=t,this.count=void 0!==e?e.length/t:0,this.normalized=n,this.usage=kt,this.updateRanges=[],this.gpuType=Ee,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;rt.count&&Qt("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 zn);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return Jt("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),void this.boundingBox.set(new gn(-1/0,-1/0,-1/0),new gn(1/0,1/0,1/0));if(void 0!==e){if(this.boundingBox.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e0&&(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;t0&&(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;e0){const n=e[t[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e(e.far-e.near)**2)return}Ni.copy(i).invert(),Pi.copy(e.ray).applyMatrix4(Ni),null!==n.boundingBox&&!1===Pi.intersectsBox(n.boundingBox)||this._computeIntersections(e,t,Pi)}}_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;in.far?null:{distance:u,point:zi.clone(),object:e}}(e,t,n,r,Ii,Ui,Oi,ki);if(c){const e=new gn;ei.getBarycoord(ki,Ii,Ui,Oi,e),i&&(c.uv=ei.getInterpolatedAttribute(i,o,l,u,e,new fn)),s&&(c.uv1=ei.getInterpolatedAttribute(s,o,l,u,e,new fn)),a&&(c.normal=ei.getInterpolatedAttribute(a,o,l,u,e,new gn),c.normal.dot(r.direction)>0&&c.normal.multiplyScalar(-1));const t={a:o,b:l,c:u,normal:new gn,materialIndex:0};ei.getNormal(Ii,Ui,Oi,t.normal),c.face=t,c.barycoord=e}return c}class Hi extends Ci{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,b=s/2,x=p/2,T=f/2,S=m+1,M=g+1;let w=0,E=0;const A=new gn;for(let s=0;s0?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;e0&&(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 Yi extends zr{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new pr,this.projectionMatrix=new pr,this.projectionMatrixInverse=new pr,this.coordinateSystem=Gt,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return(new this.constructor).copy(this)}}const Ki=new gn,Zi=new fn,Qi=new fn;class Ji extends Yi{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*an*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(.5*sn*this.fov);return.5*this.getFilmHeight()/e}getEffectiveFOV(){return 2*an*Math.atan(Math.tan(.5*sn*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){Ki.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Ki.x,Ki.y).multiplyScalar(-e/Ki.z),Ki.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(Ki.x,Ki.y).multiplyScalar(-e/Ki.z)}getViewSize(e,t){return this.getViewBounds(e,Zi,Qi),t.subVectors(Qi,Zi)}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*sn*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.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,null!==this.view&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const es=-90;class ts extends zr{constructor(e,t,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;const r=new Ji(es,1,e,t);r.layers=this.layers,this.add(r);const i=new Ji(es,1,e,t);i.layers=this.layers,this.add(i);const s=new Ji(es,1,e,t);s.layers=this.layers,this.add(s);const a=new Ji(es,1,e,t);a.layers=this.layers,this.add(a);const o=new Ji(es,1,e,t);o.layers=this.layers,this.add(o);const l=new Ji(es,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===Gt)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!==Ht)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 ns extends In{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 rs extends Fn{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 ns(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 \n\t\t\t\t\t#include \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 \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 Hi(5,5,5),i=new qi({name:"CubemapFromEquirect",uniforms:ji(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:1,blending:0});i.uniforms.tEquirect.value=t;const s=new Vi(r,i),a=t.minFilter;t.minFilter===ye&&(t.minFilter=_e);return new ts(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 is=class extends zr{constructor(){super(),this.isGroup=!0,this.type="Group"}};const ss={type:"move"};class as{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return null===this._hand&&(this._hand=new is,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 is,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new gn,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new gn),this._targetRay}getGripSpace(){return null===this._grip&&(this._grip=new is,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new gn,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new gn),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(ss)))}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 is;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}}class os extends zr{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 Sr,this.environmentIntensity=1,this.environmentRotation=new Sr,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 ls{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=void 0!==e?e.length/t:0,this.usage=kt,this.updateRanges=[],this.version=0,this.uuid=on()}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;r1?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||gs.getNormalMatrix(e),r=this.coplanarPoint(fs).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 vs=new ir,ys=new fn(.5,.5),bs=new gn;class xs{constructor(e=new _s,t=new _s,n=new _s,r=new _s,i=new _s,s=new _s){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,n=!1){const r=this.planes,i=e.elements,s=i[0],a=i[1],o=i[2],l=i[3],u=i[4],c=i[5],h=i[6],d=i[7],p=i[8],f=i[9],m=i[10],g=i[11],_=i[12],v=i[13],y=i[14],b=i[15];if(r[0].setComponents(l-s,d-u,g-p,b-_).normalize(),r[1].setComponents(l+s,d+u,g+p,b+_).normalize(),r[2].setComponents(l+a,d+c,g+f,b+v).normalize(),r[3].setComponents(l-a,d-c,g-f,b-v).normalize(),n)r[4].setComponents(o,h,m,y).normalize(),r[5].setComponents(l-o,d-h,g-m,b-y).normalize();else if(r[4].setComponents(l-o,d-h,g-m,b-y).normalize(),t===Gt)r[5].setComponents(l+o,d+h,g+m,b+y).normalize();else{if(t!==Ht)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);r[5].setComponents(o,h,m,y).normalize()}return this}intersectsObject(e){if(void 0!==e.boundingSphere)null===e.boundingSphere&&e.computeBoundingSphere(),vs.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;null===t.boundingSphere&&t.computeBoundingSphere(),vs.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(vs)}intersectsSprite(e){vs.center.set(0,0,0);const t=ys.distanceTo(e.center);return vs.radius=.7071067811865476+t,vs.applyMatrix4(e.matrixWorld),this.intersectsSphere(vs)}intersectsSphere(e){const t=this.planes,n=e.center,r=-e.radius;for(let e=0;e<6;e++){if(t[e].distanceToPoint(n)0?e.max.x:e.min.x,bs.y=r.normal.y>0?e.max.y:e.min.y,bs.z=r.normal.z>0?e.max.z:e.min.z,r.distanceToPoint(bs)<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 Ts=new pr,Ss=new xs;class Ms{constructor(){this.coordinateSystem=Gt}intersectsObject(e,t){if(!t.isArrayCamera||0===t.cameras.length)return!1;for(let n=0;nr)return;Ps.applyMatrix4(e.matrixWorld);const l=t.ray.origin.distanceTo(Ps);return lt.far?void 0:{distance:l,point:Ls.clone().applyMatrix4(e.matrixWorld),index:a,face:null,faceIndex:null,barycoord:null,object:e}}class Is extends li{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new si(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 Us extends In{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=fe,this.minFilter=fe,this.generateMipmaps=!1,this.needsUpdate=!0}}class Os extends In{constructor(e,t,n=1014,r,i,s,a=1003,o=1003,l,u=1026,c=1){if(u!==Oe&&u!==Fe)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 Nn(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 Fs extends Os{constructor(e,t=1014,n=301,r,i,s=1003,a=1003,o,l=1026){const u={width:e,height:e,depth:1},c=[u,u,u,u,u,u];super(e,e,t,n,r,i,s,a,o,l),this.image=c,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}}class Bs extends In{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}class ks extends Ci{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 fn,f=new gn;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 b=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;e0||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 xi(c,3)),this.setAttribute("normal",new xi(h,3)),this.setAttribute("uv",new xi(d,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new ks(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class zs extends ks{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 zs(e.radius,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class Vs{constructor(){this.type="Curve",this.arcLengthDivisions=200,this.needsUpdate=!1,this.cacheArcLengths=null}getPoint(){Qt("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 fn:new gn);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 gn,r=[],i=[],s=[],a=new gn,o=new pr;for(let t=0;t<=e;t++){const n=t/e;r[t]=this.getTangentAt(n,new gn)}i[0]=new gn,s[0]=new gn;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(ln(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(ln(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 Gs extends Vs{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 fn){const n=t,r=2*Math.PI;let i=this.aEndAngle-this.aStartAngle;const s=Math.abs(i)r;)i-=r;i0?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]:(js.subVectors(r[0],r[1]).add(r[0]),a=js);const c=r[l%i],h=r[(l+1)%i];if(this.closed||l+2r.length-2?r.length-1:s+1],c=r[s>r.length-3?r.length-1:s+2];return n.set(qs(a,o.x,l.x,u.x,c.x),qs(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;t0)&&d.push(t,i,l),(e!==n-1||o0!=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 oa extends li{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new si(16777215),this.specular=new si(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new si(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new fn(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Sr,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 la extends li{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new si(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new si(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new fn(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 ua extends li{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new fn(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 ca extends li{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new si(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new si(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new fn(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Sr,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 ha extends li{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 da extends li{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 pa extends li{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new si(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new fn(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={MATCAP:""},this.color.copy(e.color),this.matcap=e.matcap,this.map=e.map,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this.fog=e.fog,this}}class fa extends ws{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 ma={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 ga{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._abortController=null,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;te.start-t.start);let t=0;for(let e=1;e 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}\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#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, pow4( 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;\nmaterial.diffuseContribution = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.metalness = 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 = min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor;\n\tmaterial.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = vec3( 0.04 );\n\tmaterial.specularColorBlended = mix( material.specularColor, 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.0001, 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:"uniform sampler2D dfgLUT;\nstruct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tvec3 diffuseContribution;\n\tvec3 specularColor;\n\tvec3 specularColorBlended;\n\tfloat roughness;\n\tfloat metalness;\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\tvec3 iridescenceFresnelDielectric;\n\t\tvec3 iridescenceFresnelMetallic;\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 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.specularColorBlended;\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 * transpose( 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 rInv = 1.0 / ( roughness + 0.1 );\n\tfloat a = -1.9362 + 1.0678 * roughness + 0.4573 * r2 - 0.8469 * rInv;\n\tfloat b = -0.6014 + 0.5538 * roughness - 0.4670 * r2 - 0.1255 * rInv;\n\tfloat DG = exp( a * dotNV + b );\n\treturn saturate( DG );\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg;\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\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg;\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}\nvec3 BRDF_GGX_Multiscatter( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 singleScatter = BRDF_GGX( lightDir, viewDir, normal, material );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 dfgV = texture2D( dfgLUT, vec2( material.roughness, dotNV ) ).rg;\n\tvec2 dfgL = texture2D( dfgLUT, vec2( material.roughness, dotNL ) ).rg;\n\tvec3 FssEss_V = material.specularColorBlended * dfgV.x + material.specularF90 * dfgV.y;\n\tvec3 FssEss_L = material.specularColorBlended * dfgL.x + material.specularF90 * dfgL.y;\n\tfloat Ess_V = dfgV.x + dfgV.y;\n\tfloat Ess_L = dfgL.x + dfgL.y;\n\tfloat Ems_V = 1.0 - Ess_V;\n\tfloat Ems_L = 1.0 - Ess_L;\n\tvec3 Favg = material.specularColorBlended + ( 1.0 - material.specularColorBlended ) * 0.047619;\n\tvec3 Fms = FssEss_V * FssEss_L * Favg / ( 1.0 - Ems_V * Ems_L * Favg + EPSILON );\n\tfloat compensationFactor = Ems_V * Ems_L;\n\tvec3 multiScatter = Fms * compensationFactor;\n\treturn singleScatter + multiScatter;\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.specularColorBlended * t2.x + ( vec3( 1.0 ) - material.specularColorBlended ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseContribution * 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 \n \t\tsheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n \n \t\tfloat sheenAlbedoV = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n \t\tfloat sheenAlbedoL = IBLSheenBRDF( geometryNormal, directLight.direction, material.sheenRoughness );\n \n \t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * max( sheenAlbedoV, sheenAlbedoL );\n \n \t\tirradiance *= sheenEnergyComp;\n \n \t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX_Multiscatter( directLight.direction, geometryViewDir, geometryNormal, material );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseContribution );\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\tvec3 diffuse = irradiance * BRDF_Lambert( material.diffuseContribution );\n\t#ifdef USE_SHEEN\n\t\tfloat sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;\n\t\tdiffuse *= sheenEnergyComp;\n\t#endif\n\treflectedLight.indirectDiffuse += diffuse;\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 ) * RECIPROCAL_PI;\n \t#endif\n\tvec3 singleScatteringDielectric = vec3( 0.0 );\n\tvec3 multiScatteringDielectric = vec3( 0.0 );\n\tvec3 singleScatteringMetallic = vec3( 0.0 );\n\tvec3 multiScatteringMetallic = vec3( 0.0 );\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnelDielectric, material.roughness, singleScatteringDielectric, multiScatteringDielectric );\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.iridescence, material.iridescenceFresnelMetallic, material.roughness, singleScatteringMetallic, multiScatteringMetallic );\n\t#else\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScatteringDielectric, multiScatteringDielectric );\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.roughness, singleScatteringMetallic, multiScatteringMetallic );\n\t#endif\n\tvec3 singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, material.metalness );\n\tvec3 multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, material.metalness );\n\tvec3 totalScatteringDielectric = singleScatteringDielectric + multiScatteringDielectric;\n\tvec3 diffuse = material.diffuseContribution * ( 1.0 - totalScatteringDielectric );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tvec3 indirectSpecular = radiance * singleScattering;\n\tindirectSpecular += multiScattering * cosineWeightedIrradiance;\n\tvec3 indirectDiffuse = diffuse * cosineWeightedIrradiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;\n\t\tindirectSpecular *= sheenEnergyComp;\n\t\tindirectDiffuse *= sheenEnergyComp;\n\t#endif\n\treflectedLight.indirectSpecular += indirectSpecular;\n\treflectedLight.indirectDiffuse += indirectDiffuse;\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.iridescenceFresnelDielectric = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceFresnelMetallic = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.diffuseColor );\n\t\tmaterial.iridescenceFresnel = mix( material.iridescenceFresnelDielectric, material.iridescenceFresnelMetallic, material.metalness );\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 ) && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )\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_LOGARITHMIC_DEPTH_BUFFER )\n\tgl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_pars_vertex:"#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\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\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform sampler2DShadow directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\t#else\n\t\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\t#endif\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\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform sampler2DShadow spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\t#else\n\t\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\t#endif\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\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform samplerCubeShadow pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\t#elif defined( SHADOWMAP_TYPE_BASIC )\n\t\t\tuniform samplerCube pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\t#endif\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\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\tfloat interleavedGradientNoise( vec2 position ) {\n\t\t\treturn fract( 52.9829189 * fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) );\n\t\t}\n\t\tvec2 vogelDiskSample( int sampleIndex, int samplesCount, float phi ) {\n\t\t\tconst float goldenAngle = 2.399963229728653;\n\t\t\tfloat r = sqrt( ( float( sampleIndex ) + 0.5 ) / float( samplesCount ) );\n\t\t\tfloat theta = float( sampleIndex ) * goldenAngle + phi;\n\t\t\treturn vec2( cos( theta ), sin( theta ) ) * r;\n\t\t}\n\t#endif\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\tfloat getShadow( sampler2DShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\tshadowCoord.z += shadowBias;\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\t\tfloat radius = shadowRadius * texelSize.x;\n\t\t\t\tfloat phi = interleavedGradientNoise( gl_FragCoord.xy ) * 6.28318530718;\n\t\t\t\tshadow = (\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 0, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 1, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 2, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 3, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 4, 5, phi ) * radius, shadowCoord.z ) )\n\t\t\t\t) * 0.2;\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\tshadowCoord.z += shadowBias;\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tvec2 distribution = texture2D( shadowMap, shadowCoord.xy ).rg;\n\t\t\t\tfloat mean = distribution.x;\n\t\t\t\tfloat variance = distribution.y * distribution.y;\n\t\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\t\tfloat hard_shadow = step( mean, shadowCoord.z );\n\t\t\t\t#else\n\t\t\t\t\tfloat hard_shadow = step( shadowCoord.z, mean );\n\t\t\t\t#endif\n\t\t\t\tif ( hard_shadow == 1.0 ) {\n\t\t\t\t\tshadow = 1.0;\n\t\t\t\t} else {\n\t\t\t\t\tvariance = max( variance, 0.0000001 );\n\t\t\t\t\tfloat d = shadowCoord.z - mean;\n\t\t\t\t\tfloat p_max = variance / ( variance + d * d );\n\t\t\t\t\tp_max = clamp( ( p_max - 0.3 ) / 0.65, 0.0, 1.0 );\n\t\t\t\t\tshadow = max( hard_shadow, p_max );\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#else\n\t\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\tshadowCoord.z += shadowBias;\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tfloat depth = texture2D( shadowMap, shadowCoord.xy ).r;\n\t\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\t\tshadow = step( depth, shadowCoord.z );\n\t\t\t\t#else\n\t\t\t\t\tshadow = step( shadowCoord.z, depth );\n\t\t\t\t#endif\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\tfloat getPointShadow( samplerCubeShadow 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\tvec3 bd3D = normalize( lightToPosition );\n\t\tvec3 absVec = abs( lightToPosition );\n\t\tfloat viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );\n\t\tif ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\tdp += shadowBias;\n\t\t\tfloat texelSize = shadowRadius / shadowMapSize.x;\n\t\t\tvec3 absDir = abs( bd3D );\n\t\t\tvec3 tangent = absDir.x > absDir.z ? vec3( 0.0, 1.0, 0.0 ) : vec3( 1.0, 0.0, 0.0 );\n\t\t\ttangent = normalize( cross( bd3D, tangent ) );\n\t\t\tvec3 bitangent = cross( bd3D, tangent );\n\t\t\tfloat phi = interleavedGradientNoise( gl_FragCoord.xy ) * 6.28318530718;\n\t\t\tshadow = (\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * vogelDiskSample( 0, 5, phi ).x + bitangent * vogelDiskSample( 0, 5, phi ).y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * vogelDiskSample( 1, 5, phi ).x + bitangent * vogelDiskSample( 1, 5, phi ).y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * vogelDiskSample( 2, 5, phi ).x + bitangent * vogelDiskSample( 2, 5, phi ).y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * vogelDiskSample( 3, 5, phi ).x + bitangent * vogelDiskSample( 3, 5, phi ).y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * vogelDiskSample( 4, 5, phi ).x + bitangent * vogelDiskSample( 4, 5, phi ).y ) * texelSize, dp ) )\n\t\t\t) * 0.2;\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\t#elif defined( SHADOWMAP_TYPE_BASIC )\n\tfloat getPointShadow( samplerCube 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\tvec3 bd3D = normalize( lightToPosition );\n\t\tvec3 absVec = abs( lightToPosition );\n\t\tfloat viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );\n\t\tif ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\tdp += shadowBias;\n\t\t\tfloat depth = textureCube( shadowMap, bd3D ).r;\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tshadow = step( depth, dp );\n\t\t\t#else\n\t\t\t\tshadow = step( dp, depth );\n\t\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\t#endif\n\t#endif\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 && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )\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.diffuseContribution, material.specularColorBlended, 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 \n\t#include \n}",backgroundCube_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \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 \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 \n\t#include \n}",cube_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \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 \n\t#include \n}",depth_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvHighPrecisionZW = gl_Position.zw;\n}",depth_frag:"#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\tfloat fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ];\n\t#else\n\t\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5;\n\t#endif\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}",distance_vert:"#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition.xyz;\n}",distance_frag:"#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main () {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = vec4( dist, 0.0, 0.0, 1.0 );\n}",equirect_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}",equirect_frag:"uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include \n\t#include \n}",linedashed_vert:"uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",linedashed_frag:"uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshbasic_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshbasic_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \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 \n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshlambert_vert:"#define LAMBERT\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}",meshlambert_frag:"#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshmatcap_vert:"#define MATCAP\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n}",meshmatcap_frag:"#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \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 \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \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 \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_FragColor = vec4( normalize( normal ) * 0.5 + 0.5, 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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}",meshphong_frag:"#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshphysical_vert:"#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include \n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n \n\t\toutgoingLight = outgoingLight + sheenSpecularDirect + sheenSpecularIndirect;\n \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 \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshtoon_vert:"#define TOON\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}",meshtoon_frag:"#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",points_vert:"uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \n#include \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 \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \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 \n\t#include \n\t#include \n\t#include \n}",points_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",shadow_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",shadow_frag:"uniform vec3 color;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include \n\t#include \n\t#include \n}",sprite_vert:"uniform float rotation;\nuniform vec2 center;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \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 \n\t#include \n\t#include \n}",sprite_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n}"},Qa={common:{diffuse:{value:new si(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new yn},alphaMap:{value:null},alphaMapTransform:{value:new yn},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new yn}},envmap:{envMap:{value:null},envMapRotation:{value:new yn},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new yn}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new yn}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new yn},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new yn},normalScale:{value:new fn(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new yn},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new yn}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new yn}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new yn}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new si(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 si(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new yn},alphaTest:{value:0},uvTransform:{value:new yn}},sprite:{diffuse:{value:new si(16777215)},opacity:{value:1},center:{value:new fn(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new yn},alphaMap:{value:null},alphaMapTransform:{value:new yn},alphaTest:{value:0}}},Ja={basic:{uniforms:Wi([Qa.common,Qa.specularmap,Qa.envmap,Qa.aomap,Qa.lightmap,Qa.fog]),vertexShader:Za.meshbasic_vert,fragmentShader:Za.meshbasic_frag},lambert:{uniforms:Wi([Qa.common,Qa.specularmap,Qa.envmap,Qa.aomap,Qa.lightmap,Qa.emissivemap,Qa.bumpmap,Qa.normalmap,Qa.displacementmap,Qa.fog,Qa.lights,{emissive:{value:new si(0)}}]),vertexShader:Za.meshlambert_vert,fragmentShader:Za.meshlambert_frag},phong:{uniforms:Wi([Qa.common,Qa.specularmap,Qa.envmap,Qa.aomap,Qa.lightmap,Qa.emissivemap,Qa.bumpmap,Qa.normalmap,Qa.displacementmap,Qa.fog,Qa.lights,{emissive:{value:new si(0)},specular:{value:new si(1118481)},shininess:{value:30}}]),vertexShader:Za.meshphong_vert,fragmentShader:Za.meshphong_frag},standard:{uniforms:Wi([Qa.common,Qa.envmap,Qa.aomap,Qa.lightmap,Qa.emissivemap,Qa.bumpmap,Qa.normalmap,Qa.displacementmap,Qa.roughnessmap,Qa.metalnessmap,Qa.fog,Qa.lights,{emissive:{value:new si(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Za.meshphysical_vert,fragmentShader:Za.meshphysical_frag},toon:{uniforms:Wi([Qa.common,Qa.aomap,Qa.lightmap,Qa.emissivemap,Qa.bumpmap,Qa.normalmap,Qa.displacementmap,Qa.gradientmap,Qa.fog,Qa.lights,{emissive:{value:new si(0)}}]),vertexShader:Za.meshtoon_vert,fragmentShader:Za.meshtoon_frag},matcap:{uniforms:Wi([Qa.common,Qa.bumpmap,Qa.normalmap,Qa.displacementmap,Qa.fog,{matcap:{value:null}}]),vertexShader:Za.meshmatcap_vert,fragmentShader:Za.meshmatcap_frag},points:{uniforms:Wi([Qa.points,Qa.fog]),vertexShader:Za.points_vert,fragmentShader:Za.points_frag},dashed:{uniforms:Wi([Qa.common,Qa.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Za.linedashed_vert,fragmentShader:Za.linedashed_frag},depth:{uniforms:Wi([Qa.common,Qa.displacementmap]),vertexShader:Za.depth_vert,fragmentShader:Za.depth_frag},normal:{uniforms:Wi([Qa.common,Qa.bumpmap,Qa.normalmap,Qa.displacementmap,{opacity:{value:1}}]),vertexShader:Za.meshnormal_vert,fragmentShader:Za.meshnormal_frag},sprite:{uniforms:Wi([Qa.sprite,Qa.fog]),vertexShader:Za.sprite_vert,fragmentShader:Za.sprite_frag},background:{uniforms:{uvTransform:{value:new yn},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Za.background_vert,fragmentShader:Za.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new yn}},vertexShader:Za.backgroundCube_vert,fragmentShader:Za.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Za.cube_vert,fragmentShader:Za.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Za.equirect_vert,fragmentShader:Za.equirect_frag},distance:{uniforms:Wi([Qa.common,Qa.displacementmap,{referencePosition:{value:new gn},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Za.distance_vert,fragmentShader:Za.distance_frag},shadow:{uniforms:Wi([Qa.lights,Qa.fog,{color:{value:new si(0)},opacity:{value:1}}]),vertexShader:Za.shadow_vert,fragmentShader:Za.shadow_frag}};Ja.physical={uniforms:Wi([Ja.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new yn},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new yn},clearcoatNormalScale:{value:new fn(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new yn},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new yn},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new yn},sheen:{value:0},sheenColor:{value:new si(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new yn},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new yn},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new yn},transmissionSamplerSize:{value:new fn},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new yn},attenuationDistance:{value:0},attenuationColor:{value:new si(0)},specularColor:{value:new si(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new yn},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new yn},anisotropyVector:{value:new fn},anisotropyMap:{value:null},anisotropyMapTransform:{value:new yn}}]),vertexShader:Za.meshphysical_vert,fragmentShader:Za.meshphysical_frag};const eo={r:0,b:0,g:0},to=new Sr,no=new pr;function ro(e,t,n,r,i,s,a){const o=new si(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(eo,$i(e)),r.buffers.color.setClear(eo.r,eo.g,eo.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===ce)?(void 0===u&&(u=new Vi(new Hi(1,1,1),new qi({name:"BackgroundCubeMaterial",uniforms:ji(Ja.backgroundCube.uniforms),vertexShader:Ja.backgroundCube.vertexShader,fragmentShader:Ja.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)),to.copy(n.backgroundRotation),to.x*=-1,to.y*=-1,to.z*=-1,r.isCubeTexture&&!1===r.isRenderTargetTexture&&(to.y*=-1,to.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(no.makeRotationFromEuler(to)),u.material.toneMapped=Mn.getTransfer(r.colorSpace)!==Ct,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 Vi(new ea(2,2),new qi({name:"BackgroundMaterial",uniforms:ji(Ja.background.uniforms),vertexShader:Ja.background.vertexShader,fragmentShader:Ja.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=Mn.getTransfer(r.colorSpace)!==Ct,!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 io(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=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===Me;if(o.isInterleavedBufferAttribute){const t=o.data,l=t.stride,g=o.offset;if(t.isInstancedInterleavedBuffer){for(let e=0;e0&&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&&(Qt("WebGLRenderer:",a,"not supported, using",o,"instead."),a=o);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===Ue||r.convert(t)===e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT)},textureTypeReadable:function(n){const i=n===Ae&&(t.has("EXT_color_buffer_half_float")||t.has("EXT_color_buffer_float"));return!(n!==be&&r.convert(n)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)&&n!==Ee&&!i)},precision:a,logarithmicDepthBuffer:!0===n.logarithmicDepthBuffer,reversedDepthBuffer:!0===n.reversedDepthBuffer&&t.has("EXT_clip_control"),maxTextures:e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),maxVertexTextures:e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS),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),maxSamples:e.getParameter(e.MAX_SAMPLES),samples:e.getParameter(e.SAMPLES)}}function oo(e){const t=this;let n=null,r=0,i=!1,s=!1;const a=new _s,o=new yn,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.length0);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 lo(e){let t=new WeakMap;function n(e,t){return t===le?e.mapping=ae:t===ue&&(e.mapping=oe),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===le||s===ue){if(t.has(i)){return n(t.get(i).texture,i.mapping)}{const s=i.image;if(s&&s.height>0){const a=new rs(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 uo=[.125,.215,.35,.446,.526,.582],co=20,ho=new Pa,po=new si;let fo=null,mo=0,go=0,_o=!1;const vo=new gn;let yo=class{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._backgroundBox=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null}fromScene(e,t=0,n=.1,r=100,i={}){const{size:s=256,position:a=vo}=i;fo=this._renderer.getRenderTarget(),mo=this._renderer.getActiveCubeFace(),go=this._renderer.getActiveMipmapLevel(),_o=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=So(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=To(),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())}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._ggxMaterial&&this._ggxMaterial.dispose(),null!==this._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let e=0;ee-4?o=uo[a-e+4-1]:0===a&&(o=0),n.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;e2?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 b=new Ci;b.setAttribute("position",new _i(_,f)),b.setAttribute("uv",new _i(v,m)),b.setAttribute("faceIndex",new _i(y,g)),r.push(new Vi(b,null)),i>4&&i--}return{lodMeshes:r,sizeLods:t,sigmas:n}}(r)),this._blurMaterial=function(e,t,n){const r=new Float32Array(co),i=new gn(0,1,0),s=new qi({name:"SphericalGaussianBlur",defines:{n:co,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:Mo(),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 \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),this._ggxMaterial=function(e,t,n){const r=new qi({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:256,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:Mo(),fragmentShader:'\n\n\t\t\tprecision highp float;\n\t\t\tprecision highp int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform float roughness;\n\t\t\tuniform float mipInt;\n\n\t\t\t#define ENVMAP_TYPE_CUBE_UV\n\t\t\t#include \n\n\t\t\t#define PI 3.14159265359\n\n\t\t\t// Van der Corput radical inverse\n\t\t\tfloat radicalInverse_VdC(uint bits) {\n\t\t\t\tbits = (bits << 16u) | (bits >> 16u);\n\t\t\t\tbits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);\n\t\t\t\tbits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);\n\t\t\t\tbits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);\n\t\t\t\tbits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);\n\t\t\t\treturn float(bits) * 2.3283064365386963e-10; // / 0x100000000\n\t\t\t}\n\n\t\t\t// Hammersley sequence\n\t\t\tvec2 hammersley(uint i, uint N) {\n\t\t\t\treturn vec2(float(i) / float(N), radicalInverse_VdC(i));\n\t\t\t}\n\n\t\t\t// GGX VNDF importance sampling (Eric Heitz 2018)\n\t\t\t// "Sampling the GGX Distribution of Visible Normals"\n\t\t\t// https://jcgt.org/published/0007/04/01/\n\t\t\tvec3 importanceSampleGGX_VNDF(vec2 Xi, vec3 V, float roughness) {\n\t\t\t\tfloat alpha = roughness * roughness;\n\n\t\t\t\t// Section 3.2: Transform view direction to hemisphere configuration\n\t\t\t\tvec3 Vh = normalize(vec3(alpha * V.x, alpha * V.y, V.z));\n\n\t\t\t\t// Section 4.1: Orthonormal basis\n\t\t\t\tfloat lensq = Vh.x * Vh.x + Vh.y * Vh.y;\n\t\t\t\tvec3 T1 = lensq > 0.0 ? vec3(-Vh.y, Vh.x, 0.0) / sqrt(lensq) : vec3(1.0, 0.0, 0.0);\n\t\t\t\tvec3 T2 = cross(Vh, T1);\n\n\t\t\t\t// Section 4.2: Parameterization of projected area\n\t\t\t\tfloat r = sqrt(Xi.x);\n\t\t\t\tfloat phi = 2.0 * PI * Xi.y;\n\t\t\t\tfloat t1 = r * cos(phi);\n\t\t\t\tfloat t2 = r * sin(phi);\n\t\t\t\tfloat s = 0.5 * (1.0 + Vh.z);\n\t\t\t\tt2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2;\n\n\t\t\t\t// Section 4.3: Reprojection onto hemisphere\n\t\t\t\tvec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * Vh;\n\n\t\t\t\t// Section 3.4: Transform back to ellipsoid configuration\n\t\t\t\treturn normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z)));\n\t\t\t}\n\n\t\t\tvoid main() {\n\t\t\t\tvec3 N = normalize(vOutputDirection);\n\t\t\t\tvec3 V = N; // Assume view direction equals normal for pre-filtering\n\n\t\t\t\tvec3 prefilteredColor = vec3(0.0);\n\t\t\t\tfloat totalWeight = 0.0;\n\n\t\t\t\t// For very low roughness, just sample the environment directly\n\t\t\t\tif (roughness < 0.001) {\n\t\t\t\t\tgl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Tangent space basis for VNDF sampling\n\t\t\t\tvec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);\n\t\t\t\tvec3 tangent = normalize(cross(up, N));\n\t\t\t\tvec3 bitangent = cross(N, tangent);\n\n\t\t\t\tfor(uint i = 0u; i < uint(GGX_SAMPLES); i++) {\n\t\t\t\t\tvec2 Xi = hammersley(i, uint(GGX_SAMPLES));\n\n\t\t\t\t\t// For PMREM, V = N, so in tangent space V is always (0, 0, 1)\n\t\t\t\t\tvec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness);\n\n\t\t\t\t\t// Transform H back to world space\n\t\t\t\t\tvec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z);\n\t\t\t\t\tvec3 L = normalize(2.0 * dot(V, H) * H - V);\n\n\t\t\t\t\tfloat NdotL = max(dot(N, L), 0.0);\n\n\t\t\t\t\tif(NdotL > 0.0) {\n\t\t\t\t\t\t// Sample environment at fixed mip level\n\t\t\t\t\t\t// VNDF importance sampling handles the distribution filtering\n\t\t\t\t\t\tvec3 sampleColor = bilinearCubeUV(envMap, L, mipInt);\n\n\t\t\t\t\t\t// Weight by NdotL for the split-sum approximation\n\t\t\t\t\t\t// VNDF PDF naturally accounts for the visible microfacet distribution\n\t\t\t\t\t\tprefilteredColor += sampleColor * NdotL;\n\t\t\t\t\t\ttotalWeight += NdotL;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (totalWeight > 0.0) {\n\t\t\t\t\tprefilteredColor = prefilteredColor / totalWeight;\n\t\t\t\t}\n\n\t\t\t\tgl_FragColor = vec4(prefilteredColor, 1.0);\n\t\t\t}\n\t\t',blending:0,depthTest:!1,depthWrite:!1});return r}(r,e,t)}return r}_compileMaterial(e){const t=new Vi(new Ci,e);this._renderer.compile(t,ho)}_sceneToCubeUV(e,t,n,r,i){const s=new Ji(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(po),l.toneMapping=0,l.autoClear=!1;l.state.buffers.depth.getReversed()&&(l.setRenderTarget(r),l.clearDepth(),l.setRenderTarget(null)),null===this._backgroundBox&&(this._backgroundBox=new Vi(new Hi,new ui({name:"PMREM.Background",side:1,depthWrite:!1,depthTest:!1})));const h=this._backgroundBox,d=h.material;let p=!1;const f=e.background;f?f.isColor&&(d.color.copy(f),e.background=null,p=!0):(d.color.copy(po),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;xo(r,n*u,t>2?u:0,u,u),l.setRenderTarget(r),p&&l.render(h,s),l.render(e,s)}l.toneMapping=c,l.autoClear=u,e.background=f}_textureToCubeUV(e,t){const n=this._renderer,r=e.mapping===ae||e.mapping===oe;r?(null===this._cubemapMaterial&&(this._cubemapMaterial=So()),this._cubemapMaterial.uniforms.flipEnvMap.value=!1===e.isRenderTargetTexture?-1:1):null===this._equirectMaterial&&(this._equirectMaterial=To());const i=r?this._cubemapMaterial:this._equirectMaterial,s=this._lodMeshes[0];s.material=i;i.uniforms.envMap.value=e;const a=this._cubeSize;xo(t,0,0,3*a,2*a),n.setRenderTarget(t),n.render(s,ho)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;const r=this._lodMeshes.length;for(let t=1;th-4?n-h+4:0),f=4*(this._cubeSize-d);o.envMap.value=e.texture,o.roughness.value=c,o.mipInt.value=h-t,xo(i,p,f,3*d,2*d),r.setRenderTarget(i),r.render(a,ho),o.envMap.value=i.texture,o.roughness.value=0,o.mipInt.value=h-n,xo(e,p,f,3*d,2*d),r.setRenderTarget(e),r.render(a,ho)}_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&&Jt("blur direction must be either latitudinal or longitudinal!");const u=this._lodMeshes[r];u.material=l;const 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):co;f>co&&Qt(`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_-4?r-_+4:0),4*(this._cubeSize-v),3*v,2*v),o.setRenderTarget(t),o.render(u,ho)}};function bo(e,t,n){const r=new Fn(e,t,n);return r.texture.mapping=ce,r.texture.name="PMREM.cubeUv",r.scissorTest=!0,r}function xo(e,t,n,r,i){e.viewport.set(t,n,r,i),e.scissor.set(t,n,r,i)}function To(){return new qi({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:Mo(),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 \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 So(){return new qi({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Mo(),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 Mo(){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 wo(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===le||s===ue,o=s===ae||s===oe;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 yo(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;rt.maxTextureSize&&(b=Math.ceil(y/t.maxTextureSize),y=t.maxTextureSize);const x=new Float32Array(y*b*4*c),T=new Bn(x,y,b,c);T.type=Ee,T.needsUpdate=!0;const S=4*v;for(let w=0;w\n\t\t\t#include \n\n\t\t\tvoid main() {\n\t\t\t\tgl_FragColor = texture2D( tDiffuse, vUv );\n\n\t\t\t\t#ifdef LINEAR_TONE_MAPPING\n\t\t\t\t\tgl_FragColor.rgb = LinearToneMapping( gl_FragColor.rgb );\n\t\t\t\t#elif defined( REINHARD_TONE_MAPPING )\n\t\t\t\t\tgl_FragColor.rgb = ReinhardToneMapping( gl_FragColor.rgb );\n\t\t\t\t#elif defined( CINEON_TONE_MAPPING )\n\t\t\t\t\tgl_FragColor.rgb = CineonToneMapping( gl_FragColor.rgb );\n\t\t\t\t#elif defined( ACES_FILMIC_TONE_MAPPING )\n\t\t\t\t\tgl_FragColor.rgb = ACESFilmicToneMapping( gl_FragColor.rgb );\n\t\t\t\t#elif defined( AGX_TONE_MAPPING )\n\t\t\t\t\tgl_FragColor.rgb = AgXToneMapping( gl_FragColor.rgb );\n\t\t\t\t#elif defined( NEUTRAL_TONE_MAPPING )\n\t\t\t\t\tgl_FragColor.rgb = NeutralToneMapping( gl_FragColor.rgb );\n\t\t\t\t#elif defined( CUSTOM_TONE_MAPPING )\n\t\t\t\t\tgl_FragColor.rgb = CustomToneMapping( gl_FragColor.rgb );\n\t\t\t\t#endif\n\n\t\t\t\t#ifdef SRGB_TRANSFER\n\t\t\t\t\tgl_FragColor = sRGBTransferOETF( gl_FragColor );\n\t\t\t\t#endif\n\t\t\t}",depthTest:!1,depthWrite:!1}),u=new Vi(o,l),c=new Pa(-1,1,1,-1,0,1);let h,d=null,p=null,f=!1,m=null,g=[],_=!1;this.setSize=function(e,t){s.setSize(e,t),a.setSize(e,t);for(let n=0;n0&&!0===g[0].isRenderPass;const t=s.width,n=s.height;for(let e=0;e0)return e;const i=t*n;let s=ko[i];if(void 0===s&&(s=new Float32Array(i),ko[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 Wo(e,t){if(e.length!==t.length)return!1;for(let n=0,r=e.length;n0&&(this.seq=r.concat(i))}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 kl(e,t,n){const r=e.createShader(t);return e.shaderSource(r,n),e.compileShader(r),r}let zl=0;const Vl=new yn;function Gl(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":" "} ${i}: ${n[e]}`)}return r.join("\n")}(e.getShaderSource(t),r)}return i}function Hl(e,t){const n=function(e){Mn._getMatrix(Vl,Mn.workingColorSpace,e);const t=`mat3( ${Vl.elements.map(e=>e.toFixed(4))} )`;switch(Mn.getTransfer(e)){case Rt:return[t,"LinearTransferOETF"];case Ct:return[t,"sRGBTransferOETF"];default:return Qt("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")}const jl={[J]:"Linear",[ee]:"Reinhard",[te]:"Cineon",[ne]:"ACESFilmic",[ie]:"AgX",[se]:"Neutral",[re]:"Custom"};function Wl(e,t){const n=jl[t];return void 0===n?(Qt("WebGLProgram: Unsupported toneMapping:",t),"vec3 "+e+"( vec3 color ) { return LinearToneMapping( color ); }"):"vec3 "+e+"( vec3 color ) { return "+n+"ToneMapping( color ); }"}const $l=new gn;function Xl(){Mn.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 ql(e){return""!==e}function Yl(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 Kl(e,t){return e.replace(/NUM_CLIPPING_PLANES/g,t.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,t.numClippingPlanes-t.numClipIntersection)}const Zl=/^[ \t]*#include +<([\w\d./]+)>/gm;function Ql(e){return e.replace(Zl,eu)}const Jl=new Map;function eu(e,t){let n=Za[t];if(void 0===n){const e=Jl.get(t);if(void 0===e)throw new Error("Can not resolve #include <"+t+">");n=Za[e],Qt('WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',t,e)}return Ql(n)}const tu=/#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 nu(e){return e.replace(tu,ru)}function ru(e,t,n,r){let i="";for(let e=parseInt(t);e0&&(g+="\n"),_=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,f].filter(ql).join("\n"),_.length>0&&(_+="\n")):(g=[iu(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_LOGARITHMIC_DEPTH_BUFFER":"",n.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","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(ql).join("\n"),_=[iu(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_LOGARITHMIC_DEPTH_BUFFER":"",n.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",0!==n.toneMapping?"#define TONE_MAPPING":"",0!==n.toneMapping?Za.tonemapping_pars_fragment:"",0!==n.toneMapping?Wl("toneMapping",n.toneMapping):"",n.dithering?"#define DITHERING":"",n.opaque?"#define OPAQUE":"",Za.colorspace_pars_fragment,Hl("linearToOutputTexel",n.outputColorSpace),Xl(),n.useDepthPacking?"#define DEPTH_PACKING "+n.depthPacking:"","\n"].filter(ql).join("\n")),a=Ql(a),a=Yl(a,n),a=Kl(a,n),o=Ql(o),o=Yl(o,n),o=Kl(o,n),a=nu(a),o=nu(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,b=v+_+o,x=kl(i,i.VERTEX_SHADER,y),T=kl(i,i.FRAGMENT_SHADER,b);function S(t){if(e.debug.checkShaderErrors){const n=i.getProgramInfoLog(m)||"",r=i.getShaderInfoLog(x)||"",s=i.getShaderInfoLog(T)||"",a=n.trim(),o=r.trim(),l=s.trim();let u=!0,c=!0;if(!1===i.getProgramParameter(m,i.LINK_STATUS))if(u=!1,"function"==typeof e.debug.onShaderError)e.debug.onShaderError(i,m,x,T);else{const e=Gl(i,x,"vertex"),n=Gl(i,T,"fragment");Jt("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: "+a+"\n"+e+"\n"+n)}else""!==a?Qt("WebGLProgram: Program Info Log:",a):""!==o&&""!==l||(c=!1);c&&(t.diagnostics={runnable:u,programLog:a,vertexShader:{log:o,prefix:g},fragmentShader:{log:l,prefix:_}})}i.deleteShader(x),i.deleteShader(T),M=new Bl(i,m),w=function(e,t){const n={},r=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let i=0;i0,$=s.clearcoat>0,X=s.dispersion>0,q=s.iridescence>0,Y=s.sheen>0,K=s.transmission>0,Z=W&&!!s.anisotropyMap,Q=$&&!!s.clearcoatMap,J=$&&!!s.clearcoatNormalMap,ee=$&&!!s.clearcoatRoughnessMap,te=q&&!!s.iridescenceMap,ne=q&&!!s.iridescenceThicknessMap,re=Y&&!!s.sheenColorMap,ie=Y&&!!s.sheenRoughnessMap,se=!!s.specularMap,ae=!!s.specularColorMap,oe=!!s.specularIntensityMap,le=K&&!!s.transmissionMap,ue=K&&!!s.thicknessMap,he=!!s.gradientMap,de=!!s.alphaMap,pe=s.alphaTest>0,fe=!!s.alphaHash,me=!!s.extensions;let ge=0;s.toneMapped&&(null!==N&&!0!==N.isXRRenderTarget||(ge=e.toneMapping));const _e={shaderID:T,shaderType:s.type,shaderName:s.name,vertexShader:w,fragmentShader:E,defines:s.defines,customVertexShaderID:A,customFragmentShaderID:R,isRawShaderMaterial:!0===s.isRawShaderMaterial,glslVersion:s.glslVersion,precision:p,batching:D,batchingColor:D&&null!==g._colorsTexture,instancing:L,instancingColor:L&&null!==g.instanceColor,instancingMorph:L&&null!==g.morphTexture,outputColorSpace:null===N?e.outputColorSpace:!0===N.isXRRenderTarget?N.texture.colorSpace:At,alphaToCoverage:!!s.alphaToCoverage,map:I,matcap:U,envMap:O,envMapMode:O&&b.mapping,envMapCubeUVHeight:x,aoMap:F,lightMap:B,bumpMap:k,normalMap:z,displacementMap:V,emissiveMap:G,normalMapObjectSpace:z&&1===s.normalMapType,normalMapTangentSpace:z&&0===s.normalMapType,metalnessMap:H,roughnessMap:j,anisotropy:W,anisotropyMap:Z,clearcoat:$,clearcoatMap:Q,clearcoatNormalMap:J,clearcoatRoughnessMap:ee,dispersion:X,iridescence:q,iridescenceMap:te,iridescenceThicknessMap:ne,sheen:Y,sheenColorMap:re,sheenRoughnessMap:ie,specularMap:se,specularColorMap:ae,specularIntensityMap:oe,transmission:K,transmissionMap:le,thicknessMap:ue,gradientMap:he,opaque:!1===s.transparent&&1===s.blending&&!1===s.alphaToCoverage,alphaMap:de,alphaTest:pe,alphaHash:fe,combine:s.combine,mapUv:I&&m(s.map.channel),aoMapUv:F&&m(s.aoMap.channel),lightMapUv:B&&m(s.lightMap.channel),bumpMapUv:k&&m(s.bumpMap.channel),normalMapUv:z&&m(s.normalMap.channel),displacementMapUv:V&&m(s.displacementMap.channel),emissiveMapUv:G&&m(s.emissiveMap.channel),metalnessMapUv:H&&m(s.metalnessMap.channel),roughnessMapUv:j&&m(s.roughnessMap.channel),anisotropyMapUv:Z&&m(s.anisotropyMap.channel),clearcoatMapUv:Q&&m(s.clearcoatMap.channel),clearcoatNormalMapUv:J&&m(s.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:ee&&m(s.clearcoatRoughnessMap.channel),iridescenceMapUv:te&&m(s.iridescenceMap.channel),iridescenceThicknessMapUv:ne&&m(s.iridescenceThicknessMap.channel),sheenColorMapUv:re&&m(s.sheenColorMap.channel),sheenRoughnessMapUv:ie&&m(s.sheenRoughnessMap.channel),specularMapUv:se&&m(s.specularMap.channel),specularColorMapUv:ae&&m(s.specularColorMap.channel),specularIntensityMapUv:oe&&m(s.specularIntensityMap.channel),transmissionMapUv:le&&m(s.transmissionMap.channel),thicknessMapUv:ue&&m(s.thicknessMap.channel),alphaMapUv:de&&m(s.alphaMap.channel),vertexTangents:!!v.attributes.tangent&&(z||W),vertexColors:s.vertexColors,vertexAlphas:!0===s.vertexColors&&!!v.attributes.color&&4===v.attributes.color.itemSize,pointsUvs:!0===g.isPoints&&!!v.attributes.uv&&(I||de),fog:!!_,useFog:!0===s.fog,fogExp2:!!_&&_.isFogExp2,flatShading:!0===s.flatShading&&!1===s.wireframe,sizeAttenuation:!0===s.sizeAttenuation,logarithmicDepthBuffer:d,reversedDepthBuffer:P,skinning:!0===g.isSkinnedMesh,morphTargets:void 0!==v.morphAttributes.position,morphNormals:void 0!==v.morphAttributes.normal,morphColors:void 0!==v.morphAttributes.color,morphTargetsCount:M,morphTextureStride:C,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:ge,decodeVideoTexture:I&&!0===s.map.isVideoTexture&&Mn.getTransfer(s.map.colorSpace)===Ct,decodeVideoTextureEmissive:G&&!0===s.emissiveMap.isVideoTexture&&Mn.getTransfer(s.emissiveMap.colorSpace)===Ct,premultipliedAlpha:s.premultipliedAlpha,doubleSided:2===s.side,flipSided:1===s.side,useDepthPacking:s.depthPacking>=0,depthPacking:s.depthPacking||0,index0AttributeName:s.index0AttributeName,extensionClipCullDistance:me&&!0===s.extensions.clipCullDistance&&r.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(me&&!0===s.extensions.multiDraw||D)&&r.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:r.has("KHR_parallel_shader_compile"),customProgramCacheKey:s.customProgramCacheKey()};return _e.vertexUv1s=u.has(1),_e.vertexUv2s=u.has(2),_e.vertexUv3s=u.has(3),u.clear(),_e},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.instancing&&o.enable(0);t.instancingColor&&o.enable(1);t.instancingMorph&&o.enable(2);t.matcap&&o.enable(3);t.envMap&&o.enable(4);t.normalMapObjectSpace&&o.enable(5);t.normalMapTangentSpace&&o.enable(6);t.clearcoat&&o.enable(7);t.iridescence&&o.enable(8);t.alphaTest&&o.enable(9);t.vertexColors&&o.enable(10);t.vertexAlphas&&o.enable(11);t.vertexUv1s&&o.enable(12);t.vertexUv2s&&o.enable(13);t.vertexUv3s&&o.enable(14);t.vertexTangents&&o.enable(15);t.anisotropy&&o.enable(16);t.alphaHash&&o.enable(17);t.batching&&o.enable(18);t.dispersion&&o.enable(19);t.batchingColor&&o.enable(20);t.gradientMap&&o.enable(21);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.reversedDepthBuffer&&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=Ja[t];n=Xi.clone(e.uniforms)}else n=e.uniforms;return n},acquireProgram:function(t,n){let r=h.get(n);return void 0!==r?++r.usedTimes:(r=new uu(e,n,t,s),c.push(r),h.set(n,r)),r},releaseProgram:function(e){if(0===--e.usedTimes){const t=c.indexOf(e);c[t]=c[c.length-1],c.pop(),h.delete(e.cacheKey),e.destroy()}},releaseShaderCache:function(e){l.remove(e)},programs:c,dispose:function(){l.dispose()}}}function fu(){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 mu(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 gu(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 _u(){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;n1&&n.sort(e||mu),r.length>1&&r.sort(t||gu),i.length>1&&i.sort(t||gu)}}}function vu(){let e=new WeakMap;return{get:function(t,n){const r=e.get(t);let i;return void 0===r?(i=new _u,e.set(t,[i])):n>=r.length?(i=new _u,r.push(i)):i=r[n],i},dispose:function(){e=new WeakMap}}}function yu(){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 gn,color:new si};break;case"SpotLight":n={position:new gn,direction:new gn,color:new si,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":n={position:new gn,color:new si,distance:0,decay:0};break;case"HemisphereLight":n={direction:new gn,skyColor:new si,groundColor:new si};break;case"RectAreaLight":n={color:new si,position:new gn,halfWidth:new gn,halfHeight:new gn}}return e[t.id]=n,n}}}let bu=0;function xu(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+(t.map?1:0)-(e.map?1:0)}function Tu(e){const t=new yu,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 fn};break;case"PointLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new fn,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 gn);const i=new gn,s=new pr,a=new pr;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(xu);for(let e=0,y=i.length;e0&&(!0===e.has("OES_texture_float_linear")?(r.rectAreaLTC1=Qa.LTC_FLOAT_1,r.rectAreaLTC2=Qa.LTC_FLOAT_2):(r.rectAreaLTC1=Qa.LTC_HALF_1,r.rectAreaLTC2=Qa.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=bu++)},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=i.length?(s=new Su(e),i.push(s)):s=i[r],s},dispose:function(){t=new WeakMap}}}const wu=[new gn(1,0,0),new gn(-1,0,0),new gn(0,1,0),new gn(0,-1,0),new gn(0,0,1),new gn(0,0,-1)],Eu=[new gn(0,-1,0),new gn(0,-1,0),new gn(0,0,1),new gn(0,0,-1),new gn(0,-1,0),new gn(0,-1,0)],Au=new pr,Ru=new gn,Cu=new gn;function Nu(e,t,n){let r=new xs;const i=new fn,s=new fn,a=new Un,o=new ha,l=new da,u={},c=n.maxTextureSize,h={[x]:1,[T]:0,[S]:2},d=new qi({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new fn},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;\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 = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ).rg;\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 = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ).r;\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( max( 0.0, squared_mean - mean * mean ) );\n\tgl_FragColor = vec4( mean, std_dev, 0.0, 1.0 );\n}"}),p=d.clone();p.defines.HORIZONTAL_PASS=1;const f=new Ci;f.setAttribute("position",new _i(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const m=new Vi(f,d),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1;let _=this.type;function v(n,r){const s=t.update(m);d.defines.VSM_SAMPLES!==n.blurSamples&&(d.defines.VSM_SAMPLES=n.blurSamples,p.defines.VSM_SAMPLES=n.blurSamples,d.needsUpdate=!0,p.needsUpdate=!0),null===n.mapPass&&(n.mapPass=new Fn(i.x,i.y,{format:ze,type:Ae})),d.uniforms.shadow_pass.value=n.map.depthTexture,d.uniforms.resolution.value=n.mapSize,d.uniforms.radius.value=n.radius,e.setRenderTarget(n.mapPass),e.clear(),e.renderBufferDirect(r,null,s,d,m,null),p.uniforms.shadow_pass.value=n.mapPass.texture,p.uniforms.resolution.value=n.mapSize,p.uniforms.radius.value=n.radius,e.setRenderTarget(n.map),e.clear(),e.renderBufferDirect(r,null,s,p,m,null)}function y(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 b(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;ue.needsUpdate=!0):e.material.needsUpdate=!0)});for(let l=0,u=t.length;lc||i.y>c)&&(i.x>c&&(s.x=Math.floor(c/f.x),i.x=s.x*f.x,h.mapSize.x=s.x),i.y>c&&(s.y=Math.floor(c/f.y),i.y=s.y*f.y,h.mapSize.y=s.y)),null===h.map||!0===p){if(null!==h.map&&(null!==h.map.depthTexture&&(h.map.depthTexture.dispose(),h.map.depthTexture=null),h.map.dispose()),3===this.type){if(u.isPointLight){Qt("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}h.map=new Fn(i.x,i.y,{format:ze,type:Ae,minFilter:_e,magFilter:_e,generateMipmaps:!1}),h.map.texture.name=u.name+".shadowMap",h.map.depthTexture=new Os(i.x,i.y,Ee),h.map.depthTexture.name=u.name+".shadowMapDepth",h.map.depthTexture.format=Oe,h.map.depthTexture.compareFunction=null,h.map.depthTexture.minFilter=fe,h.map.depthTexture.magFilter=fe}else{u.isPointLight?(h.map=new rs(i.x),h.map.depthTexture=new Fs(i.x,we)):(h.map=new Fn(i.x,i.y),h.map.depthTexture=new Os(i.x,i.y,we)),h.map.depthTexture.name=u.name+".shadowMap",h.map.depthTexture.format=Oe;const t=e.state.buffers.depth.getReversed();1===this.type?(h.map.depthTexture.compareFunction=t?Ft:It,h.map.depthTexture.minFilter=_e,h.map.depthTexture.magFilter=_e):(h.map.depthTexture.compareFunction=null,h.map.depthTexture.minFilter=fe,h.map.depthTexture.magFilter=fe)}h.camera.updateProjectionMatrix()}const m=h.map.isWebGLCubeRenderTarget?6:1;for(let t=0;t=1):-1!==Y.indexOf("OpenGL ES")&&(q=parseFloat(/^OpenGL ES (\d)/.exec(Y)[1]),X=q>=2);let K=null,Z={};const Q=e.getParameter(e.SCISSOR_BOX),J=e.getParameter(e.VIEWPORT),ee=(new Un).fromArray(Q),te=(new Un).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;an||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),Qt("WebGLRenderer: Texture has been resized from ("+i.width+"x"+i.height+") to ("+n+"x"+s+")."),a}return"data"in e&&Qt("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];Qt("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),i===e.UNSIGNED_INT_10F_11F_11F_REV&&(o=e.R11F_G11F_B10F)),r===e.RGBA){const t=a?Rt:Mn.getTransfer(s);i===e.FLOAT&&(o=e.RGBA32F),i===e.HALF_FLOAT&&(o=e.RGBA16F),i===e.UNSIGNED_BYTE&&(o=t===Ct?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 b(t,n){let r;return t?null===n||n===we||n===Ne?r=e.DEPTH24_STENCIL8:n===Ee?r=e.DEPTH32F_STENCIL8:n===Se&&(r=e.DEPTH24_STENCIL8,Qt("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):null===n||n===we||n===Ne?r=e.DEPTH_COMPONENT24:n===Ee?r=e.DEPTH_COMPONENT32F:n===Se&&(r=e.DEPTH_COMPONENT16),r}function x(e,t){return!0===g(e)||e.isFramebufferTexture&&e.minFilter!==fe&&e.minFilter!==_e?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;r0&&s.__version!==t.version){const e=t.image;if(null===e)Qt("WebGLRenderer: Texture marked for update but no image data found.");else{if(!1!==e.complete)return void D(s,t,i);Qt("WebGLRenderer: Texture marked for update but image is incomplete")}}else t.isExternalTexture&&(s.__webglTexture=t.sourceTexture?t.sourceTexture:null);n.bindTexture(e.TEXTURE_2D,s.__webglTexture,e.TEXTURE0+i)}const A={[he]:e.REPEAT,[de]:e.CLAMP_TO_EDGE,[pe]:e.MIRRORED_REPEAT},R={[fe]:e.NEAREST,[me]:e.NEAREST_MIPMAP_NEAREST,[ge]:e.NEAREST_MIPMAP_LINEAR,[_e]:e.LINEAR,[ve]:e.LINEAR_MIPMAP_NEAREST,[ye]:e.LINEAR_MIPMAP_LINEAR},C={[Pt]:e.NEVER,[Bt]:e.ALWAYS,[Lt]:e.LESS,[It]:e.LEQUAL,[Dt]:e.EQUAL,[Ft]:e.GEQUAL,[Ut]:e.GREATER,[Ot]:e.NOTEQUAL};function N(n,s){if(s.type!==Ee||!1!==t.has("OES_texture_float_linear")||s.magFilter!==_e&&s.magFilter!==ve&&s.magFilter!==ge&&s.magFilter!==ye&&s.minFilter!==_e&&s.minFilter!==ve&&s.minFilter!==ge&&s.minFilter!==ye||Qt("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===fe)return;if(s.minFilter!==ge&&s.minFilter!==ye)return;if(s.type===Ee&&!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=Mn.getPrimaries(Mn.workingColorSpace),r=a.colorSpace===wt?null:Mn.getPrimaries(a.colorSpace),d=a.colorSpace===wt||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=x(a,p);if(a.isDepthTexture)S=b(a.format===Fe,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;te.start-t.start);let o=0;for(let e=1;e0){const r=qa(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 Qt("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;t0){const t=qa(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>=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>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=b(n.stencilBuffer,s),l=n.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;V(n)?o.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,z(n),a,n.width,n.height):r?e.renderbufferStorageMultisample(e.RENDERBUFFER,z(n),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{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)for(let e=0;e<6;e++)O(i.__webglFramebuffer[e],t,e);else{const e=t.texture.mipmaps;e&&e.length>0?O(i.__webglFramebuffer[0],t,0):O(i.__webglFramebuffer,t,0)}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!==At&&n!==wt&&(Mn.getTransfer(n)===Ct?r===Ue&&i===be||Qt("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):Jt("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&&Qt("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);!1===t.isRenderTargetTexture&&t.version>0&&s.__version!==t.version?D(s,t,i):(t.isExternalTexture&&(s.__webglTexture=t.sourceTexture?t.sourceTexture:null),n.bindTexture(e.TEXTURE_2D_ARRAY,s.__webglTexture,e.TEXTURE0+i))},this.setTexture3D=function(t,i){const s=r.get(t);!1===t.isRenderTargetTexture&&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);!0!==t.isCubeDepthTexture&&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=Mn.getPrimaries(Mn.workingColorSpace),r=a.colorSpace===wt?null:Mn.getPrimaries(a.colorSpace),h=a.colorSpace===wt||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],b=s.convert(a.format,a.colorSpace),T=s.convert(a.type),S=y(a.internalFormat,b,T,a.colorSpace),M=!0!==a.isVideoTexture,w=void 0===c.__version||!0===l,E=u.dataReady;let A,R=x(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;r0&&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,b,T,f[t].data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,S,f[t].width,f[t].height,0,b,T,f[t].data);for(let r=0;r1;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;n0){o.__webglFramebuffer=[];for(let t=0;t0&&!1===V(t)){o.__webglMultisampledFramebuffer=e.createFramebuffer(),o.__webglColorRenderbuffer=[],n.bindFramebuffer(e.FRAMEBUFFER,o.__webglMultisampledFramebuffer);for(let n=0;n0)for(let r=0;r0)for(let n=0;n0)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;t0?n.bindFramebuffer(e.DRAW_FRAMEBUFFER,c.__webglFramebuffer[0]):n.bindFramebuffer(e.DRAW_FRAMEBUFFER,c.__webglFramebuffer);for(let n=0;n= 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 Vi(new ea(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class Ou extends tn{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="undefined"!=typeof XRWebGLBinding,m=new Uu,g={},_=t.getContextAttributes();let v=null,y=null;const b=[],x=[],T=new fn;let S=null;const M=new Ji;M.viewport=new Un;const w=new Ji;w.viewport=new Un;const E=[M,w],A=new Ba;let R=null,C=null;function N(e){const t=x.indexOf(e.inputSource);if(-1===t)return;const n=b[t];void 0!==n&&(n.update(e.inputSource,e.frame,l||s),n.dispatchEvent({type:e.type,data:e.inputSource}))}function P(){r.removeEventListener("select",N),r.removeEventListener("selectstart",N),r.removeEventListener("selectend",N),r.removeEventListener("squeeze",N),r.removeEventListener("squeezestart",N),r.removeEventListener("squeezeend",N),r.removeEventListener("end",P),r.removeEventListener("inputsourceschange",L);for(let e=0;e=0&&(x[r]=null,b[r].disconnect(n))}for(let t=0;t=x.length){x.push(n),r=e;break}if(null===x[e]){x[e]=n,r=e;break}}if(-1===r)break}const i=b[r];i&&i.connect(n)}}this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(e){let t=b[e];return void 0===t&&(t=new as,b[e]=t),t.getTargetRaySpace()},this.getControllerGrip=function(e){let t=b[e];return void 0===t&&(t=new as,b[e]=t),t.getGripSpace()},this.getHand=function(e){let t=b[e];return void 0===t&&(t=new as,b[e]=t),t.getHandSpace()},this.setFramebufferScaleFactor=function(e){i=e,!0===n.isPresenting&&Qt("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(e){a=e,!0===n.isPresenting&&Qt("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 null===c&&f&&(c=new XRWebGLBinding(r,t)),c},this.getFrame=function(){return p},this.getSession=function(){return r},this.setSession=async function(u){if(r=u,null!==r){v=e.getRenderTarget(),r.addEventListener("select",N),r.addEventListener("selectstart",N),r.addEventListener("selectend",N),r.addEventListener("squeeze",N),r.addEventListener("squeezestart",N),r.addEventListener("squeezeend",N),r.addEventListener("end",P),r.addEventListener("inputsourceschange",L),!0!==_.xrCompatible&&await t.makeXRCompatible(),S=e.getPixelRatio(),e.getSize(T);if(f&&"createProjectionLayer"in XRWebGLBinding.prototype){let n=null,s=null,a=null;_.depth&&(a=_.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,n=_.stencil?Fe:Oe,s=_.stencil?Ne:we);const o={colorFormat:t.RGBA8,depthFormat:a,scaleFactor:i};c=this.getBinding(),h=c.createProjectionLayer(o),r.updateRenderState({layers:[h]}),e.setPixelRatio(1),e.setSize(h.textureWidth,h.textureHeight,!1),y=new Fn(h.textureWidth,h.textureHeight,{format:Ue,type:be,depthTexture:new Os(h.textureWidth,h.textureHeight,s,void 0,void 0,void 0,void 0,void 0,void 0,n),stencilBuffer:_.stencil,colorSpace:e.outputColorSpace,samples:_.antialias?4:0,resolveDepthBuffer:!1===h.ignoreDepthValues,resolveStencilBuffer:!1===h.ignoreDepthValues})}else{const n={antialias:_.antialias,alpha:!0,depth:_.depth,stencil:_.stencil,framebufferScaleFactor:i};d=new XRWebGLLayer(r,t,n),r.updateRenderState({baseLayer:d}),e.setPixelRatio(1),e.setSize(d.framebufferWidth,d.framebufferHeight,!1),y=new Fn(d.framebufferWidth,d.framebufferHeight,{format:Ue,type:be,colorSpace:e.outputColorSpace,stencilBuffer:_.stencil,resolveDepthBuffer:!1===d.ignoreDepthValues,resolveStencilBuffer:!1===d.ignoreDepthValues})}y.isXRRenderTarget=!0,this.setFoveation(o),l=null,s=await r.requestReferenceSpace(a),F.setContext(r),F.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(null!==r)return r.environmentBlendMode},this.getDepthTexture=function(){return m.getDepthTexture()};const D=new gn,I=new gn;function U(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!==m.texture&&(m.depthNear>0&&(t=m.depthNear),m.depthFar>0&&(n=m.depthFar)),A.near=w.near=M.near=t,A.far=w.far=M.far=n,R===A.near&&C===A.far||(r.updateRenderState({depthNear:A.near,depthFar:A.far}),R=A.near,C=A.far),A.layers.mask=6|e.layers.mask,M.layers.mask=3&A.layers.mask,w.layers.mask=5&A.layers.mask;const i=e.parent,s=A.cameras;U(A,i);for(let e=0;e0&&(e.alphaTest.value=r.alphaTest);const i=t.get(r),s=i.envMap,a=i.envMapRotation;s&&(e.envMap.value=s,Fu.copy(a),Fu.x*=-1,Fu.y*=-1,Fu.z*=-1,s.isCubeTexture&&!1===s.isRenderTargetTexture&&(Fu.y*=-1,Fu.z*=-1),e.envMapRotation.value.setFromMatrix4(Bu.makeRotationFromEuler(Fu)),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 zu(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?Qt("WebGLRenderer: Texture samplers can not be part of an uniforms group."):Qt("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;e0&&(n+=r-i);e.__size=n,e.__cache={}}(n),d=function(t){const n=function(){for(let e=0;e0){const e=tc[0].object;Hu.setFromNormalAndCoplanarPoint(t.getWorldDirection(Hu.normal),Yu.setFromMatrixPosition(e.matrixWorld)),ec!==e&&null!==ec&&(this.dispatchEvent({type:"hoveroff",object:ec}),n.style.cursor="auto",ec=null),ec!==e&&(this.dispatchEvent({type:"hoveron",object:e}),n.style.cursor="pointer",ec=e)}else null!==ec&&(this.dispatchEvent({type:"hoveroff",object:ec}),n.style.cursor="auto",ec=null);Xu.copy(ju)}}function oc(e){const t=this.object,n=this.domElement,r=this.raycaster;!1!==this.enabled&&(this._updatePointer(e),this._updateState(e),tc.length=0,r.setFromCamera(ju,t),r.intersectObjects(this.objects,this.recursive,tc),tc.length>0&&(Ju=!0===this.transformGroup?cc(tc[0].object):tc[0].object,Hu.setFromNormalAndCoplanarPoint(t.getWorldDirection(Hu.normal),Yu.setFromMatrixPosition(Ju.matrixWorld)),r.ray.intersectPlane(Hu,qu)&&(this.state===rc?(Ku.copy(Ju.parent.matrixWorld).invert(),Wu.copy(qu).sub(Yu.setFromMatrixPosition(Ju.matrixWorld)),n.style.cursor="move",this.dispatchEvent({type:"dragstart",object:Ju})):this.state===ic&&(Zu.set(0,1,0).applyQuaternion(t.quaternion).normalize(),Qu.set(1,0,0).applyQuaternion(t.quaternion).normalize(),n.style.cursor="move",this.dispatchEvent({type:"dragstart",object:Ju})))),Xu.copy(ju))}function lc(){!1!==this.enabled&&(Ju&&(this.dispatchEvent({type:"dragend",object:Ju}),Ju=null),this.domElement.style.cursor=ec?"pointer":"auto",this.state=nc)}function uc(e){!1!==this.enabled&&e.preventDefault()}function cc(e,t=null){return e.isGroup&&(t=e),null===e.parent?t:cc(e.parent,t)}function hc(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=(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 pc(e,t,n){this.node=e,this.x0=t,this.x1=n}function fc(e){return e[0]}function mc(e,t){var n=new gc(null==t?fc:t,NaN,NaN);return null==e?n:n.addAll(e)}function gc(e,t,n){this._x=e,this._x0=t,this._x1=n,this._root=void 0}function _c(e){for(var t={data:e.data},n=t;e=e.next;)n=n.next={data:e.data};return t}var vc=mc.prototype=gc.prototype;function yc(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 bc(e,t,n,r,i){this.node=e,this.x0=t,this.y0=n,this.x1=r,this.y1=i}function xc(e){return e[0]}function Tc(e){return e[1]}function Sc(e,t,n){var r=new Mc(null==t?xc:t,null==n?Tc:n,NaN,NaN,NaN,NaN);return null==e?r:r.addAll(e)}function Mc(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 wc(e){for(var t={data:e.data},n=t;e=e.next;)n=n.next={data:e.data};return t}vc.copy=function(){var e,t,n=new gc(this._x,this._x0,this._x1),r=this._root;if(!r)return n;if(!r.length)return n._root=_c(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]=_c(t));return n},vc.add=function(e){const t=+this._x.call(null,e);return dc(this.cover(t),t,e)},vc.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;ai&&(i=s));if(r>i)return this;this.cover(r).cover(i);for(let r=0;re||e>=n;)switch(i=+(el||(i=s.x1)=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=(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)},vc.removeAll=function(e){for(var t=0,n=e.length;t=(a=(y+T)/2))?y=a:T=a,(p=n>=(o=(b+S)/2))?b=o:S=o,(f=r>=(l=(x+M)/2))?x=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=(b+S)/2))?b=o:S=o,(f=r>=(l=(x+M)/2))?x=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 Rc(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}Ec.copy=function(){var e,t,n=new Mc(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=wc(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]=wc(t));return n},Ec.add=function(e){const t=+this._x.call(null,e),n=+this._y.call(null,e);return yc(this.cover(t,n),t,n,e)},Ec.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;nc&&(c=r),ih&&(h=i));if(l>c||u>h)return this;for(this.cover(l,u).cover(c,h),n=0;ne||e>=i||r>t||t>=s;)switch(o=(td||(s=l.y0)>p||(a=l.x1)=_)<<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),b=v*v+y*y;if(b=(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)},Ec.removeAll=function(e){for(var t=0,n=e.length;tMath.sqrt((e-r)**2+(t-i)**2+(n-s)**2);function Nc(e){return e[0]}function Pc(e){return e[1]}function Lc(e){return e[2]}function Dc(e,t,n,r){var i=new Ic(null==t?Nc:t,null==n?Pc:n,null==r?Lc:r,NaN,NaN,NaN,NaN,NaN,NaN);return null==e?i:i.addAll(e)}function Ic(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 Uc(e){for(var t={data:e.data},n=t;e=e.next;)n=n.next={data:e.data};return t}var Oc=Dc.prototype=Ic.prototype;function Fc(e){return function(){return e}}function Bc(e){return 1e-6*(e()-.5)}function kc(e){return e.index}function zc(e,t){var n=e.get(t);if(!n)throw new Error("node not found: "+t);return n}function Vc(e){var t,n,r,i,s,a,o,l=kc,u=function(e){return 1/Math.min(s[e.source.index],s[e.target.index])},c=Fc(30),h=1;function d(r){for(var s=0,l=e.length;s1&&(_=d.y+d.vy-c.y-c.vy||Bc(o)),i>2&&(v=d.z+d.vz-c.z-c.vz||Bc(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"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:Fc(+e),f(),d):u},d.distance=function(e){return arguments.length?(c="function"==typeof e?e:Fc(+e),m(),d):c},d}Oc.copy=function(){var e,t,n=new Ic(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=Uc(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]=Uc(t));return n},Oc.add=function(e){const t=+this._x.call(null,e),n=+this._y.call(null,e),r=+this._z.call(null,e);return Ac(this.cover(t,n,r),t,n,r,e)},Oc.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;ml&&(l=d),pu&&(u=p),fc&&(c=f));if(s>l||a>u||o>c)return this;this.cover(s,a,o).cover(l,u,c);for(let s=0;se||e>=a||i>t||t>=o||s>n||n>=l;)switch(c=(ng||(a=h.y0)>_||(o=h.z0)>v||(l=h.x1)=S)<<2|(t>=T)<<1|e>=x)&&(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,b.data),w=t-+this._y.call(null,b.data),E=n-+this._z.call(null,b.data),A=M*M+w*w+E*E;if(A{if(!h.length)do{const s=h.data;Cc(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=(l=(_+b)/2))?_=l:b=l,(d=a>=(u=(v+x)/2))?v=u:x=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)},Oc.removeAll=function(e){for(var t=0,n=e.length;t{}};function Hc(){for(var e,t=0,n=arguments.length,r={};t=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(;++a0)for(var n,r,i=new Array(n),s=0;s=0&&t._call.call(void 0,e),t=t._next;--Yc}()}finally{Yc=0,function(){var e,t,n=Xc,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:Xc=t);qc=e,uh(r)}(),Jc=0}}function lh(){var e=th.now(),t=e-Qc;t>1e3&&(eh-=t,Qc=e)}function uh(e){Yc||(Kc&&(Kc=clearTimeout(Kc)),e-Jc>24?(e<1/0&&(Kc=setTimeout(oh,e-th.now()-eh)),Zc&&(Zc=clearInterval(Zc))):(Zc||(Qc=th.now(),Zc=setInterval(lh,1e3)),Yc=1,nh(oh)))}sh.prototype=ah.prototype={constructor:sh,restart:function(e,t,n){if("function"!=typeof e)throw new TypeError("callback is not a function");n=(null==n?rh():+n)+(null==t?0:+t),this._next||qc===this||(qc?qc._next=this:Xc=this,qc=this),this._call=e,this._time=n,uh()},stop:function(){this._call&&(this._call=null,this._time=1/0,uh())}};const ch=4294967296;function hh(e){return e.x}function dh(e){return e.y}function ph(e){return e.z}var fh=Math.PI*(3-Math.sqrt(5)),mh=20*Math.PI/(9+Math.sqrt(221));function gh(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=ah(p),h=Hc("tick","end"),d=function(){let e=1;return()=>(e=(1664525*e+1013904223)%ch)/ch}();function p(){f(),h.call("tick",n),i1&&(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;n1&&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*fh,o=n*mh;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;p1?(h.on(e,t),n):h.on(e)}}}function _h(){var e,t,n,r,i,s,a=Fc(-30),o=1,l=1/0,u=.81;function c(r){var s,a=e.length,o=(1===t?mc(e,hh):2===t?Sc(e,hh,dh):3===t?Dc(e,hh,dh,ph):null).visitAfter(d);for(i=r,s=0;s1&&(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(_*_/u1&&0===m&&(v+=(m=Bc(r))*m),t>2&&0===g&&(v+=(g=Bc(r))*g),v1&&(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=Bc(r))*f),t>1&&0===m&&(v+=(m=Bc(r))*m),t>2&&0===g&&(v+=(g=Bc(r))*g),v1&&(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:Fc(+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 vh(e){!function(e){if(!e)throw new Error("Eventify cannot use falsy object as events subject");const t=["on","fire","off"];for(let n=0;n1&&(i=Array.prototype.slice.call(arguments,1));for(let e=0;e"u")return t=Object.create(null),e;if(t[n])if("function"!=typeof r)delete t[n];else{const e=t[n];for(let t=0;t1&&(i=Array.prototype.slice.call(arguments,1));for(let e=0;e>>19))+(e<<5)&4294967295)^e<<9))+(e<<3)&4294967295)^e>>>16),this.seed=e,(268435455&e)/268435456}return Kh=1,ed.exports=e,ed.exports.random=e,ed.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)},ed.exports}().random(42),x=[],T=[],S=m(l,b),M=g(x,l,b),w=v(l,b),E=_(l),A=[],R=new Map,C=0;L("nbody",function(){if(0===x.length)return;S.insertBodies(x);var e=x.length;for(;e--;){var t=x[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:x,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;enew f(e))(e);return x.push(t),t},removeBody:function(e){if(e){var t=x.indexOf(e);if(!(t<0))return x.splice(t,1),0===x.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:b};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(Rh)return Nh.exports;Rh=1;const e=Lh();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 Nh.exports=function(e,n){let r=t(e,n),{Body:i}=new Function(r)();return i},Nh.exports.generateCreateBodyFunctionBody=t,Nh.exports.getVectorCode=r,Nh.exports.getBodyCode=n,Nh.exports}(),t=function(){if(Dh)return Ih.exports;Dh=1;const e=Lh(),t=Ph();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 {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 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 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 Ih.exports=function(e){let t=n(e);return new Function(t)()},Ih.exports.generateQuadTreeFunctionBody=n,Ih.exports.getInsertStackCode=o,Ih.exports.getQuadNodeCode=a,Ih.exports.isSamePosition=r,Ih.exports.getChildBodyCode=s,Ih.exports.setChildBodyCode=i,Ih.exports}(),n=function(){if(Uh)return Oh.exports;Uh=1,Oh.exports=function(e){let n=t(e);return new Function("bodies","settings","random",n)},Oh.exports.generateFunctionBody=t;const e=Lh();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 Oh.exports}(),r=function(){if(Fh)return Bh.exports;Fh=1;const e=Lh();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 Bh.exports=function(e){let n=t(e);return new Function("options",n)},Bh.exports.generateCreateDragForceFunctionBody=t,Bh.exports}(),i=function(){if(kh)return zh.exports;kh=1;const e=Lh();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 zh.exports=function(e){let n=t(e);return new Function("options","random",n)},zh.exports.generateCreateSpringForceFunctionBody=t,zh.exports}(),s=function(){if(Vh)return qh.exports;Vh=1;const e=Lh();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 qh.exports=function(e){let n=t(e);return new Function("bodies","timeStep","adaptiveTimeStepWeight",n)},qh.exports.generateIntegratorFunctionBody=t,qh.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 Zh}var nd=function(){if(Jh)return Ch.exports;Jh=1,Ch.exports=function(n,r){if(!n)throw new Error("Graph structure cannot be undefined");var i=(r&&r.createSimulator||td())(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 b(e).pos},setNodePosition:function(e){var t=b(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){b(e.id).isPinned=!!t},isNodePinned:function(e){return b(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=t||n<0||h&&e-u>=s}function m(){var e=ld();if(f(e))return g(e);o=setTimeout(m,function(e){var n=t-(e-l);return h?Ed(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=ld(),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=Md(t)||0,id(n)&&(c=!!n.leading,s=(h="maxWait"in n)?wd(Md(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(ld())},_}function Rd(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n=t)&&(n=t);else{let r=-1;for(let i of e)null!=(i=t(i,++r,e))&&(n=i)&&(n=i)}return n}function Bd(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 kd(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n1&&(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=Rp(e,360),t=Rp(t,100),n=Rp(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=Ap(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 up(e,t,n){e=Rp(e,255),t=Rp(t,255),n=Rp(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>1)+720)%360;--t;)r.h=(r.h+i)%360,s.push(lp(r));return s}function Mp(e,t){t=t||6;for(var n=lp(e).toHsv(),r=n.h,i=n.s,s=n.v,a=[],o=1/t;t--;)a.push(lp({h:r,s:i,v:s})),s=(s+o)%1;return a}lp.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=Ap(e),this._roundA=Math.round(100*this._a)/100,this},toHsv:function(){var e=cp(this._r,this._g,this._b);return{h:360*e.h,s:e.s,v:e.v,a:this._a}},toHsvString:function(){var e=cp(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=up(this._r,this._g,this._b);return{h:360*e.h,s:e.s,l:e.l,a:this._a}},toHslString:function(){var e=up(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 hp(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=[Pp(Math.round(e).toString(16)),Pp(Math.round(t).toString(16)),Pp(Math.round(n).toString(16)),Pp(Dp(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*Rp(this._r,255))+"%",g:Math.round(100*Rp(this._g,255))+"%",b:Math.round(100*Rp(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+Math.round(100*Rp(this._r,255))+"%, "+Math.round(100*Rp(this._g,255))+"%, "+Math.round(100*Rp(this._b,255))+"%)":"rgba("+Math.round(100*Rp(this._r,255))+"%, "+Math.round(100*Rp(this._g,255))+"%, "+Math.round(100*Rp(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":!(this._a<1)&&(Ep[hp(this._r,this._g,this._b,!0)]||!1)},toFilter:function(e){var t="#"+dp(this._r,this._g,this._b,this._a),n=t,r=this._gradientType?"GradientType = 1, ":"";if(e){var i=lp(e);n="#"+dp(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 lp(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(gp,arguments)},brighten:function(){return this._applyModification(_p,arguments)},darken:function(){return this._applyModification(vp,arguments)},desaturate:function(){return this._applyModification(pp,arguments)},saturate:function(){return this._applyModification(fp,arguments)},greyscale:function(){return this._applyModification(mp,arguments)},spin:function(){return this._applyModification(yp,arguments)},_applyCombination:function(e,t){return e.apply(null,[this].concat([].slice.call(t)))},analogous:function(){return this._applyCombination(Sp,arguments)},complement:function(){return this._applyCombination(bp,arguments)},monochromatic:function(){return this._applyCombination(Mp,arguments)},splitcomplement:function(){return this._applyCombination(Tp,arguments)},triad:function(){return this._applyCombination(xp,[3])},tetrad:function(){return this._applyCombination(xp,[4])}},lp.fromRatio=function(e,t){if("object"==sp(e)){var n={};for(var r in e)e.hasOwnProperty(r)&&(n[r]="a"===r?e[r]:Lp(e[r]));e=n}return lp(e,t)},lp.equals=function(e,t){return!(!e||!t)&&lp(e).toRgbString()==lp(t).toRgbString()},lp.random=function(){return lp.fromRatio({r:Math.random(),g:Math.random(),b:Math.random()})},lp.mix=function(e,t,n){n=0===n?0:n||50;var r=lp(e).toRgb(),i=lp(t).toRgb(),s=n/100;return lp({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})}, // =4.5;break;case"AAlarge":i=s>=3;break;case"AAAsmall":i=s>=7}return i},lp.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;ul&&(l=r,o=lp(t[u]));return lp.isReadable(e,o,{level:s,size:a})||!i?o:(n.includeFallbackColors=!1,lp.mostReadable(e,["#fff","#000"],n))};var wp=lp.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"},Ep=lp.hexNames=function(e){var t={};for(var n in e)e.hasOwnProperty(n)&&(t[e[n]]=n);return t}(wp);function Ap(e){return e=parseFloat(e),(isNaN(e)||e<0||e>1)&&(e=1),e}function Rp(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 Cp(e){return Math.min(1,Math.max(0,e))}function Np(e){return parseInt(e,16)}function Pp(e){return 1==e.length?"0"+e:""+e}function Lp(e){return e<=1&&(e=100*e+"%"),e}function Dp(e){return Math.round(255*parseFloat(e)).toString(16)}function Ip(e){return Np(e)/255}var Up,Op,Fp,Bp=(Op="[\\s|\\(]+("+(Up="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)")+")[,|\\s]+("+Up+")[,|\\s]+("+Up+")\\s*\\)?",Fp="[\\s|\\(]+("+Up+")[,|\\s]+("+Up+")[,|\\s]+("+Up+")[,|\\s]+("+Up+")\\s*\\)?",{CSS_UNIT:new RegExp(Up),rgb:new RegExp("rgb"+Op),rgba:new RegExp("rgba"+Fp),hsl:new RegExp("hsl"+Op),hsla:new RegExp("hsla"+Fp),hsv:new RegExp("hsv"+Op),hsva:new RegExp("hsva"+Fp),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 kp(e){return!!Bp.CSS_UNIT.exec(e)}function zp(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n1&&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 Hp(this,t),Yp(n=Gp(this,t),"scene",void 0),Wp(n,df,void 0),Wp(n,pf,void 0),n.scene=e,$p(df,n,s),$p(pf,n,o),n.onRemoveObj(function(){}),n}return Qp(t,e),qp(t,[{key:"onCreateObj",value:function(e){var n=this;return rf(t,"onCreateObj",this)([function(t){var r=e(t);return t[jp(pf,n)]=r,r[jp(df,n)]=t,n.scene.add(r),r}]),this}},{key:"onRemoveObj",value:function(e){var n=this;return rf(t,"onRemoveObj",this)([function(r,i){var s=rf(t,"getData",n)([r]);e(r,i),n.scene.remove(r),hf(r),delete s[jp(pf,n)]}]),this}}])}(tp),mf=function(e){return isNaN(e)?parseInt(lp(e).toHex(),16):e},gf=function(e){return isNaN(e)?lp(e).getAlpha():1},_f=function e(){var t=new Id,n=[],r=[],i=rp;function s(e){let s=t.get(e);if(void 0===s){if(i!==rp)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 Id;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)},np.apply(s,arguments),s}(ip);function vf(e,t,n){t&&"string"==typeof n&&e.filter(function(e){return!e[n]}).forEach(function(e){e[n]=_f(t(e))})}var yf=window.THREE?window.THREE:{Group:is,Mesh:Vi,MeshLambertMaterial:ca,Color:si,BufferGeometry:Ci,BufferAttribute:_i,Matrix4:pr,Vector3:gn,SphereGeometry:ta,CylinderGeometry:ks,TubeGeometry:na,ConeGeometry:zs,Line:class extends zr{constructor(e=new Ci,t=new ws){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;e0){const n=e[t[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e0&&(d.fire("changed",o),o.length=0)}function w(e){if("function"!=typeof e)throw new Error("Function is expected to iterate over graph nodes. You passed "+e);for(var t=n.values(),r=t.next();!r.done;){if(e(r.value))return!0;r=t.next()}}},forcelayout:rd},xf=(new yf.BufferGeometry).setAttribute?"setAttribute":"addAttribute",Tf=(new yf.BufferGeometry).applyMatrix4?"applyMatrix4":"applyMatrix",Sf=Ld({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()0){var f=o.x-s.x,m=o.y-s.y||0,g=(new yf.Vector3).subVectors(h,c),_=g.clone().multiplyScalar(l).cross(0!==f||0!==m?new yf.Vector3(0,0,1):new yf.Vector3(0,1,0)).applyAxisAngle(g.normalize(),p).add((new yf.Vector3).addVectors(c,h).divideScalar(2));u=new yf.QuadraticBezierCurve3(c,_,h)}else{var v=70*l,y=-p,b=y+Math.PI/2;u=new yf.CubicBezierCurve3(c,new yf.Vector3(v*Math.cos(b),v*Math.sin(b),0).add(c),new yf.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=nf(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[xf]("position",new yf.BufferAttribute(new Float32Array(3*g.length),3)),m.geometry.setFromPoints(g)}else{var _=m.geometry.getAttribute("position");_&&_.array&&6===_.array.length||m.geometry[xf]("position",_=new yf.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 yf.TubeGeometry(f,p,v,e.linkResolution,!1);m.geometry.dispose(),m.geometry=y}else{if(!m.geometry.type.match(/^Cylinder(Buffer)?Geometry$/)){var b=Math.ceil(10*n(i))/10/2,x=new yf.CylinderGeometry(b,b,1,e.linkResolution,1,!1);x[Tf]((new yf.Matrix4).makeTranslation(0,.5,0)),x[Tf]((new yf.Matrix4).makeRotationX(Math.PI/2)),m.geometry.dispose(),m.geometry=x}var T=new yf.Vector3(c.x,c.y||0,c.z||0),S=new yf.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=Dd(e.linkDirectionalArrowRelPos),n=Dd(e.linkDirectionalArrowLength),r=Dd(e.nodeVal),e.arrowDataMapper.entries().forEach(function(i){var s=nf(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/_),b=g((v-f)/_);["x","y","z"].forEach(function(e){return l.position[e]=b[e]});var x=Xp(yf.Vector3,sf(["x","y","z"].map(function(e){return y[e]})));l.parent.localToWorld(x),l.lookAt(x)}}}),i=Dd(e.linkDirectionalParticleSpeed),s=Dd(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(sf(r||[]),sf(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 hf(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 yf.Group;n.__linkThreeObjType="singleHopPhotons",t.__singleHopPhotonsObj=n,e.graphScene.add(n)}var r=Dd(e.linkDirectionalParticleThreeObject)(t);if(r&&e.linkDirectionalParticleThreeObject===r&&(r=r.clone()),!r){var i=Dd(e.linkDirectionalParticleWidth),s=Math.ceil(10*i(t))/10/2,a=e.linkDirectionalParticleResolution,o=new yf.SphereGeometry(s,a,a),l=Dd(e.linkColor),u=Dd(e.linkDirectionalParticleColor)(t)||l(t)||"#f0f0f0",c=new yf.Color(mf(u)),h=3*e.linkOpacity,d=new yf.MeshLambertMaterial({color:c,transparent:!0,opacity:h});r=new yf.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 yf.Box3;i.copy(n.geometry.boundingBox).applyMatrix4(n.matrixWorld),r.push(i)}return r.concat.apply(r,sf((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,sf(["x","y","z"].map(function(e){return Yp({},e,[Bd(n,function(t){return t.min[e]}),Fd(n,function(t){return t.max[e]})])}))):null}},stateInit:function(){return{d3ForceLayout:gh().force("link",Vc()).force("charge",_h()).force("center",hc()).force("dagRadial",null).stop(),engineRunning:!1}},init:function(e,t){t.graphScene=e,t.nodeDataMapper=new ff(e,{objBindAttr:"__threeObj"}),t.linkDataMapper=new ff(e,{objBindAttr:"__lineObj"}),t.arrowDataMapper=new ff(e,{objBindAttr:"__arrowObj"}),t.particlesDataMapper=new ff(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"])&&vf(e.graphData.nodes,Dd(e.nodeAutoColorBy),e.nodeColor),null!==e.linkAutoColorBy&&n(["linkAutoColorBy","graphData","linkColor"])&&vf(e.graphData.links,Dd(e.linkAutoColorBy),e.linkColor),e._flushObjects||n(["graphData","nodeThreeObject","nodeThreeObjectExtend","nodeVal","nodeColor","nodeVisibility","nodeRelSize","nodeResolution","nodeOpacity"])){var r=Dd(e.nodeThreeObject),i=Dd(e.nodeThreeObjectExtend),s=Dd(e.nodeVal),a=Dd(e.nodeColor),o=Dd(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 yf.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 yf.SphereGeometry(i,o,o)),t.geometry.dispose(),t.geometry=l[r]);var c=a(n),h=new yf.Color(mf(c||"#ffffaa")),d=e.nodeOpacity*gf(c);"MeshLambertMaterial"===t.material.type&&t.material.color.equals(h)&&t.material.opacity===d||(u.hasOwnProperty(c)||(u[c]=new yf.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=Dd(e.linkThreeObject),h=Dd(e.linkThreeObjectExtend),d=Dd(e.linkMaterial),p=Dd(e.linkVisibility),f=Dd(e.linkColor),m=Dd(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),hf(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 yf.Mesh;else{var a=new yf.BufferGeometry;a[xf]("position",new yf.BufferAttribute(new Float32Array(6),3)),n=new yf.Line(a)}return i?s?((r=new yf.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 yf.CylinderGeometry(a,a,1,o,1,!1);l[Tf]((new yf.Matrix4).makeTranslation(0,.5,0)),l[Tf]((new yf.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 yf.Color(mf(c||"#f0f0f0")),p=e.linkOpacity*gf(c),y=s?"MeshLambertMaterial":"LineBasicMaterial";if(r.material.type!==y||!r.material.color.equals(h)||r.material.opacity!==p){var b=s?_:v;b.hasOwnProperty(c)||(b[c]=new yf[y]({color:h,transparent:p<1,opacity:p,depthWrite:p>=1})),r.material.dispose(),r.material=b[c]}}}}).digest(y),e.linkDirectionalArrowLength||t.hasOwnProperty("linkDirectionalArrowLength")){var b=Dd(e.linkDirectionalArrowLength),x=Dd(e.linkDirectionalArrowColor);e.arrowDataMapper.onCreateObj(function(){var e=new yf.Mesh(void 0,new yf.MeshLambertMaterial({transparent:!0}));return e.__linkThreeObjType="arrow",e}).onUpdateObj(function(t,n){var r=b(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 yf.ConeGeometry(.25*r,r,i);s.translate(0,r/2,0),s.rotateX(Math.PI/2),t.geometry.dispose(),t.geometry=s}var a=x(n)||f(n)||"#f0f0f0";t.material.color=new yf.Color(mf(a)),t.material.opacity=3*e.linkOpacity*gf(a)}).digest(y.filter(b))}if(e.linkDirectionalParticles||t.hasOwnProperty("linkDirectionalParticles")){var T=Dd(e.linkDirectionalParticles),S=Dd(e.linkDirectionalParticleWidth),M=Dd(e.linkDirectionalParticleColor),w=Dd(e.linkDirectionalParticleThreeObject),E={},A={};e.particlesDataMapper.onCreateObj(function(){var e=new yf.Group;return e.__linkThreeObjType="photons",e.__photonDataMapper=new ff(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 yf.SphereGeometry(o,l,l)),r=A[o]);var u=M(n)||f(n)||"#f0f0f0",c=new yf.Color(mf(u)),h=3*e.linkOpacity;s&&s.material.color.equals(c)&&s.material.opacity===h?i=s.material:(E.hasOwnProperty(u)||(E[u]=new yf.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 yf.Mesh(r,i)}).onUpdateObj(function(e){e.geometry=r,e.material=i}).digest(sf(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"===of(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(sf(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(sf(r),[s]),i+(s.skip?0:1)))},a=0,o=n.length;a1&&(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[1,2,3].includes(e))||2,c()},u.strength=function(e){return arguments.length?(l="function"==typeof e?e:Fc(+e),c(),u):l},u.radius=function(t){return arguments.length?(e="function"==typeof t?t:Fc(+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=bf.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=bf.forcelayout(F,function(e){for(var t=1;t0&&e.d3ForceLayout.alpha()2&&void 0!==arguments[2]&&arguments[2],n=function(n){function r(){var n;Hp(this,r);for(var i=arguments.length,s=new Array(i),a=0;a1&&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}(Sf,(window.THREE?window.THREE:{Group:is}).Group,!0);const wf=["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"],Ef=new WeakMap;class Af{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=!0===e.object.isSkinnedMesh,this.refreshUniforms=wf,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}t.lights=this.getLightsData(e.lightsNode.getLights()),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!!(e.context.modelViewMatrix||e.context.modelNormalViewMatrix||e.context.getAO||e.context.getShadow)}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,t){const{object:n,material:r,geometry:i}=e,s=this.getRenderObjectData(e);if(!0!==s.worldMatrix.equals(n.matrixWorld))return s.worldMatrix.copy(n.matrixWorld),!1;const a=s.material;for(const e in a){const t=a[e],n=r[e];if(void 0!==t.equals){if(!1===t.equals(n))return t.copy(n),!1}else if(!0===n.isTexture){if(t.id!==n.id||t.version!==n.version)return t.id=n.id,t.version=n.version,!1}else if(t!==n)return a[e]=n,!1}if(a.transmission>0){const{width:t,height:n}=e.context;if(s.bufferWidth!==t||s.bufferHeight!==n)return s.bufferWidth=t,s.bufferHeight=n,!1}const o=s.geometry,l=i.attributes,u=o.attributes,c=Object.keys(u),h=Object.keys(l);if(o.id!==i.id)return o.id=i.id,!1;if(c.length!==h.length)return s.geometry.attributes=this.getAttributesData(l),!1;for(const e of c){const t=u[e],n=l[e];if(void 0===n)return delete u[e],!1;if(t.version!==n.version)return t.version=n.version,!1}const d=i.index,p=o.indexVersion,f=d?d.version:null;if(p!==f)return o.indexVersion=f,!1;if(o.drawRange.start!==i.drawRange.start||o.drawRange.count!==i.drawRange.count)return o.drawRange.start=i.drawRange.start,o.drawRange.count=i.drawRange.count,!1;if(s.morphTargetInfluences){let e=!1;for(let t=0;t>>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 Cf=e=>Rf(e),Nf=e=>Rf(e),Pf=(...e)=>Rf(e),Lf=new Map([[1,"float"],[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),Df=new WeakMap;function If(e){return Lf.get(e)}function Uf(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 Of(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 si(...t):"vec2"===n?new fn(...t):"vec3"===n?new gn(...t):"vec4"===n?new Un(...t):"mat2"===n?new $a(...t):"mat3"===n?new yn(...t):"mat4"===n?new pr(...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 Ff(e){let t=Df.get(e);return void 0===t&&(t={},Df.set(e,t)),t}const Bf="vertex",kf="none",zf="frame",Vf="render",Gf="object",Hf="readOnly",jf="writeOnly",Wf="readWrite",$f=["setup","analyze","generate"],Xf=["fragment","vertex","compute"],qf=["x","y","z","w"],Yf={analyze:"setup",generate:"analyze"};let Kf=0;class Zf extends tn{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=kf,this.updateBeforeType=kf,this.updateAfterType=kf,this.uuid=pn.generateUUID(),this.version=0,this.name="",this.global=!1,this.parents=!1,this.isNode=!0,this._beforeNodes=null,this._cacheKey=null,this._cacheKeyVersion=0,Object.defineProperty(this,"id",{value:Kf++})}set needsUpdate(e){!0===e&&this.version++}get type(){return this.constructor.type}onUpdate(e,t){return this.updateType=t,this.update=e.bind(this),this}onFrameUpdate(e){return this.onUpdate(e,zf)}onRenderUpdate(e){return this.onUpdate(e,Vf)}onObjectUpdate(e){return this.onUpdate(e,Gf)}onReference(e){return this.updateReference=e.bind(this),this}updateReference(){return this}isGlobal(){return this.global}*getChildren(){for(const{childNode:e}of this._getChildren())yield e}dispose(){this.dispatchEvent({type:"dispose"})}traverse(e){e(this);for(const t of this.getChildren())t.traverse(e)}_getChildren(e=new Set){const t=[];e.add(this);for(const n of Object.getOwnPropertyNames(this)){const r=this[n];if(!0!==n.startsWith("_")&&!e.has(r))if(!0===Array.isArray(r))for(let e=0;e0&&(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 Qf extends Zf{static get type(){return"ArrayElementNode"}constructor(e,t){super(),this.node=e,this.indexNode=t,this.isArrayElementNode=!0}getNodeType(e){return this.node.getElementType(e)}getMemberType(e,t){return this.node.getMemberType(e,t)}generate(e){const t=this.indexNode.getNodeType(e);return`${this.node.build(e)}[ ${this.indexNode.build(e,!e.isVector(t)&&e.isInteger(t)?t:"uint")} ]`}}class Jf extends Zf{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 em extends Zf{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 tm extends em{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){Jt(`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&&(Jt(`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);if(e.getComponentType(l)!==s){const t=e.getTypeFromLength(u,s);i=e.format(i,l,t)}a.push(i)}const l=`${e.getType(n)}( ${a.join(", ")} )`;return e.format(l,n,t)}}const nm=qf.join("");class rm extends Zf{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(qf.indexOf(t)+1,e);return e}getComponentType(e){return e.getComponentType(this.node.getNodeType(e))}getNodeType(e){return e.getTypeFromLength(this.components.length,this.getComponentType(e))}getScope(){return this.node.getScope()}generate(e,t){const 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===nm.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 im extends em{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(e=>e.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"))(e).split("").sort().join("");Zf.prototype.assign=function(...e){if(!0!==this.isStackNode)return null!==cm?cm.assign(this,...e):Jt("TSL: No stack defined for assign operation. Make sure the assign is inside a Fn()."),this;{const t=hm.get("assign");return this.addToStack(t(...e))}},Zf.prototype.toVarIntent=function(){return this},Zf.prototype.get=function(e){return new um(this,e)};const fm={};function mm(e,t,n){fm[e]=fm[t]=fm[n]={get(){this._cache=this._cache||{};let t=this._cache[e];return void 0===t&&(t=new rm(this,e),this._cache[e]=t),t},set(t){this[e].assign(zm(t))}};const r=e.toUpperCase(),i=t.toUpperCase(),s=n.toUpperCase();Zf.prototype["set"+r]=Zf.prototype["set"+i]=Zf.prototype["set"+s]=function(t){const n=pm(e);return new im(this,n,zm(t))},Zf.prototype["flip"+r]=Zf.prototype["flip"+i]=Zf.prototype["flip"+s]=function(){const t=pm(e);return new sm(this,t)}}const gm=["x","y","z","w"],_m=["r","g","b","a"],vm=["s","t","p","q"];for(let e=0;e<4;e++){let t=gm[e],n=_m[e],r=vm[e];mm(t,n,r);for(let i=0;i<4;i++){t=gm[e]+gm[i],n=_m[e]+_m[i],r=vm[e]+vm[i],mm(t,n,r);for(let s=0;s<4;s++){t=gm[e]+gm[i]+gm[s],n=_m[e]+_m[i]+_m[s],r=vm[e]+vm[i]+vm[s],mm(t,n,r);for(let a=0;a<4;a++)t=gm[e]+gm[i]+gm[s]+gm[a],n=_m[e]+_m[i]+_m[s]+_m[a],r=vm[e]+vm[i]+vm[s]+vm[a],mm(t,n,r)}}}for(let e=0;e<32;e++)fm[e]={get(){this._cache=this._cache||{};let t=this._cache[e];return void 0===t&&(t=new Qf(this,new lm(e,"uint")),this._cache[e]=t),t},set(t){this[e].assign(zm(t))}};Object.defineProperties(Zf.prototype,fm);const ym=new WeakMap,bm=function(e,t=null){for(const n in e)e[n]=zm(e[n],t);return e},xm=function(e,t=null){const n=e.length;for(let r=0;ro?(Jt(`TSL: "${n}" parameter length exceeds limit.`),t.slice(0,o)):t}return null===t?s=(...t)=>i(new e(...Hm(u(t)))):null!==n?(n=zm(n),s=(...r)=>i(new e(t,...Hm(u(r)),n))):s=(...n)=>i(new e(t,...Hm(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},Sm=function(e,...t){return new e(...Hm(t))};class Mm extends Zf{constructor(e,t){super(),this.shaderNode=e,this.rawInputs=t,this.isShaderCallNodeInternal=!0}getNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}getElementType(e){return this.getOutputNode(e).getElementType(e)}getMemberType(e,t){return this.getOutputNode(e).getMemberType(e,t)}call(e){const{shaderNode:t,rawInputs:n}=this,r=e.getNodeProperties(t),i=e.getClosestSubBuild(t.subBuilds)||"",s=i||"default";if(r[s])return r[s];const a=e.subBuildFn,o=e.fnCall;e.subBuildFn=i,e.fnCall=this;let l=null;if(t.layout){let r=ym.get(e.constructor);void 0===r&&(r=new WeakMap,ym.set(e.constructor,r));let i=r.get(t);void 0===i&&(i=zm(e.buildFunctionNode(t)),r.set(t,i)),e.addInclude(i);const s=n?function(e){let t;Gm(e);t=e[0]&&(e[0].isNode||Object.getPrototypeOf(e[0])!==Object.prototype)?[...e]:e[0];return t}(n):null;l=zm(i.call(s))}else{const r=new Proxy(e,{get:(e,t,n)=>{let r;return r=Symbol.iterator===t?function*(){yield}:Reflect.get(e,t,n),r}}),i=n?function(e){let t=0;return Gm(e),new Proxy(e,{get:(n,r,i)=>{let s;if("length"===r)return s=e.length,s;if(Symbol.iterator===r)s=function*(){for(const t of e)yield zm(t)};else{if(e.length>0)if(Object.getPrototypeOf(e[0])===Object.prototype){const n=e[0];s=void 0===n[r]?n[t++]:Reflect.get(n,r,i)}else e[0]instanceof Zf&&(s=void 0===e[r]?e[t++]:Reflect.get(e,r,i));else s=Reflect.get(n,r,i);s=zm(s)}return s}})}(n):null,s=Array.isArray(n)?n.length>0:null!==n,a=t.jsFunc,o=s||a.length>1?a(i,r):a(r);l=zm(o)}return e.subBuildFn=a,e.fnCall=o,t.once&&(r[s]=l),l}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),o=e.fnCall;if(e.fnCall=this,"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 e.fnCall=o,n}}class wm extends Zf{constructor(e,t){super(t),this.jsFunc=e,this.layout=null,this.global=!0,this.once=!1}setLayout(e){return this.layout=e,this}getLayout(){return this.layout}call(e=null){return new Mm(this,e)}setup(){return this.call()}}const Em=[!1,!0],Am=[0,1,2,3],Rm=[-1,-2],Cm=[.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],Nm=new Map;for(const e of Em)Nm.set(e,new lm(e));const Pm=new Map;for(const e of Am)Pm.set(e,new lm(e,"uint"));const Lm=new Map([...Pm].map(e=>new lm(e.value,"int")));for(const e of Rm)Lm.set(e,new lm(e,"int"));const Dm=new Map([...Lm].map(e=>new lm(e.value)));for(const e of Cm)Dm.set(e,new lm(e));for(const e of Cm)Dm.set(-e,new lm(-e));const Im={bool:Nm,uint:Pm,ints:Lm,float:Dm},Um=new Map([...Nm,...Dm]),Om=(e,t)=>Um.has(e)?Um.get(e):!0===e.isNode?e:new lm(e,t),Fm=function(e,t=null){return(...n)=>{for(const t of n)if(void 0===t)return Jt(`TSL: Invalid parameter for the type "${e}".`),new lm(0,e);if((0===n.length||!["bool","float","int","uint"].includes(e)&&n.every(e=>{const t=typeof e;return"object"!==t&&"function"!==t}))&&(n=[Of(e,...n)]),1===n.length&&null!==t&&t.has(n[0]))return Vm(t.get(n[0]));if(1===n.length){const t=Om(n[0],e);return t.nodeType===e?Vm(t):Vm(new Jf(t,e))}const r=n.map(e=>Om(e));return Vm(new tm(r,e))}},Bm=e=>"object"==typeof e&&null!==e?e.value:e;function km(e,t){return new wm(e,t)}const zm=(e,t=null)=>function(e,t=null){const n=Uf(e);return"node"===n?e:null===t&&("float"===n||"boolean"===n)||n&&"shader"!==n&&"string"!==n?zm(Om(e,t)):"shader"===n?e.isFn?e:Ym(e):e}(e,t),Vm=(e,t=null)=>zm(e,t).toVarIntent(),Gm=(e,t=null)=>new bm(e,t),Hm=(e,t=null)=>new xm(e,t),jm=(e,t=null,n=null,r=null)=>new Tm(e,t,n,r),Wm=(e,...t)=>new Sm(e,...t),$m=(e,t=null,n=null,r={})=>new Tm(e,t,n,{...r,intent:!0});let Xm=0;class qm extends Zf{constructor(e,t=null){super();let n=null;null!==t&&("object"==typeof t?n=t.return:("string"==typeof t?n=t:Jt("TSL: Invalid layout type."),t=null)),this.shaderNode=new km(e,n),null!==t&&this.setLayout(t),this.isFn=!0}setLayout(e){const t=this.shaderNode.nodeType;if("object"!=typeof e.inputs){const n={name:"fn"+Xm++,type:t,inputs:[]};for(const t in e)"return"!==t&&n.inputs.push({name:t,type:e[t]});e=n}return this.shaderNode.setLayout(e),this}getNodeType(e){return this.shaderNode.getNodeType(e)||"float"}call(...e){const t=this.shaderNode.call(e);return"void"===this.shaderNode.nodeType&&t.toStack(),t.toVarIntent()}once(e=null){return this.shaderNode.once=!0,this.shaderNode.subBuilds=e,this}generate(e){const t=this.getNodeType(e);return Jt('TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".'),e.generateConst(t)}}function Ym(e,t=null){const n=new qm(e,t);return new Proxy(()=>{},{apply:(e,t,r)=>n.call(...r),get:(e,t,r)=>Reflect.get(n,t,r),set:(e,t,r,i)=>Reflect.set(n,t,r,i)})}const Km=e=>{cm=e},Zm=()=>cm,Qm=(...e)=>cm.If(...e);function Jm(e){return cm&&cm.addToStack(e),e}dm("toStack",Jm);const eg=new Fm("color"),tg=new Fm("float",Im.float),ng=new Fm("int",Im.ints),rg=new Fm("uint",Im.uint),ig=new Fm("bool",Im.bool),sg=new Fm("vec2"),ag=new Fm("ivec2"),og=new Fm("uvec2"),lg=new Fm("bvec2"),ug=new Fm("vec3"),cg=new Fm("ivec3"),hg=new Fm("uvec3"),dg=new Fm("bvec3"),pg=new Fm("vec4"),fg=new Fm("ivec4"),mg=new Fm("uvec4"),gg=new Fm("bvec4"),_g=new Fm("mat2"),vg=new Fm("mat3"),yg=new Fm("mat4");dm("toColor",eg),dm("toFloat",tg),dm("toInt",ng),dm("toUint",rg),dm("toBool",ig),dm("toVec2",sg),dm("toIVec2",ag),dm("toUVec2",og),dm("toBVec2",lg),dm("toVec3",ug),dm("toIVec3",cg),dm("toUVec3",hg),dm("toBVec3",dg),dm("toVec4",pg),dm("toIVec4",fg),dm("toUVec4",mg),dm("toBVec4",gg),dm("toMat2",_g),dm("toMat3",vg),dm("toMat4",yg);dm("element",jm(Qf).setParameterLength(2)),dm("convert",(e,t)=>zm(new Jf(zm(e),t))),dm("append",e=>(Qt("TSL: .append() has been renamed to .toStack()."),Jm(e)));class bg extends Zf{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}customCacheKey(){return Cf(this.type+":"+(this.name||"")+":"+(this.varying?"1":"0"))}getHash(e){return this.name||super.getHash(e)}generate(e){let t;return!0===this.varying?(t=e.getVaryingFromNode(this,this.name),t.needsInterpolation=!0):t=e.getVarFromNode(this,this.name),e.getPropertyName(t)}}const xg=(e,t)=>new bg(e,t),Tg=(e,t)=>new bg(e,t,!0),Sg=Wm(bg,"vec4","DiffuseColor"),Mg=Wm(bg,"vec3","DiffuseContribution"),wg=Wm(bg,"vec3","EmissiveColor"),Eg=Wm(bg,"float","Roughness"),Ag=Wm(bg,"float","Metalness"),Rg=Wm(bg,"float","Clearcoat"),Cg=Wm(bg,"float","ClearcoatRoughness"),Ng=Wm(bg,"vec3","Sheen"),Pg=Wm(bg,"float","SheenRoughness"),Lg=Wm(bg,"float","Iridescence"),Dg=Wm(bg,"float","IridescenceIOR"),Ig=Wm(bg,"float","IridescenceThickness"),Ug=Wm(bg,"float","AlphaT"),Og=Wm(bg,"float","Anisotropy"),Fg=Wm(bg,"vec3","AnisotropyT"),Bg=Wm(bg,"vec3","AnisotropyB"),kg=Wm(bg,"color","SpecularColor"),zg=Wm(bg,"color","SpecularColorBlended"),Vg=Wm(bg,"float","SpecularF90"),Gg=Wm(bg,"float","Shininess"),Hg=Wm(bg,"vec4","Output"),jg=Wm(bg,"float","dashSize"),Wg=Wm(bg,"float","gapSize"),$g=Wm(bg,"float","IOR"),Xg=Wm(bg,"float","Transmission"),qg=Wm(bg,"float","Thickness"),Yg=Wm(bg,"float","AttenuationDistance"),Kg=Wm(bg,"color","AttenuationColor"),Zg=Wm(bg,"float","Dispersion");class Qg extends Zf{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 Jg=e=>new Qg(e),e_=(e,t=0)=>new Qg(e,!0,t),t_=e_("frame"),n_=e_("render"),r_=Jg("object");class i_ extends am{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=r_}setName(e){return this.name=e,this}label(e){return Qt('TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}onUpdate(e,t){return e=e.bind(this),super.onUpdate(t=>{const n=e(t,this);void 0!==n&&(this.value=n)},t)}getInputType(e){let t=super.getInputType(e);return"bool"===t&&(t="uint"),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.nodeName),o=e.getPropertyName(a);void 0!==e.context.nodeName&&delete e.context.nodeName;let l=o;if("bool"===n){const t=e.getDataFromNode(this);let r=t.propertyName;if(void 0===r){const i=e.getVarFromNode(this,null,"bool");r=e.getPropertyName(i),t.propertyName=r,l=e.format(o,s,n),e.addLineFlowCode(`${r} = ${l}`,this)}l=r}return e.format(l,n,t)}}const s_=(e,t)=>{const n=(e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null)(t||e);if(n===e&&(e=Of(n)),e&&!0===e.isNode){let t=e.value;e.traverse(e=>{!0===e.isConstNode&&(t=e.value)}),e=t}return new i_(e,n)};class a_ extends em{static get type(){return"ArrayNode"}constructor(e,t,n=null){super(e),this.count=t,this.values=n,this.isArrayNode=!0}getArrayCount(){return this.count}getNodeType(e){return null===this.nodeType?this.values[0].getNodeType(e):this.nodeType}getElementType(e){return this.getNodeType(e)}getMemberType(e,t){return null===this.nodeType?this.values[0].getMemberType(e,t):super.getMemberType(e,t)}generate(e){const t=this.getNodeType(e);return e.generateArray(t,this.count,this.values)}}dm("toArray",(e,t)=>((...e)=>{let t;if(1===e.length){const n=e[0];t=new a_(null,n.length,n)}else{const n=e[0],r=e[1];t=new a_(n,r)}return zm(t)})(Array(t).fill(e)));class o_ extends em{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 qf.join("").slice(0,n)!==t.components}return!1}setup(e){const{targetNode:t,sourceNode:n}=this,r=t.getScope();e.getDataFromNode(r).assign=!0;const i=e.getNodeProperties(this);i.sourceNode=n,i.targetNode=t.context({assign:!0})}generate(e,t){const{targetNode:n,sourceNode:r}=e.getNodeProperties(this),i=this.needsSplitAssign(e),s=n.build(e),a=n.getNodeType(e),o=r.build(e,a),l=r.getNodeType(e),u=e.getDataFromNode(this);let c;if(!0===u.initialized)"void"!==t&&(c=s);else if(i){const r=e.getVarFromNode(this,null,a),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{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)Jt("TSL: The number of provided parameters exceeds the expected number of inputs in 'Fn()'."),i.length=r.length;else if(i.length(t=t.length>1||t[0]&&!0===t[0].isNode?Hm(t):Gm(t[0]),new l_(zm(e),t)));const u_={"==":"equal","!=":"notEqual","<":"lessThan",">":"greaterThan","<=":"lessThanEqual",">=":"greaterThanEqual","%":"mod"};class c_ extends em{static get type(){return"OperatorNode"}constructor(e,t,n,...r){if(super(),r.length>0){let i=new c_(e,t,n);for(let t=0;t>"===n||"<<"===n)return e.getIntegerType(s);if("!"===n||"&&"===n||"||"===n||"^^"===n)return"bool";if("=="===n||"!="===n||"<"===n||">"===n||"<="===n||">="===n){const t=Math.max(e.getTypeLength(s),e.getTypeLength(a));return t>1?`bvec${t}`:"bool"}if(e.isMatrix(s)){if("float"===a)return s;if(e.isVector(a))return e.getVectorFromMatrix(s);if(e.isMatrix(a))return s}else if(e.isMatrix(a)){if("float"===s)return a;if(e.isVector(s))return e.getVectorFromMatrix(a)}return e.getTypeLength(a)>e.getTypeLength(s)?a:s}generate(e,t){const n=this.op,{aNode:r,bNode:i}=this,s=this.getNodeType(e,t);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===Gt;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 h_=$m(c_,"+").setParameterLength(2,1/0).setName("add"),d_=$m(c_,"-").setParameterLength(2,1/0).setName("sub"),p_=$m(c_,"*").setParameterLength(2,1/0).setName("mul"),f_=$m(c_,"/").setParameterLength(2,1/0).setName("div"),m_=$m(c_,"%").setParameterLength(2).setName("mod"),g_=$m(c_,"==").setParameterLength(2).setName("equal"),__=$m(c_,"!=").setParameterLength(2).setName("notEqual"),v_=$m(c_,"<").setParameterLength(2).setName("lessThan"),y_=$m(c_,">").setParameterLength(2).setName("greaterThan"),b_=$m(c_,"<=").setParameterLength(2).setName("lessThanEqual"),x_=$m(c_,">=").setParameterLength(2).setName("greaterThanEqual"),T_=$m(c_,"&&").setParameterLength(2,1/0).setName("and"),S_=$m(c_,"||").setParameterLength(2,1/0).setName("or"),M_=$m(c_,"!").setParameterLength(1).setName("not"),w_=$m(c_,"^^").setParameterLength(2).setName("xor"),E_=$m(c_,"&").setParameterLength(2).setName("bitAnd"),A_=$m(c_,"~").setParameterLength(1).setName("bitNot"),R_=$m(c_,"|").setParameterLength(2).setName("bitOr"),C_=$m(c_,"^").setParameterLength(2).setName("bitXor"),N_=$m(c_,"<<").setParameterLength(2).setName("shiftLeft"),P_=$m(c_,">>").setParameterLength(2).setName("shiftRight"),L_=Ym(([e])=>(e.addAssign(1),e)),D_=Ym(([e])=>(e.subAssign(1),e)),I_=Ym(([e])=>{const t=ng(e).toConst();return e.addAssign(1),t}),U_=Ym(([e])=>{const t=ng(e).toConst();return e.subAssign(1),t});dm("add",h_),dm("sub",d_),dm("mul",p_),dm("div",f_),dm("mod",m_),dm("equal",g_),dm("notEqual",__),dm("lessThan",v_),dm("greaterThan",y_),dm("lessThanEqual",b_),dm("greaterThanEqual",x_),dm("and",T_),dm("or",S_),dm("not",M_),dm("xor",w_),dm("bitAnd",E_),dm("bitNot",A_),dm("bitOr",R_),dm("bitXor",C_),dm("shiftLeft",N_),dm("shiftRight",P_),dm("incrementBefore",L_),dm("decrementBefore",D_),dm("increment",I_),dm("decrement",U_);dm("modInt",(e,t)=>(Qt('TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.'),m_(ng(e),ng(t))));class O_ extends em{static get type(){return"MathNode"}constructor(e,t,n=null,r=null){if(super(),(e===O_.MAX||e===O_.MIN)&&arguments.length>3){let i=new O_(e,t,n);for(let t=2;ts&&i>a?t:s>a?n:a>i?r:t}getNodeType(e){const t=this.method;return t===O_.LENGTH||t===O_.DISTANCE||t===O_.DOT?"float":t===O_.CROSS?"vec3":t===O_.ALL||t===O_.ANY?"bool":t===O_.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===O_.ONE_MINUS)i=d_(1,t);else if(r===O_.RECIPROCAL)i=f_(1,t);else if(r===O_.DIFFERENCE)i=sv(d_(t,n));else if(r===O_.TRANSFORM_DIRECTION){let r=t,s=n;e.isMatrix(r.getNodeType(e))?s=pg(ug(s),0):r=pg(ug(r),0);const a=p_(r,s).xyz;i=Z_(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===O_.NEGATE)return e.format("( - "+s.build(e,i)+" )",r,t);{const u=[];return n===O_.CROSS?u.push(s.build(e,r),a.build(e,r)):l===Gt&&n===O_.STEP?u.push(s.build(e,1===e.getTypeLength(s.getNodeType(e))?"float":i),a.build(e,i)):l!==Gt||n!==O_.MIN&&n!==O_.MAX?n===O_.REFRACT?u.push(s.build(e,i),a.build(e,i),o.build(e,"float")):n===O_.MIX?u.push(s.build(e,i),a.build(e,i),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":i)):(l===Ht&&n===O_.ATAN&&null!==a&&(n="atan2"),"fragment"===e.shaderStage||n!==O_.DFDX&&n!==O_.DFDY||(Qt(`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}}O_.ALL="all",O_.ANY="any",O_.RADIANS="radians",O_.DEGREES="degrees",O_.EXP="exp",O_.EXP2="exp2",O_.LOG="log",O_.LOG2="log2",O_.SQRT="sqrt",O_.INVERSE_SQRT="inversesqrt",O_.FLOOR="floor",O_.CEIL="ceil",O_.NORMALIZE="normalize",O_.FRACT="fract",O_.SIN="sin",O_.COS="cos",O_.TAN="tan",O_.ASIN="asin",O_.ACOS="acos",O_.ATAN="atan",O_.ABS="abs",O_.SIGN="sign",O_.LENGTH="length",O_.NEGATE="negate",O_.ONE_MINUS="oneMinus",O_.DFDX="dFdx",O_.DFDY="dFdy",O_.ROUND="round",O_.RECIPROCAL="reciprocal",O_.TRUNC="trunc",O_.FWIDTH="fwidth",O_.TRANSPOSE="transpose",O_.DETERMINANT="determinant",O_.INVERSE="inverse",O_.EQUALS="equals",O_.MIN="min",O_.MAX="max",O_.STEP="step",O_.REFLECT="reflect",O_.DISTANCE="distance",O_.DIFFERENCE="difference",O_.DOT="dot",O_.CROSS="cross",O_.POW="pow",O_.TRANSFORM_DIRECTION="transformDirection",O_.MIX="mix",O_.CLAMP="clamp",O_.REFRACT="refract",O_.SMOOTHSTEP="smoothstep",O_.FACEFORWARD="faceforward";const F_=tg(1e-6),B_=tg(Math.PI),k_=$m(O_,O_.ALL).setParameterLength(1),z_=$m(O_,O_.ANY).setParameterLength(1),V_=$m(O_,O_.RADIANS).setParameterLength(1),G_=$m(O_,O_.DEGREES).setParameterLength(1),H_=$m(O_,O_.EXP).setParameterLength(1),j_=$m(O_,O_.EXP2).setParameterLength(1),W_=$m(O_,O_.LOG).setParameterLength(1),$_=$m(O_,O_.LOG2).setParameterLength(1),X_=$m(O_,O_.SQRT).setParameterLength(1),q_=$m(O_,O_.INVERSE_SQRT).setParameterLength(1),Y_=$m(O_,O_.FLOOR).setParameterLength(1),K_=$m(O_,O_.CEIL).setParameterLength(1),Z_=$m(O_,O_.NORMALIZE).setParameterLength(1),Q_=$m(O_,O_.FRACT).setParameterLength(1),J_=$m(O_,O_.SIN).setParameterLength(1),ev=$m(O_,O_.COS).setParameterLength(1),tv=$m(O_,O_.TAN).setParameterLength(1),nv=$m(O_,O_.ASIN).setParameterLength(1),rv=$m(O_,O_.ACOS).setParameterLength(1),iv=$m(O_,O_.ATAN).setParameterLength(1,2),sv=$m(O_,O_.ABS).setParameterLength(1),av=$m(O_,O_.SIGN).setParameterLength(1),ov=$m(O_,O_.LENGTH).setParameterLength(1),lv=$m(O_,O_.NEGATE).setParameterLength(1),uv=$m(O_,O_.ONE_MINUS).setParameterLength(1),cv=$m(O_,O_.DFDX).setParameterLength(1),hv=$m(O_,O_.DFDY).setParameterLength(1),dv=$m(O_,O_.ROUND).setParameterLength(1),pv=$m(O_,O_.RECIPROCAL).setParameterLength(1),fv=$m(O_,O_.TRUNC).setParameterLength(1),mv=$m(O_,O_.FWIDTH).setParameterLength(1),gv=$m(O_,O_.TRANSPOSE).setParameterLength(1),_v=$m(O_,O_.DETERMINANT).setParameterLength(1),vv=$m(O_,O_.INVERSE).setParameterLength(1),yv=$m(O_,O_.MIN).setParameterLength(2,1/0),bv=$m(O_,O_.MAX).setParameterLength(2,1/0),xv=$m(O_,O_.STEP).setParameterLength(2),Tv=$m(O_,O_.REFLECT).setParameterLength(2),Sv=$m(O_,O_.DISTANCE).setParameterLength(2),Mv=$m(O_,O_.DIFFERENCE).setParameterLength(2),wv=$m(O_,O_.DOT).setParameterLength(2),Ev=$m(O_,O_.CROSS).setParameterLength(2),Av=$m(O_,O_.POW).setParameterLength(2),Rv=e=>p_(e,e),Cv=e=>p_(e,e,e,e),Nv=$m(O_,O_.TRANSFORM_DIRECTION).setParameterLength(2),Pv=e=>wv(e,e),Lv=$m(O_,O_.MIX).setParameterLength(3),Dv=(e,t=0,n=1)=>zm(new O_(O_.CLAMP,zm(e),zm(t),zm(n))),Iv=e=>Dv(e),Uv=$m(O_,O_.REFRACT).setParameterLength(3),Ov=$m(O_,O_.SMOOTHSTEP).setParameterLength(3),Fv=$m(O_,O_.FACEFORWARD).setParameterLength(3),Bv=Ym(([e])=>{const t=wv(e.xy,sg(12.9898,78.233)),n=m_(t,B_);return Q_(J_(n).mul(43758.5453))});dm("all",k_),dm("any",z_),dm("equals",(e,t)=>(Qt('TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"'),g_(e,t))),dm("radians",V_),dm("degrees",G_),dm("exp",H_),dm("exp2",j_),dm("log",W_),dm("log2",$_),dm("sqrt",X_),dm("inverseSqrt",q_),dm("floor",Y_),dm("ceil",K_),dm("normalize",Z_),dm("fract",Q_),dm("sin",J_),dm("cos",ev),dm("tan",tv),dm("asin",nv),dm("acos",rv),dm("atan",iv),dm("abs",sv),dm("sign",av),dm("length",ov),dm("lengthSq",Pv),dm("negate",lv),dm("oneMinus",uv),dm("dFdx",cv),dm("dFdy",hv),dm("round",dv),dm("reciprocal",pv),dm("trunc",fv),dm("fwidth",mv),dm("atan2",(e,t)=>(Qt('TSL: "atan2" is overloaded. Use "atan" instead.'),iv(e,t))),dm("min",yv),dm("max",bv),dm("step",(e,t)=>xv(t,e)),dm("reflect",Tv),dm("distance",Sv),dm("dot",wv),dm("cross",Ev),dm("pow",Av),dm("pow2",Rv),dm("pow3",e=>p_(e,e,e)),dm("pow4",Cv),dm("transformDirection",Nv),dm("mix",(e,t,n)=>Lv(t,n,e)),dm("clamp",Dv),dm("refract",Uv),dm("smoothstep",(e,t,n)=>Ov(t,n,e)),dm("faceForward",Fv),dm("difference",Mv),dm("saturate",Iv),dm("cbrt",e=>p_(av(e),Av(sv(e),1/3))),dm("transpose",gv),dm("determinant",_v),dm("inverse",vv),dm("rand",Bv);class kv extends Zf{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 e.flowBuildStage(this,"setup"),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,n=this.ifNode.isolate(),r=this.elseNode?this.elseNode.isolate():null,i=e.context.nodeBlock;e.getDataFromNode(n).parentNodeBlock=i,null!==r&&(e.getDataFromNode(r).parentNodeBlock=i);const s=e.context.uniformFlow,a=e.getNodeProperties(this);a.condNode=t,a.ifNode=s?n:n.context({nodeBlock:n}),a.elseNode=r?s?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?xg(n).build(e):"";r.nodeProperty=u;const c=i.build(e,"bool");if(e.context.uniformFlow&&null!==a){const r=s.build(e,n),i=a.build(e,n),o=e.getTernary(c,r,i);return e.format(o,n,t)}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&&(Qt("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&&(Qt("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 zv=jm(kv).setParameterLength(2,3);dm("select",zv);class Vv extends Zf{static get type(){return"ContextNode"}constructor(e=null,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}getNodeType(e){return this.node.getNodeType(e)}getFlowContextData(){const e=[];return this.traverse(t=>{!0===t.isContextNode&&e.push(t.value)}),Object.assign({},...e)}getMemberType(e,t){return this.node.getMemberType(e,t)}analyze(e){const t=e.addContext(this.value);this.node.build(e),e.setContext(t)}setup(e){const t=e.addContext(this.value);this.node.build(e),e.setContext(t)}generate(e,t){const n=e.addContext(this.value),r=this.node.build(e,t);return e.setContext(n),r}}const Gv=(e=null,t={})=>{let n=e;return null!==n&&!0===n.isNode||(t=n||t,n=null),new Vv(n,t)},Hv=(e,t)=>Gv(e,{nodeName:t});dm("context",Gv),dm("label",function(e,t){return Qt('TSL: "label()" has been deprecated. Use "setName()" instead.'),Hv(e,t)}),dm("uniformFlow",e=>Gv(e,{uniformFlow:!0})),dm("setName",Hv),dm("builtinShadowContext",(e,t,n)=>function(e,t,n=null){return Gv(n,{getShadow:({light:n,shadowColorNode:r})=>t===n?r.mul(e):r})}(t,n,e)),dm("builtinAOContext",(e,t)=>function(e,t=null){return Gv(t,{getAO:(t,{material:n})=>!0===n.transparent?t:null!==t?t.mul(e):e})}(t,e));class jv extends Zf{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,this.intent=!1}setIntent(e){return this.intent=e,this}isIntent(e){return!0!==e.getDataFromNode(this).forceDeclaration&&this.intent}getIntent(){return this.intent}getMemberType(e,t){return this.node.getMemberType(e,t)}getElementType(e){return this.node.getElementType(e)}getNodeType(e){return this.node.getNodeType(e)}getArrayCount(e){return this.node.getArrayCount(e)}isAssign(e){return e.getDataFromNode(this).assign}build(...e){const t=e[0];if(!1===this._hasStack(t)&&"setup"===t.buildStage&&(t.context.nodeLoop||t.context.nodeBlock)){let e=!1;if(this.node.isShaderCallNodeInternal&&null===this.node.shaderNode.getLayout()&&t.fnCall&&t.fnCall.shaderNode){if(t.getDataFromNode(this.node.shaderNode).hasLoop){t.getDataFromNode(this).forceDeclaration=!0,e=!0}}const n=t.getBaseStack();e?n.addToStackBefore(this):n.addToStack(this)}return this.isIntent(t)&&!0!==this.isAssign(t)?this.node.build(...e):super.build(...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=this.getNodeType(e);if("void"==l){!0!==this.isIntent(e)&&Jt('TSL: ".toVar()" can not be used with void type.');return t.build(e)}const u=e.getVectorType(l),c=t.build(e,u),h=e.getVarFromNode(this,n,u,void 0,o),d=e.getPropertyName(h);let p=d;if(o)if(s)p=a?`const ${d}`:`let ${d}`;else{const n=t.getArrayCount(e);p=`const ${e.getVar(h.type,d,n)}`}return e.addLineFlowCode(`${p} = ${c}`,this),d}_hasStack(e){return void 0!==e.getDataFromNode(this).stack}}const Wv=jm(jv);dm("toVar",(e,t=null)=>Wv(e,t).toStack()),dm("toConst",(e,t=null)=>Wv(e,t,!0).toStack()),dm("toVarIntent",e=>Wv(e).setIntent(!0).toStack());class $v extends Zf{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 Xv=(e,t,n=null)=>zm(new $v(zm(e),t,n));class qv extends Zf{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=Xv(this.node,"VERTEX")}return n.needsInterpolation||(n.needsInterpolation="fragment"===e.shaderStage),n}setup(e){this.setupVarying(e),e.flowNodeFromShaderStage(Bf,this.node)}analyze(e){this.setupVarying(e),e.flowNodeFromShaderStage(Bf,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,Bf);e.flowNodeFromShaderStage(Bf,n.node,i,s),n[t]=s}return e.getPropertyName(r)}}const Yv=jm(qv).setParameterLength(1,2);dm("toVarying",Yv),dm("toVertexStage",e=>Yv(e)),dm("varying",(...e)=>(Qt("TSL: .varying() has been renamed to .toVarying()."),Yv(...e))),dm("vertexStage",(...e)=>(Qt("TSL: .vertexStage() has been renamed to .toVertexStage()."),Yv(...e)));const Kv=Ym(([e])=>{const t=e.mul(.9478672986).add(.0521327014).pow(2.4),n=e.mul(.0773993808),r=e.lessThanEqual(.04045);return Lv(t,n,r)}).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),Zv=Ym(([e])=>{const t=e.pow(.41666).mul(1.055).sub(.055),n=e.mul(12.92),r=e.lessThanEqual(.0031308);return Lv(t,n,r)}).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),Qv="WorkingColorSpace";class Jv extends em{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===Qv?Mn.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!==Mn.enabled&&n!==r&&n&&r?(Mn.getTransfer(n)===Ct&&(i=pg(Kv(i.rgb),i.a)),Mn.getPrimaries(n)!==Mn.getPrimaries(r)&&(i=pg(vg(Mn._getMatrix(new yn,n,r)).mul(i.rgb),i.a)),Mn.getTransfer(r)===Ct&&(i=pg(Zv(i.rgb),i.a)),i):i}}const ey=(e,t)=>zm(new Jv(zm(e),t,Qv));dm("workingToColorSpace",(e,t)=>zm(new Jv(zm(e),Qv,t))),dm("colorSpaceToWorking",ey);let ty=class extends Qf{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 ny extends Zf{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=Gf}setGroup(e){return this.group=e,this}element(e){return new ty(this,zm(e))}setNodeType(e){const t=s_(null,e);null!==this.group&&t.setGroup(this.group),this.node=t}getNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let n=e[t[0]];for(let e=1;enew ry(e,t,n);class sy extends em{static get type(){return"ToneMappingNode"}constructor(e,t=ay,n=null){super("vec3"),this._toneMapping=e,this.exposureNode=t,this.colorNode=n}customCacheKey(){return Pf(this._toneMapping)}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return 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=pg(i(t.rgb,this.exposureNode),t.a):(Jt("ToneMappingNode: Unsupported Tone Mapping configuration.",n),r=t),r}}const ay=iy("toneMappingExposure","float");dm("toneMapping",(e,t,n)=>((e,t,n)=>zm(new sy(e,zm(t),zm(n))))(t,n,e));const oy=new WeakMap;function ly(e,t){let n=oy.get(e);return void 0===n&&(n=new ls(e,t),oy.set(e,n)),n}class uy extends am{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=kt,this.instanced=!1,this.attribute=null,this.global=!0,e&&!0===e.isBufferAttribute&&e.itemSize<=4&&(this.attribute=e,this.usage=e.usage,this.instanced=e.isInstancedBufferAttribute)}getHash(e){if(0===this.bufferStride&&0===this.bufferOffset){let t=e.globalCache.getData(this.value);return void 0===t&&(t={node:this},e.globalCache.setData(this.value,t)),t.node.uuid}return this.uuid}getNodeType(e){return null===this.bufferType&&(this.bufferType=e.getTypeFromAttribute(this.attribute)),this.bufferType}setup(e){if(null!==this.attribute)return;const t=this.getNodeType(e),n=e.getTypeLength(t),r=this.value,i=this.bufferStride||n,s=this.bufferOffset;let a;a=!0===r.isInterleavedBuffer?r:!0===r.isBufferAttribute?ly(r.array,i):ly(r,i);const o=new cs(a,n,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=Yv(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}}function cy(e,t=null,n=0,r=0,i=35044,s=!1){return"mat3"===t||null===t&&9===e.itemSize?vg(new uy(e,"vec3",9,0).setUsage(i).setInstanced(s),new uy(e,"vec3",9,3).setUsage(i).setInstanced(s),new uy(e,"vec3",9,6).setUsage(i).setInstanced(s)):"mat4"===t||null===t&&16===e.itemSize?yg(new uy(e,"vec4",16,0).setUsage(i).setInstanced(s),new uy(e,"vec4",16,4).setUsage(i).setInstanced(s),new uy(e,"vec4",16,8).setUsage(i).setInstanced(s),new uy(e,"vec4",16,12).setUsage(i).setInstanced(s)):new uy(e,t,n,r)}const hy=(e,t=null,n=0,r=0)=>cy(e,t,n,r),dy=(e,t=null,n=0,r=0)=>cy(e,t,n,r,kt,!0),py=(e,t=null,n=0,r=0)=>cy(e,t,n,r,zt,!0);dm("toAttribute",e=>hy(e.value));class fy extends Zf{static get type(){return"ComputeNode"}constructor(e,t){super("void"),this.isComputeNode=!0,this.computeNode=e,this.workgroupSize=t,this.count=null,this.version=1,this.name="",this.updateBeforeType=Gf,this.onInitFunction=null}setCount(e){return this.count=e,this}getCount(){return this.count}dispose(){this.dispatchEvent({type:"dispose"})}setName(e){return this.name=e,this}label(e){return Qt('TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}onInit(e){return this.onInitFunction=e,this}updateBefore({renderer:e}){e.compute(this)}setup(e){const t=this.computeNode.build(e);if(t){e.getNodeProperties(this).outputComputeNode=t.outputNode,t.outputNode=null}return t}generate(e,t){const{shaderStage: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)}}}const my=(e,t=[64])=>{(0===t.length||t.length>3)&&Jt("TSL: compute() workgroupSize must have 1, 2, or 3 elements");for(let e=0;emy(e,n).setCount(t)),dm("computeKernel",my);class gy extends Zf{static get type(){return"IsolateNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isIsolateNode=!0}getNodeType(e){const t=e.getCache(),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}setParent(e){return this.parent=e,this}getParent(){return this.parent}}const _y=e=>new gy(zm(e));dm("cache",function(e,t=!0){return Qt('TSL: "cache()" has been deprecated. Use "isolate()" instead.'),_y(e).setParent(t)}),dm("isolate",_y);class vy extends Zf{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)}}dm("bypass",jm(vy).setParameterLength(2));class yy extends Zf{static get type(){return"RemapNode"}constructor(e,t,n,r=tg(0),i=tg(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 by=jm(yy,null,null,{doClamp:!1}).setParameterLength(3,5),xy=jm(yy).setParameterLength(3,5);dm("remap",by),dm("remapClamp",xy);class Ty extends Zf{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 Sy=jm(Ty).setParameterLength(1,2);dm("discard",e=>(e?zv(e,Sy("discard")):Sy("discard")).toStack());class My extends em{static get type(){return"RenderOutputNode"}constructor(e,t,n){super("vec4"),this.colorNode=e,this._toneMapping=t,this.outputColorSpace=n,this.isRenderOutputNode=!0}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}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)||wt;return 0!==n&&(t=t.toneMapping(n)),r!==wt&&r!==Mn.workingColorSpace&&(t=t.workingToColorSpace(r)),t}}dm("renderOutput",(e,t=null,n=null)=>zm(new My(zm(e),t,n)));class wy extends em{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):Zt(s),n}}dm("debug",(e,t=null)=>zm(new wy(zm(e),t)).toStack());class Ey{constructor(){this._renderer=null,this.currentFrame=null}get nodeFrame(){return this._renderer._nodes.nodeFrame}setRenderer(e){return this._renderer=e,this}getRenderer(){return this._renderer}init(){}begin(){}finish(){}inspect(){}computeAsync(){}beginCompute(){}finishCompute(){}beginRender(){}finishRender(){}copyTextureToTexture(){}copyFramebufferToTexture(){}}class Ay extends Zf{static get type(){return"InspectorNode"}constructor(e,t="",n=null){super(),this.node=e,this.name=t,this.callback=n,this.updateType=zf,this.isInspectorNode=!0}getName(){return this.name||this.node.name}update(e){e.renderer.inspector.inspect(this)}getNodeType(e){return this.node.getNodeType(e)}setup(e){let t=this.node;return!0===e.context.inspector&&null!==this.callback&&(t=this.callback(t)),!0!==e.renderer.backend.isWebGPUBackend&&e.renderer.inspector.constructor!==Ey&&en('TSL: ".toInspector()" is only available with WebGPU.'),t}}dm("toInspector",function(e,t="",n=null){return(e=zm(e)).before(new Ay(e,t,n))});class Ry extends Zf{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 Yv(this).build(e,n)}return Qt(`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 Cy=(e,t=null)=>new Ry(e,t),Ny=(e=0)=>Cy("uv"+(e>0?e:""),"vec2");class Py extends Zf{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 Ly=jm(Py).setParameterLength(1,2);class Dy extends i_{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=zf}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 Iy=jm(Dy).setParameterLength(1),Uy=new In;class Oy extends i_{static get type(){return"TextureNode"}constructor(e=Uy,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.offsetNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=kf,this.referenceNode=null,this._value=e,this._matrixUniform=null,this._flipYUniform=null,this.setUpdateMatrix(null===t)}set value(e){this.referenceNode?this.referenceNode.value=e:this._value=e}get value(){return this.referenceNode?this.referenceNode.value:this._value}getUniformHash(){return this.value.uuid}getNodeType(){return!0===this.value.isDepthTexture?"float":this.value.type===we?"uvec4":this.value.type===Me?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return Ny(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return null===this._matrixUniform&&(this._matrixUniform=s_(this.value.matrix)),this._matrixUniform.mul(ug(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this}setupUV(e,t){return e.isFlipY()&&(null===this._flipYUniform&&(this._flipYUniform=s_(!1)),t=t.toVar(),t=this.sampler?this._flipYUniform.select(t.flipY(),t):this._flipYUniform.select(t.setY(ng(Ly(this,this.levelNode).y).sub(t.y).sub(1)),t)),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().");const r=Ym(()=>{let t=this.uvNode;return null!==t&&!0!==e.context.forceUVContext||!e.context.getUV||(t=e.context.getUV(this,e)),t||(t=this.getDefaultUV()),!0===this.updateMatrix&&(t=this.getTransformedUV(t)),t=this.setupUV(e,t),this.updateType=null!==this._matrixUniform||null!==this._flipYUniform?Gf:kf,t})();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,t.offsetNode=this.offsetNode}generateUV(e,t){return t.build(e,!0===this.sampler?"vec2":"ivec2")}generateOffset(e,t){return t.build(e,"ivec2")}generateSnippet(e,t,n,r,i,s,a,o,l){const u=this.value;let c;return c=i?e.generateTextureBias(u,t,n,i,s,l):o?e.generateTextureGrad(u,t,n,o,s,l):a?e.generateTextureCompare(u,t,n,a,s,l):!1===this.sampler?e.generateTextureLoad(u,t,n,r,s,l):r?e.generateTextureLevel(u,t,n,r,s,l):e.generateTexture(u,t,n,s,l),c}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,offsetNode:h}=r,d=this.generateUV(e,t),p=n?n.build(e,"float"):null,f=o?o.build(e,"float"):null,m=u?u.build(e,"int"):null,g=l?l.build(e,"float"):null,_=c?[c[0].build(e,"vec2"),c[1].build(e,"vec2")]:null,v=h?this.generateOffset(e,h):null,y=e.getVarFromNode(this);a=e.getPropertyName(y);const b=this.generateSnippet(e,i,d,p,f,m,g,_,v);e.addLineFlowCode(`${a} = ${b}`,this),s.snippet=b,s.propertyName=a}let o=a;const l=this.getNodeType(e);return e.needsToWorkingColorSpace(n)&&(o=ey(Sy(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 Qt("TextureNode: .uv() has been renamed. Use .sample() instead."),this.sample(e)}sample(e){const t=this.clone();return t.uvNode=zm(e),t.referenceNode=this.getBase(),zm(t)}load(e){return this.sample(e).setSampler(!1)}blur(e){const t=this.clone();t.biasNode=zm(e).mul(Iy(t)),t.referenceNode=this.getBase();const n=t.value;return!1===t.generateMipmaps&&(n&&!1===n.generateMipmaps||n.minFilter===fe||n.magFilter===fe)&&(Qt("TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture."),t.biasNode=null),zm(t)}level(e){const t=this.clone();return t.levelNode=zm(e),t.referenceNode=this.getBase(),zm(t)}size(e){return Ly(this,e)}bias(e){const t=this.clone();return t.biasNode=zm(e),t.referenceNode=this.getBase(),zm(t)}getBase(){return this.referenceNode?this.referenceNode.getBase():this}compare(e){const t=this.clone();return t.compareNode=zm(e),t.referenceNode=this.getBase(),zm(t)}grad(e,t){const n=this.clone();return n.gradNode=[zm(e),zm(t)],n.referenceNode=this.getBase(),zm(n)}depth(e){const t=this.clone();return t.depthNode=zm(e),t.referenceNode=this.getBase(),zm(t)}offset(e){const t=this.clone();return t.offsetNode=zm(e),t.referenceNode=this.getBase(),zm(t)}serialize(e){super.serialize(e),e.value=this.value.toJSON(e.meta).uuid,e.sampler=this.sampler,e.updateMatrix=this.updateMatrix,e.updateType=this.updateType}deserialize(e){super.deserialize(e),this.value=e.meta.textures[e.value],this.sampler=e.sampler,this.updateMatrix=e.updateMatrix,this.updateType=e.updateType}update(){const e=this.value,t=this._matrixUniform;null!==t&&(t.value=e.matrix),!0===e.matrixAutoUpdate&&e.updateMatrix();const n=this._flipYUniform;null!==n&&(n.value=e.image instanceof ImageBitmap&&!0===e.flipY||!0===e.isRenderTargetTexture||!0===e.isFramebufferTexture||!0===e.isDepthTexture)}clone(){const e=new this.constructor(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e}}const Fy=jm(Oy).setParameterLength(1,4).setName("texture"),By=(e=Uy,t=null,n=null,r=null)=>{let i;return e&&!0===e.isTextureNode?(i=zm(e.clone()),i.referenceNode=e.getBase(),null!==t&&(i.uvNode=zm(t)),null!==n&&(i.levelNode=zm(n)),null!==r&&(i.biasNode=zm(r))):i=Fy(e,t,n,r),i},ky=(...e)=>By(...e).setSampler(!1);class zy extends i_{static get type(){return"BufferNode"}constructor(e,t,n=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=n,this.updateRanges=[]}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}getElementType(e){return this.getNodeType(e)}getInputType(){return"buffer"}}const Vy=(e,t,n)=>new zy(e,t,n);class Gy extends Qf{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 Hy extends zy{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=null===t?Uf(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=Vf,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;nnew Hy(e,t);const Wy=jm(class extends Zf{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}}).setParameterLength(1);let $y,Xy;class qy extends Zf{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this._output=null,this.isViewportNode=!0}getNodeType(){return this.scope===qy.DPR?"float":this.scope===qy.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=kf;return this.scope!==qy.SIZE&&this.scope!==qy.VIEWPORT&&this.scope!==qy.DPR||(e=Vf),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===qy.VIEWPORT?null!==t?Xy.copy(t.viewport):(e.getViewport(Xy),Xy.multiplyScalar(e.getPixelRatio())):this.scope===qy.DPR?this._output.value=e.getPixelRatio():null!==t?($y.width=t.width,$y.height=t.height):e.getDrawingBufferSize($y)}setup(){const e=this.scope;let t=null;return t=e===qy.SIZE?s_($y||($y=new fn)):e===qy.VIEWPORT?s_(Xy||(Xy=new Un)):e===qy.DPR?s_(1):sg(Qy.div(Zy)),this._output=t,t}generate(e){if(this.scope===qy.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const n=e.getNodeProperties(Zy).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${n}.y - ${t}.y )`}return t}return super.generate(e)}}qy.COORDINATE="coordinate",qy.VIEWPORT="viewport",qy.SIZE="size",qy.UV="uv",qy.DPR="dpr";const Yy=Wm(qy,qy.DPR),Ky=Wm(qy,qy.UV),Zy=Wm(qy,qy.SIZE),Qy=Wm(qy,qy.COORDINATE),Jy=Wm(qy,qy.VIEWPORT),eb=Jy.zw;Jy.xy;const tb=s_(0,"uint").setName("u_cameraIndex").setGroup(e_("cameraIndex")).toVarying("v_cameraIndex"),nb=s_("float").setName("cameraNear").setGroup(n_).onRenderUpdate(({camera:e})=>e.near),rb=s_("float").setName("cameraFar").setGroup(n_).onRenderUpdate(({camera:e})=>e.far),ib=Ym(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const n=[];for(const t of e.cameras)n.push(t.projectionMatrix);t=jy(n).setGroup(n_).setName("cameraProjectionMatrices").element(e.isMultiViewCamera?Wy("gl_ViewID_OVR"):tb).toConst("cameraProjectionMatrix")}else t=s_("mat4").setName("cameraProjectionMatrix").setGroup(n_).onRenderUpdate(({camera:e})=>e.projectionMatrix);return t}).once()(),sb=Ym(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const n=[];for(const t of e.cameras)n.push(t.matrixWorldInverse);t=jy(n).setGroup(n_).setName("cameraViewMatrices").element(e.isMultiViewCamera?Wy("gl_ViewID_OVR"):tb).toConst("cameraViewMatrix")}else t=s_("mat4").setName("cameraViewMatrix").setGroup(n_).onRenderUpdate(({camera:e})=>e.matrixWorldInverse);return t}).once()(),ab=Ym(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const n=[];for(let t=0,r=e.cameras.length;t{const n=e.cameras,r=t.array;for(let e=0,t=n.length;et.value.setFromMatrixPosition(e.matrixWorld));return t}).once()(),ob=new ir;class lb extends Zf{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=Gf,this.uniformNode=new i_(null)}getNodeType(){const e=this.scope;return e===lb.WORLD_MATRIX?"mat4":e===lb.POSITION||e===lb.VIEW_POSITION||e===lb.DIRECTION||e===lb.SCALE?"vec3":e===lb.RADIUS?"float":void 0}update(e){const t=this.object3d,n=this.uniformNode,r=this.scope;if(r===lb.WORLD_MATRIX)n.value=t.matrixWorld;else if(r===lb.POSITION)n.value=n.value||new gn,n.value.setFromMatrixPosition(t.matrixWorld);else if(r===lb.SCALE)n.value=n.value||new gn,n.value.setFromMatrixScale(t.matrixWorld);else if(r===lb.DIRECTION)n.value=n.value||new gn,t.getWorldDirection(n.value);else if(r===lb.VIEW_POSITION){const r=e.camera;n.value=n.value||new gn,n.value.setFromMatrixPosition(t.matrixWorld),n.value.applyMatrix4(r.matrixWorldInverse)}else if(r===lb.RADIUS){const r=e.object.geometry;null===r.boundingSphere&&r.computeBoundingSphere(),ob.copy(r.boundingSphere).applyMatrix4(t.matrixWorld),n.value=ob.radius}}generate(e){const t=this.scope;return t===lb.WORLD_MATRIX?this.uniformNode.nodeType="mat4":t===lb.POSITION||t===lb.VIEW_POSITION||t===lb.DIRECTION||t===lb.SCALE?this.uniformNode.nodeType="vec3":t===lb.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}}lb.WORLD_MATRIX="worldMatrix",lb.POSITION="position",lb.SCALE="scale",lb.VIEW_POSITION="viewPosition",lb.DIRECTION="direction",lb.RADIUS="radius";const ub=jm(lb,lb.POSITION).setParameterLength(1);class cb extends lb{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const hb=Wm(cb,cb.WORLD_MATRIX),db=s_(new yn).onObjectUpdate(({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld)),pb=Ym(e=>e.context.modelViewMatrix||fb).once()().toVar("modelViewMatrix"),fb=sb.mul(hb),mb=Ym(e=>(e.context.isHighPrecisionModelViewMatrix=!0,s_("mat4").onObjectUpdate(({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld)))).once()().toVar("highpModelViewMatrix"),gb=Ym(e=>{const t=e.context.isHighPrecisionModelViewMatrix;return s_("mat3").onObjectUpdate(({object:e,camera:n})=>(!0!==t&&e.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix)))}).once()().toVar("highpModelNormalViewMatrix"),_b=Cy("position","vec3"),vb=_b.toVarying("positionLocal"),yb=_b.toVarying("positionPrevious"),bb=Ym(e=>hb.mul(vb).xyz.toVarying(e.getSubBuildProperty("v_positionWorld")),"vec3").once(["POSITION"])(),xb=Ym(()=>vb.transformDirection(hb).toVarying("v_positionWorldDirection").normalize().toVar("positionWorldDirection"),"vec3").once(["POSITION"])(),Tb=Ym(e=>e.context.setupPositionView().toVarying("v_positionView"),"vec3").once(["POSITION"])(),Sb=Ym(e=>{let t;return t=e.camera.isOrthographicCamera?ug(0,0,1):Tb.negate().toVarying("v_positionViewDirection").normalize(),t.toVar("positionViewDirection")},"vec3").once(["POSITION"])();class Mb extends Zf{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){if("fragment"!==e.shaderStage)return"true";const{material:t}=e;return 1===t.side?"false":e.getFrontFacing()}}const wb=tg(Wm(Mb)).mul(2).sub(1),Eb=Ym(([e],{material:t})=>{const n=t.side;return 1===n?e=e.mul(-1):2===n&&(e=e.mul(wb)),e}),Ab=Cy("normal","vec3"),Rb=Ym(e=>!1===e.geometry.hasAttribute("normal")?(Qt('TSL: Vertex attribute "normal" not found on geometry.'),ug(0,1,0)):Ab,"vec3").once()().toVar("normalLocal"),Cb=Tb.dFdx().cross(Tb.dFdy()).normalize().toVar("normalFlat"),Nb=Ym(e=>{let t;return t=!0===e.material.flatShading?Cb:Ob(Rb).toVarying("v_normalViewGeometry").normalize(),t},"vec3").once()().toVar("normalViewGeometry"),Pb=Ym(e=>{let t=Nb.transformDirection(sb);return!0!==e.material.flatShading&&(t=t.toVarying("v_normalWorldGeometry")),t.normalize().toVar("normalWorldGeometry")},"vec3").once()(),Lb=Ym(({subBuildFn:e,material:t,context:n})=>{let r;return"NORMAL"===e||"VERTEX"===e?(r=Nb,!0!==t.flatShading&&(r=Eb(r))):r=n.setupNormal().context({getUV:null}),r},"vec3").once(["NORMAL","VERTEX"])().toVar("normalView"),Db=Lb.transformDirection(sb).toVar("normalWorld"),Ib=Ym(({subBuildFn:e,context:t})=>{let n;return n="NORMAL"===e||"VERTEX"===e?Lb:t.setupClearcoatNormal().context({getUV:null}),n},"vec3").once(["NORMAL","VERTEX"])().toVar("clearcoatNormalView"),Ub=Ym(([e,t=hb])=>{const n=vg(t),r=e.div(ug(n[0].dot(n[0]),n[1].dot(n[1]),n[2].dot(n[2])));return n.mul(r).xyz}),Ob=Ym(([e],t)=>{const n=t.context.modelNormalViewMatrix;if(n)return n.transformDirection(e);const r=db.mul(e);return sb.transformDirection(r)});Ym(()=>(Qt('TSL: "transformedNormalView" is deprecated. Use "normalView" instead.'),Lb)).once(["NORMAL","VERTEX"])(),Ym(()=>(Qt('TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.'),Db)).once(["NORMAL","VERTEX"])(),Ym(()=>(Qt('TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.'),Ib)).once(["NORMAL","VERTEX"])();const Fb=new Sr,Bb=new pr,kb=s_(0).onReference(({material:e})=>e).onObjectUpdate(({material:e})=>e.refractionRatio),zb=s_(1).onReference(({material:e})=>e).onObjectUpdate(function({material:e,scene:t}){return e.envMap?e.envMapIntensity:t.environmentIntensity}),Vb=s_(new pr).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?(Fb.copy(n),Bb.makeRotationFromEuler(Fb)):Bb.identity(),Bb}),Gb=Sb.negate().reflect(Lb),Hb=Sb.negate().refract(Lb,kb),jb=Gb.transformDirection(sb).toVar("reflectVector"),Wb=Hb.transformDirection(sb).toVar("reflectVector"),$b=new ns;class Xb extends Oy{static get type(){return"CubeTextureNode"}constructor(e,t=null,n=null,r=null){super(e,t,n,r),this.isCubeTextureNode=!0}getInputType(){return!0===this.value.isDepthTexture?"cubeDepthTexture":"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===ae?jb:e.mapping===oe?Wb:(Jt('CubeTextureNode: Mapping "%s" not supported.',e.mapping),ug(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const n=this.value;return!0===n.isDepthTexture?e.renderer.coordinateSystem===Ht?ug(t.x,t.y.negate(),t.z):t:(e.renderer.coordinateSystem!==Ht&&n.isRenderTargetTexture||(t=ug(t.x.negate(),t.yz)),Vb.mul(t))}generateUV(e,t){return t.build(e,!0===this.sampler?"vec3":"ivec3")}}const qb=jm(Xb).setParameterLength(1,4).setName("cubeTexture"),Yb=(e=$b,t=null,n=null,r=null)=>{let i;return e&&!0===e.isCubeTextureNode?(i=zm(e.clone()),i.referenceNode=e,null!==t&&(i.uvNode=zm(t)),null!==n&&(i.levelNode=zm(n)),null!==r&&(i.biasNode=zm(r))):i=qb(e,t,n,r),i};class Kb extends Qf{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 Zb extends Zf{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=Gf}element(e){return new Kb(this,zm(e))}setGroup(e){return this.group=e,this}setName(e){return this.name=e,this}label(e){return Qt('TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}setNodeType(e){let t=null;t=null!==this.count?Vy(null,e,this.count):Array.isArray(this.getValueFromReference())?jy(null,e):"texture"===e?By(null):"cubeTexture"===e?Yb(null):s_(null,e),null!==this.group&&t.setGroup(this.group),null!==this.name&&t.setName(this.name),this.node=t}getNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let n=e[t[0]];for(let e=1;enew Zb(e,t,n),Jb=(e,t,n,r)=>new Zb(e,t,r,n);class ex extends Zb{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 tx=(e,t,n=null)=>new ex(e,t,n),nx=Ny(),rx=Tb.dFdx(),ix=Tb.dFdy(),sx=nx.dFdx(),ax=nx.dFdy(),ox=Lb,lx=ix.cross(ox),ux=ox.cross(rx),cx=lx.mul(sx.x).add(ux.mul(ax.x)),hx=lx.mul(sx.y).add(ux.mul(ax.y)),dx=cx.dot(cx).max(hx.dot(hx)),px=dx.equal(0).select(0,dx.inverseSqrt()),fx=cx.mul(px).toVar("tangentViewFrame"),mx=hx.mul(px).toVar("bitangentViewFrame"),gx=Cy("tangent","vec4"),_x=gx.xyz.toVar("tangentLocal"),vx=Ym(({subBuildFn:e,geometry:t,material:n})=>{let r;return r="VERTEX"===e||t.hasAttribute("tangent")?pb.mul(pg(_x,0)).xyz.toVarying("v_tangentView").normalize():fx,!0!==n.flatShading&&(r=Eb(r)),r},"vec3").once(["NORMAL","VERTEX"])().toVar("tangentView"),yx=Ym(([e,t],{subBuildFn:n,material:r})=>{let i=e.mul(gx.w).xyz;return"NORMAL"===n&&!0!==r.flatShading&&(i=i.toVarying(t)),i}).once(["NORMAL"]),bx=vg(vx,Ym(({subBuildFn:e,geometry:t,material:n})=>{let r;return r="VERTEX"===e||t.hasAttribute("tangent")?yx(Lb.cross(vx),"v_bitangentView").normalize():mx,!0!==n.flatShading&&(r=Eb(r)),r},"vec3").once(["NORMAL","VERTEX"])().toVar("bitangentView"),Lb).toVar("TBNViewMatrix"),xx=Ym(()=>{let e=Bg.cross(Sb);return e=e.cross(Bg).normalize(),e=Lv(e,Lb,Og.mul(Eg.oneMinus()).oneMinus().pow2().pow2()).normalize(),e}).once()(),Tx=e=>ug(e,X_(Iv(tg(1).sub(wv(e,e)))));class Sx extends em{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=0,this.unpackNormalMode=""}setup({material:e}){const{normalMapType:t,scaleNode:n,unpackNormalMode:r}=this;let i=this.node.mul(2).sub(1);if(0===t?"rg"===r?i=Tx(i.xy):"ga"===r?i=Tx(i.yw):""!==r&&console.error(`THREE.NodeMaterial: Unexpected unpack normal mode: ${r}`):""!==r&&console.error(`THREE.NodeMaterial: Normal map type '${t}' is not compatible with unpack normal mode '${r}'`),null!==n){let t=n;!0===e.flatShading&&(t=Eb(t)),i=ug(i.xy.mul(t),i.z)}let s=null;return 1===t?s=Ob(i):0===t?s=bx.mul(i).normalize():(Jt(`NodeMaterial: Unsupported normal map type: ${t}`),s=Lb),s}}const Mx=jm(Sx).setParameterLength(1,2),wx=Ym(({textureNode:e,bumpScale:t})=>{const n=t=>e.isolate().context({getUV:e=>t(e.uvNode||Ny()),forceUVContext:!0}),r=tg(n(e=>e));return sg(tg(n(e=>e.add(e.dFdx()))).sub(r),tg(n(e=>e.add(e.dFdy()))).sub(r)).mul(t)}),Ex=Ym(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(wb),u=l.sign().mul(r.x.mul(a).add(r.y.mul(o)));return l.abs().mul(n).sub(u).normalize()});class Ax extends em{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=wx({textureNode:this.textureNode,bumpScale:e});return Ex({surf_pos:Tb,surf_norm:Lb,dHdxy:t})}}const Rx=jm(Ax).setParameterLength(1,2),Cx=new Map;class Nx extends Zf{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let n=Cx.get(e);return void 0===n&&(n=tx(e,t),Cx.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===Nx.COLOR){const e=void 0!==t.color?this.getColor(n):ug();r=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(n===Nx.OPACITY){const e=this.getFloat(n);r=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(n===Nx.SPECULAR_STRENGTH)r=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture("specular").r:tg(1);else if(n===Nx.SPECULAR_INTENSITY){const e=this.getFloat(n);r=t.specularIntensityMap&&!0===t.specularIntensityMap.isTexture?e.mul(this.getTexture(n).a):e}else if(n===Nx.SPECULAR_COLOR){const e=this.getColor(n);r=t.specularColorMap&&!0===t.specularColorMap.isTexture?e.mul(this.getTexture(n).rgb):e}else if(n===Nx.ROUGHNESS){const e=this.getFloat(n);r=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(n).g):e}else if(n===Nx.METALNESS){const e=this.getFloat(n);r=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(n).b):e}else if(n===Nx.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===Nx.NORMAL)t.normalMap?(r=Mx(this.getTexture("normal"),this.getCache("normalScale","vec2")),r.normalMapType=t.normalMapType,t.normalMap.format!=ze&&t.normalMap.format!=St&&t.normalMap.format!=nt||(r.unpackNormalMode="rg")):r=t.bumpMap?Rx(this.getTexture("bump").r,this.getFloat("bumpScale")):Lb;else if(n===Nx.CLEARCOAT){const e=this.getFloat(n);r=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(n).r):e}else if(n===Nx.CLEARCOAT_ROUGHNESS){const e=this.getFloat(n);r=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(n).r):e}else if(n===Nx.CLEARCOAT_NORMAL)r=t.clearcoatNormalMap?Mx(this.getTexture(n),this.getCache(n+"Scale","vec2")):Lb;else if(n===Nx.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===Nx.SHEEN_ROUGHNESS){const e=this.getFloat(n);r=t.sheenRoughnessMap&&!0===t.sheenRoughnessMap.isTexture?e.mul(this.getTexture(n).a):e,r=r.clamp(1e-4,1)}else if(n===Nx.ANISOTROPY)if(t.anisotropyMap&&!0===t.anisotropyMap.isTexture){const e=this.getTexture(n);r=_g(pT.x,pT.y,pT.y.negate(),pT.x).mul(e.rg.mul(2).sub(sg(1)).normalize().mul(e.b))}else r=pT;else if(n===Nx.IRIDESCENCE_THICKNESS){const e=Qb("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const i=Qb("0","float",t.iridescenceThicknessRange);r=e.sub(i).mul(this.getTexture(n).g).add(i)}else r=e}else if(n===Nx.TRANSMISSION){const e=this.getFloat(n);r=t.transmissionMap?e.mul(this.getTexture(n).r):e}else if(n===Nx.THICKNESS){const e=this.getFloat(n);r=t.thicknessMap?e.mul(this.getTexture(n).g):e}else if(n===Nx.IOR)r=this.getFloat(n);else if(n===Nx.LIGHT_MAP)r=this.getTexture(n).rgb.mul(this.getFloat("lightMapIntensity"));else if(n===Nx.AO)r=this.getTexture(n).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1);else if(n===Nx.LINE_DASH_OFFSET)r=t.dashOffset?this.getFloat(n):tg(0);else{const t=this.getNodeType(e);r=this.getCache(n,t)}return r}}Nx.ALPHA_TEST="alphaTest",Nx.COLOR="color",Nx.OPACITY="opacity",Nx.SHININESS="shininess",Nx.SPECULAR="specular",Nx.SPECULAR_STRENGTH="specularStrength",Nx.SPECULAR_INTENSITY="specularIntensity",Nx.SPECULAR_COLOR="specularColor",Nx.REFLECTIVITY="reflectivity",Nx.ROUGHNESS="roughness",Nx.METALNESS="metalness",Nx.NORMAL="normal",Nx.CLEARCOAT="clearcoat",Nx.CLEARCOAT_ROUGHNESS="clearcoatRoughness",Nx.CLEARCOAT_NORMAL="clearcoatNormal",Nx.EMISSIVE="emissive",Nx.ROTATION="rotation",Nx.SHEEN="sheen",Nx.SHEEN_ROUGHNESS="sheenRoughness",Nx.ANISOTROPY="anisotropy",Nx.IRIDESCENCE="iridescence",Nx.IRIDESCENCE_IOR="iridescenceIOR",Nx.IRIDESCENCE_THICKNESS="iridescenceThickness",Nx.IOR="ior",Nx.TRANSMISSION="transmission",Nx.THICKNESS="thickness",Nx.ATTENUATION_DISTANCE="attenuationDistance",Nx.ATTENUATION_COLOR="attenuationColor",Nx.LINE_SCALE="scale",Nx.LINE_DASH_SIZE="dashSize",Nx.LINE_GAP_SIZE="gapSize",Nx.LINE_WIDTH="linewidth",Nx.LINE_DASH_OFFSET="dashOffset",Nx.POINT_SIZE="size",Nx.DISPERSION="dispersion",Nx.LIGHT_MAP="light",Nx.AO="ao";const Px=Wm(Nx,Nx.ALPHA_TEST),Lx=Wm(Nx,Nx.COLOR),Dx=Wm(Nx,Nx.SHININESS),Ix=Wm(Nx,Nx.EMISSIVE),Ux=Wm(Nx,Nx.OPACITY),Ox=Wm(Nx,Nx.SPECULAR),Fx=Wm(Nx,Nx.SPECULAR_INTENSITY),Bx=Wm(Nx,Nx.SPECULAR_COLOR),kx=Wm(Nx,Nx.SPECULAR_STRENGTH),zx=Wm(Nx,Nx.REFLECTIVITY),Vx=Wm(Nx,Nx.ROUGHNESS),Gx=Wm(Nx,Nx.METALNESS),Hx=Wm(Nx,Nx.NORMAL),jx=Wm(Nx,Nx.CLEARCOAT),Wx=Wm(Nx,Nx.CLEARCOAT_ROUGHNESS),$x=Wm(Nx,Nx.CLEARCOAT_NORMAL),Xx=Wm(Nx,Nx.ROTATION),qx=Wm(Nx,Nx.SHEEN),Yx=Wm(Nx,Nx.SHEEN_ROUGHNESS),Kx=Wm(Nx,Nx.ANISOTROPY),Zx=Wm(Nx,Nx.IRIDESCENCE),Qx=Wm(Nx,Nx.IRIDESCENCE_IOR),Jx=Wm(Nx,Nx.IRIDESCENCE_THICKNESS),eT=Wm(Nx,Nx.TRANSMISSION),tT=Wm(Nx,Nx.THICKNESS),nT=Wm(Nx,Nx.IOR),rT=Wm(Nx,Nx.ATTENUATION_DISTANCE),iT=Wm(Nx,Nx.ATTENUATION_COLOR),sT=Wm(Nx,Nx.LINE_SCALE),aT=Wm(Nx,Nx.LINE_DASH_SIZE),oT=Wm(Nx,Nx.LINE_GAP_SIZE);Nx.LINE_WIDTH;const lT=Wm(Nx,Nx.LINE_DASH_OFFSET),uT=Wm(Nx,Nx.POINT_SIZE),cT=Wm(Nx,Nx.DISPERSION),hT=Wm(Nx,Nx.LIGHT_MAP),dT=Wm(Nx,Nx.AO),pT=s_(new fn).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))}),fT=Ym(e=>e.context.setupModelViewProjection(),"vec4").once()().toVarying("v_modelViewProjection");class mT extends Qf{static get type(){return"StorageArrayElementNode"}constructor(e,t){super(e,t),this.isStorageArrayElementNode=!0}set storageBufferNode(e){this.node=e}get storageBufferNode(){return this.node}getMemberType(e,t){const n=this.storageBufferNode.structTypeNode;return n?n.getMemberType(e,t):"void"}setup(e){return!1===e.isAvailable("storageBuffer")&&!0===this.node.isPBO&&e.setupPBO(this.node),super.setup(e)}generate(e,t){let n;const r=e.context.assign;if(n=!1===e.isAvailable("storageBuffer")?!0!==this.node.isPBO||!0===r||!this.node.value.isInstancedBufferAttribute&&"compute"===e.shaderStage?this.node.build(e):e.generatePBO(this):super.generate(e),!0!==r){const r=this.getNodeType(e);n=e.format(n,r,t)}return n}}const gT=jm(mT).setParameterLength(2);class _T extends zy{static get type(){return"StorageBufferNode"}constructor(e,t=null,n=0){let r,i=null;t&&t.isStruct?(r="struct",i=t.layout,(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(n=e.count)):null===t&&(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)?(r=If(e.itemSize),n=e.count):r=t,super(e,r,n),this.isStorageBufferNode=!0,this.structTypeNode=i,this.access=Wf,this.isAtomic=!1,this.isPBO=!1,this._attribute=null,this._varying=null,this.global=!0,!0!==e.isStorageBufferAttribute&&!0!==e.isStorageInstancedBufferAttribute&&(e.isInstancedBufferAttribute?e.isStorageInstancedBufferAttribute=!0:e.isStorageBufferAttribute=!0)}getHash(e){if(0===this.bufferCount){let t=e.globalCache.getData(this.value);return void 0===t&&(t={node:this},e.globalCache.setData(this.value,t)),t.node.uuid}return this.uuid}getInputType(){return this.value.isIndirectStorageBufferAttribute?"indirectStorageBuffer":"storageBuffer"}element(e){return gT(this,e)}setPBO(e){return this.isPBO=e,this}getPBO(){return this.isPBO}setAccess(e){return this.access=e,this}toReadOnly(){return this.setAccess(Hf)}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getAttributeData(){return null===this._attribute&&(this._attribute=hy(this.value),this._varying=Yv(this._attribute)),{attribute:this._attribute,varying:this._varying}}getNodeType(e){if(null!==this.structTypeNode)return this.structTypeNode.getNodeType(e);if(e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.getNodeType(e);const{attribute:t}=this.getAttributeData();return t.getNodeType(e)}getMemberType(e,t){return null!==this.structTypeNode?this.structTypeNode.getMemberType(e,t):"void"}generate(e){if(null!==this.structTypeNode&&this.structTypeNode.build(e),e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.generate(e);const{attribute:t,varying:n}=this.getAttributeData(),r=n.build(e);return e.registerTransform(r,t),r}}const vT=(e,t=null,n=0)=>new _T(e,t,n);class yT extends Zf{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===yT.VERTEX)r=e.getVertexIndex();else if(n===yT.INSTANCE)r=e.getInstanceIndex();else if(n===yT.DRAW)r=e.getDrawIndex();else if(n===yT.INVOCATION_LOCAL)r=e.getInvocationLocalIndex();else if(n===yT.INVOCATION_SUBGROUP)r=e.getInvocationSubgroupIndex();else{if(n!==yT.SUBGROUP)throw new Error("THREE.IndexNode: Unknown scope: "+n);r=e.getSubgroupIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)i=r;else{i=Yv(this).build(e,t)}return i}}yT.VERTEX="vertex",yT.INSTANCE="instance",yT.SUBGROUP="subgroup",yT.INVOCATION_LOCAL="invocationLocal",yT.INVOCATION_SUBGROUP="invocationSubgroup",yT.DRAW="draw";const bT=Wm(yT,yT.VERTEX),xT=Wm(yT,yT.INSTANCE);yT.SUBGROUP,yT.INVOCATION_SUBGROUP,yT.INVOCATION_LOCAL;const TT=Wm(yT,yT.DRAW);class ST extends Zf{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=zf,this.buffer=null,this.bufferColor=null}get isStorageMatrix(){const{instanceMatrix:e}=this;return e&&!0===e.isStorageInstancedBufferAttribute}get isStorageColor(){const{instanceColor:e}=this;return e&&!0===e.isStorageInstancedBufferAttribute}setup(e){const{instanceMatrix:t,instanceColor:n,isStorageMatrix:r,isStorageColor:i}=this,{count:s}=t;let{instanceMatrixNode:a,instanceColorNode:o}=this;if(null===a){if(r)a=vT(t,"mat4",Math.max(s,1)).element(xT);else if(s<=1e3)a=Vy(t.array,"mat4",Math.max(s,1)).element(xT);else{const e=new za(t.array,16,1);this.buffer=e;const n=t.usage===zt?py:dy,r=[n(e,"vec4",16,0),n(e,"vec4",16,4),n(e,"vec4",16,8),n(e,"vec4",16,12)];a=yg(...r)}this.instanceMatrixNode=a}if(n&&null===o){if(i)o=vT(n,"vec3",Math.max(n.count,1)).element(xT);else{const e=new ps(n.array,3),t=n.usage===zt?py:dy;this.bufferColor=e,o=ug(t(e,"vec3",3,0))}this.instanceColorNode=o}const l=a.mul(vb).xyz;if(vb.assign(l),e.hasGeometryAttribute("normal")){const e=Ub(Rb,a);Rb.assign(e)}null!==this.instanceColorNode&&Tg("vec3","vInstanceColor").assign(this.instanceColorNode)}update(){null!==this.buffer&&!0!==this.isStorageMatrix&&(this.buffer.clearUpdateRanges(),this.buffer.updateRanges.push(...this.instanceMatrix.updateRanges),this.instanceMatrix.usage!==zt&&this.instanceMatrix.version!==this.buffer.version&&(this.buffer.version=this.instanceMatrix.version)),this.instanceColor&&null!==this.bufferColor&&!0!==this.isStorageColor&&(this.bufferColor.clearUpdateRanges(),this.bufferColor.updateRanges.push(...this.instanceColor.updateRanges),this.instanceColor.usage!==zt&&this.instanceColor.version!==this.bufferColor.version&&(this.bufferColor.version=this.instanceColor.version))}}class MT extends ST{static get type(){return"InstancedMeshNode"}constructor(e){const{count:t,instanceMatrix:n,instanceColor:r}=e;super(t,n,r),this.instancedMesh=e}}const wT=jm(MT).setParameterLength(1);class ET extends Zf{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=xT:this.batchingIdNode=TT);const t=Ym(([e])=>{const t=ng(Ly(ky(this.batchMesh._indirectTexture),0).x).toConst(),n=ng(e).mod(t).toConst(),r=ng(e).div(t).toConst();return ky(this.batchMesh._indirectTexture,ag(n,r)).x}).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]}),n=t(ng(this.batchingIdNode)),r=this.batchMesh._matricesTexture,i=ng(Ly(ky(r),0).x).toConst(),s=tg(n).mul(4).toInt().toConst(),a=s.mod(i).toConst(),o=s.div(i).toConst(),l=yg(ky(r,ag(a,o)),ky(r,ag(a.add(1),o)),ky(r,ag(a.add(2),o)),ky(r,ag(a.add(3),o))),u=this.batchMesh._colorsTexture;if(null!==u){const e=Ym(([e])=>{const t=ng(Ly(ky(u),0).x).toConst(),n=e,r=n.mod(t).toConst(),i=n.div(t).toConst();return ky(u,ag(r,i)).rgb}).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]}),t=e(n);Tg("vec3","vBatchColor").assign(t)}const c=vg(l);vb.assign(l.mul(vb));const h=Rb.div(ug(c[0].dot(c[0]),c[1].dot(c[1]),c[2].dot(c[2]))),d=c.mul(h).xyz;Rb.assign(d),e.hasGeometryAttribute("tangent")&&_x.mulAssign(c)}}const AT=jm(ET).setParameterLength(1),RT=new WeakMap;class CT extends Zf{static get type(){return"SkinningNode"}constructor(e){super("void"),this.skinnedMesh=e,this.updateType=Gf,this.skinIndexNode=Cy("skinIndex","uvec4"),this.skinWeightNode=Cy("skinWeight","vec4"),this.bindMatrixNode=Qb("bindMatrix","mat4"),this.bindMatrixInverseNode=Qb("bindMatrixInverse","mat4"),this.boneMatricesNode=Jb("skeleton.boneMatrices","mat4",e.skeleton.bones.length),this.positionNode=vb,this.toPositionNode=vb,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=h_(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=Rb){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=h_(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=Jb("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,yb)}needsPreviousBoneMatrices(e){const t=e.renderer.getMRT();return t&&t.has("velocity")||!0===Ff(e.object).useVelocity}setup(e){this.needsPreviousBoneMatrices(e)&&yb.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(this.toPositionNode&&this.toPositionNode.assign(t),e.hasGeometryAttribute("normal")){const t=this.getSkinnedNormal();Rb.assign(t),e.hasGeometryAttribute("tangent")&&_x.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;RT.get(t)!==e.frameId&&(RT.set(t,e.frameId),null!==this.previousBoneMatricesNode&&(null===t.previousBoneMatrices&&(t.previousBoneMatrices=new Float32Array(t.boneMatrices)),t.previousBoneMatrices.set(t.boneMatrices)),t.update())}}class NT extends Zf{static get type(){return"LoopNode"}constructor(e=[]){super("void"),this.params=e}getVarName(e){return String.fromCharCode("i".charCodeAt(0)+e)}getProperties(e){const t=e.getNodeProperties(this);if(void 0!==t.stackNode)return t;const n={};for(let e=0,t=this.params.length-1;eNumber(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):(Jt("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");t.returnsNode.build(e,"void"),e.removeFlowTab().addFlowCode("\n"+e.tab+i);for(let t=0,n=this.params.length-1;tnew NT(Hm(e,"int")).toStack(),LT=new WeakMap,DT=new Un,IT=Ym(({bufferMap:e,influence:t,stride:n,width:r,depth:i,offset:s})=>{const a=ng(bT).mul(n).add(s),o=a.div(r),l=a.sub(o.mul(r));return ky(e,ag(l,o)).depth(i).xyz.mul(t)});class UT extends Zf{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=s_(1),this.updateType=Gf}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=LT.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 Bn(f,h,d,s);m.type=Ee,m.needsUpdate=!0;const g=4*c;for(let v=0;v{const t=tg(0).toVar();this.mesh.count>1&&null!==this.mesh.morphTexture&&void 0!==this.mesh.morphTexture?t.assign(ky(this.mesh.morphTexture,ag(ng(e).add(1),ng(xT))).r):t.assign(Qb("morphTargetInfluences","float").element(e).toVar()),Qm(t.notEqual(0),()=>{!0===n&&vb.addAssign(IT({bufferMap:a,influence:t,stride:o,width:u,depth:e,offset:ng(0)})),!0===r&&Rb.addAssign(IT({bufferMap:a,influence:t,stride:o,width:u,depth:e,offset:ng(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 OT=jm(UT).setParameterLength(1);class FT extends Zf{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class BT extends FT{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class kT extends Vv{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:ug().toVar("directDiffuse"),directSpecular:ug().toVar("directSpecular"),indirectDiffuse:ug().toVar("indirectDiffuse"),indirectSpecular:ug().toVar("indirectSpecular")};return{radiance:ug().toVar("radiance"),irradiance:ug().toVar("irradiance"),iblIrradiance:ug().toVar("iblIrradiance"),ambientOcclusion:tg(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 zT=jm(kT);class VT extends FT{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}const GT=new fn;class HT extends Oy{static get type(){return"ViewportTextureNode"}constructor(e=Ky,t=null,n=null){let r=null;null===n?(r=new Us,r.minFilter=ye,n=r):r=n,super(n,e,t),this.generateMipmaps=!1,this.defaultFramebuffer=r,this.isOutputTextureNode=!0,this.updateBeforeType=zf,this._cacheTextures=new WeakMap}getTextureForReference(e=null){let t,n;if(this.referenceNode?(t=this.referenceNode.defaultFramebuffer,n=this.referenceNode._cacheTextures):(t=this.defaultFramebuffer,n=this._cacheTextures),null===e)return t;if(!1===n.has(e)){const r=t.clone();n.set(e,r)}return n.get(e)}updateReference(e){const t=e.renderer.getRenderTarget();return this.value=this.getTextureForReference(t),this.value}updateBefore(e){const t=e.renderer,n=t.getRenderTarget();null===n?t.getDrawingBufferSize(GT):GT.set(n.width,n.height);const r=this.getTextureForReference(n);r.image.width===GT.width&&r.image.height===GT.height||(r.image.width=GT.width,r.image.height=GT.height,r.needsUpdate=!0);const i=r.generateMipmaps;r.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(r),r.generateMipmaps=i}clone(){const e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}}const jT=jm(HT,null,null,{generateMipmaps:!0}).setParameterLength(0,3);let WT=null;class $T extends HT{static get type(){return"ViewportDepthTextureNode"}constructor(e=Ky,t=null){null===WT&&(WT=new Os),super(e,t,WT)}getTextureForReference(){return WT}}const XT=jm($T).setParameterLength(0,2);class qT extends Zf{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===qT.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,n=this.valueNode;let r=null;if(t===qT.DEPTH_BASE)null!==n&&(r=JT().assign(n));else if(t===qT.DEPTH)r=e.isPerspectiveCamera?KT(Tb.z,nb,rb):YT(Tb.z,nb,rb);else if(t===qT.LINEAR_DEPTH)if(null!==n)if(e.isPerspectiveCamera){const e=ZT(n,nb,rb);r=YT(e,nb,rb)}else r=n;else r=YT(Tb.z,nb,rb);return r}}qT.DEPTH_BASE="depthBase",qT.DEPTH="depth",qT.LINEAR_DEPTH="linearDepth";const YT=(e,t,n)=>e.add(t).div(t.sub(n)),KT=(e,t,n)=>t.add(e).mul(n).div(n.sub(t).mul(e)),ZT=(e,t,n)=>t.mul(n).div(n.sub(t).mul(e).sub(n)),QT=(e,t,n)=>{t=t.max(1e-6).toVar();const r=$_(e.negate().div(t)),i=$_(n.div(t));return r.div(i)},JT=jm(qT,qT.DEPTH_BASE),eS=Wm(qT,qT.DEPTH);XT(),eS.assign=e=>JT(e);class tS extends Zf{static get type(){return"ClippingNode"}constructor(e=tS.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===tS.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(n,r):this.scope===tS.HARDWARE?this.setupHardwareClipping(r,e):this.setupDefault(n,r)}setupAlphaToCoverage(e,t){return Ym(()=>{const n=tg().toVar("distanceToPlane"),r=tg().toVar("distanceToGradient"),i=tg(1).toVar("clipOpacity"),s=t.length;if(!1===this.hardwareClipping&&s>0){const e=jy(t).setGroup(n_);PT(s,({i:t})=>{const s=e.element(t);n.assign(Tb.dot(s.xyz).negate().add(s.w)),r.assign(n.fwidth().div(2)),i.mulAssign(Ov(r.negate(),r,n))})}const a=e.length;if(a>0){const t=jy(e).setGroup(n_),s=tg(1).toVar("intersectionClipOpacity");PT(a,({i:e})=>{const i=t.element(e);n.assign(Tb.dot(i.xyz).negate().add(i.w)),r.assign(n.fwidth().div(2)),s.mulAssign(Ov(r.negate(),r,n).oneMinus())}),i.mulAssign(s.oneMinus())}Sg.a.mulAssign(i),Sg.a.equal(0).discard()})()}setupDefault(e,t){return Ym(()=>{const n=t.length;if(!1===this.hardwareClipping&&n>0){const e=jy(t).setGroup(n_);PT(n,({i:t})=>{const n=e.element(t);Tb.dot(n.xyz).greaterThan(n.w).discard()})}const r=e.length;if(r>0){const t=jy(e).setGroup(n_),n=ig(!0).toVar("clipped");PT(r,({i:e})=>{const r=t.element(e);n.assign(Tb.dot(r.xyz).greaterThan(r.w).and(n))}),n.discard()}})()}setupHardwareClipping(e,t){const n=e.length;return t.enableHardwareClipping(n),Ym(()=>{const r=jy(e).setGroup(n_),i=Wy(t.getClipDistance());PT(n,({i:e})=>{const t=r.element(e),n=Tb.dot(t.xyz).sub(t.w).negate();i.element(e).assign(n)})})()}}tS.ALPHA_TO_COVERAGE="alphaToCoverage",tS.DEFAULT="default",tS.HARDWARE="hardware";const nS=Ym(([e])=>Q_(p_(1e4,J_(p_(17,e.x).add(p_(.1,e.y)))).mul(h_(.1,sv(J_(p_(13,e.y).add(e.x))))))),rS=Ym(([e])=>nS(sg(nS(e.xy),e.z))),iS=Ym(([e])=>{const t=bv(ov(cv(e.xyz)),ov(hv(e.xyz))),n=tg(1).div(tg(.05).mul(t)).toVar("pixScale"),r=sg(j_(Y_($_(n))),j_(K_($_(n)))),i=sg(rS(Y_(r.x.mul(e.xyz))),rS(Y_(r.y.mul(e.xyz)))),s=Q_($_(n)),a=h_(p_(s.oneMinus(),i.x),p_(s,i.y)),o=yv(s,s.oneMinus()),l=ug(a.mul(a).div(p_(2,o).mul(d_(1,o))),a.sub(p_(.5,o)).div(d_(1,o)),d_(1,d_(1,a).mul(d_(1,a)).div(p_(2,o).mul(d_(1,o))))),u=a.lessThan(o.oneMinus()).select(a.lessThan(o).select(l.x,l.y),l.z);return Dv(u,1e-6,1)}).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class sS extends Ry{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 Un(1,1,1,1)),n}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const aS=Ym(([e])=>pg(e.rgb.mul(e.a),e.a),{color:"vec4",return:"vec4"});class oS extends li{static get type(){return"NodeMaterial"}get type(){return this.constructor.type}set type(e){}constructor(){super(),this.isNodeMaterial=!0,this.fog=!0,this.lights=!1,this.hardwareClipping=!1,this.lightsNode=null,this.envNode=null,this.aoNode=null,this.colorNode=null,this.normalNode=null,this.opacityNode=null,this.backdropNode=null,this.backdropAlphaNode=null,this.alphaTestNode=null,this.maskNode=null,this.positionNode=null,this.geometryNode=null,this.depthNode=null,this.receivedShadowPositionNode=null,this.castShadowPositionNode=null,this.receivedShadowNode=null,this.castShadowNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null,this.contextNode=null,Object.defineProperty(this,"shadowPositionNode",{get:()=>this.receivedShadowPositionNode,set:e=>{Qt('NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".'),this.receivedShadowPositionNode=e}})}_getNodeChildren(){const e=[];for(const t of Object.getOwnPropertyNames(this)){if(!0===t.startsWith("_"))continue;const n=this[t];n&&!0===n.isNode&&e.push({property:t,childNode:n})}return e}customProgramCacheKey(){const e=[];for(const{property:t,childNode:n}of this._getNodeChildren())e.push(Cf(t.slice(0,-4)),n.getCacheKey());return this.type+Nf(e)}build(e){this.setup(e)}setupObserver(e){return new Af(e)}setup(e){e.context.setupNormal=()=>Xv(this.setupNormal(e),"NORMAL","vec3"),e.context.setupPositionView=()=>this.setupPositionView(e),e.context.setupModelViewProjection=()=>this.setupModelViewProjection(e);const t=e.renderer,n=t.getRenderTarget();!0===t.contextNode.isContextNode?e.context={...e.context,...t.contextNode.getFlowContextData()}:Jt('NodeMaterial: "renderer.contextNode" must be an instance of `context()`.'),null!==this.contextNode&&(!0===this.contextNode.isContextNode?e.context={...e.context,...this.contextNode.getFlowContextData()}:Jt('NodeMaterial: "material.contextNode" must be an instance of `context()`.')),e.addStack();const r=Xv(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.addToStack(a);const i=pg(r,Sg.a).max(0);s=this.setupOutput(e,i),Hg.assign(s);const o=null!==this.outputNode;if(o&&(s=this.outputNode),e.context.getOutput&&(s=e.context.getOutput(s,e)),null!==n){const e=t.getMRT(),n=this.mrtNode;null!==e?(o&&Hg.assign(s),s=e,null!==n&&(s=e.merge(n))):null!==n&&(s=n)}}else{let t=this.fragmentNode;!0!==t.isOutputStructNode&&(t=pg(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.currentSamples;this.alphaToCoverage&&t>1?r=new tS(tS.ALPHA_TO_COVERAGE):e.stack.addToStack(new tS)}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.addToStack(new tS(tS.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?QT(Tb.z,nb,rb):YT(Tb.z,nb,rb))}null!==r&&eS.assign(r).toStack()}setupPositionView(){return pb.mul(vb).xyz}setupModelViewProjection(){return ib.mul(Tb)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.vertex=e.removeStack(),fT}setupPosition(e){const{object:t,geometry:n}=e;var r;if((n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color)&&OT(t).toStack(),!0===t.isSkinnedMesh&&(r=t,new CT(r)).toStack(),this.displacementMap){const e=tx("displacementMap","texture"),t=tx("displacementScale","float"),n=tx("displacementBias","float");vb.addAssign(Rb.normalize().mul(e.x.mul(t).add(n)))}return t.isBatchedMesh&&AT(t).toStack(),t.isInstancedMesh&&t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&wT(t).toStack(),null!==this.positionNode&&vb.assign(Xv(this.positionNode,"POSITION","vec3")),vb}setupDiffuseColor(e){const{object:t,geometry:n}=e;null!==this.maskNode&&ig(this.maskNode).not().discard();let r=this.colorNode?pg(this.colorNode):Lx;if(!0===this.vertexColors&&n.hasAttribute("color")&&(r=r.mul(((e=0)=>new sS(e))())),t.instanceColor){r=Tg("vec3","vInstanceColor").mul(r)}if(t.isBatchedMesh&&t._colorsTexture){r=Tg("vec3","vBatchColor").mul(r)}Sg.assign(r);const i=this.opacityNode?tg(this.opacityNode):Ux;Sg.a.assign(Sg.a.mul(i));let s=null;(null!==this.alphaTestNode||this.alphaTest>0)&&(s=null!==this.alphaTestNode?tg(this.alphaTestNode):Px,!0===this.alphaToCoverage?(Sg.a=Ov(s,s.add(mv(Sg.a)),Sg.a),Sg.a.lessThanEqual(0).discard()):Sg.a.lessThanEqual(s).discard()),!0===this.alphaHash&&Sg.a.lessThan(iS(vb)).discard(),e.isOpaque()&&Sg.a.assign(1)}setupVariants(){}setupOutgoingLight(){return!0===this.lights?ug(0):Sg.rgb}setupNormal(){return this.normalNode?ug(this.normalNode):Hx}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?tx("envMap","cubeTexture"):tx("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new VT(hT)),t}setupLights(e){const t=[],n=this.setupEnvironment(e);n&&n.isLightingNode&&t.push(n);const r=this.setupLightMap(e);r&&r.isLightingNode&&t.push(r);let i=this.aoNode;null===i&&e.material.aoMap&&(i=dT),e.context.getAO&&(i=e.context.getAO(i,e)),i&&t.push(new BT(i));let s=this.lightsNode||e.lightsNode;return t.length>0&&(s=e.renderer.lighting.createNode([...s.getLights(),...t])),s}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=zT(s,t,n,r)}else null!==n&&(a=ug(null!==r?Lv(a,n,r):n));return(i&&!0===i.isNode||t.emissive&&!0===t.emissive.isColor)&&(wg.assign(ug(i||Ix)),a=a.add(wg)),a}setupFog(e,t){const n=e.fogNode;return n&&(Hg.assign(t),t=pg(n.toVar())),t}setupPremultipliedAlpha(e,t){return aS(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=li.prototype.toJSON.call(this,e);n.inputNodes={};for(const{property:t,childNode:r}of this._getNodeChildren())n.inputNodes[t]=r.toJSON(e).uuid;function r(e){const t=[];for(const n in e){const r=e[n];delete r.metadata,t.push(r)}return t}if(t){const t=r(e.textures),i=r(e.images),s=r(e.nodes);t.length>0&&(n.textures=t),i.length>0&&(n.images=i),s.length>0&&(n.nodes=s)}return n}copy(e){return this.lightsNode=e.lightsNode,this.envNode=e.envNode,this.aoNode=e.aoNode,this.colorNode=e.colorNode,this.normalNode=e.normalNode,this.opacityNode=e.opacityNode,this.backdropNode=e.backdropNode,this.backdropAlphaNode=e.backdropAlphaNode,this.alphaTestNode=e.alphaTestNode,this.maskNode=e.maskNode,this.positionNode=e.positionNode,this.geometryNode=e.geometryNode,this.depthNode=e.depthNode,this.receivedShadowPositionNode=e.receivedShadowPositionNode,this.castShadowPositionNode=e.castShadowPositionNode,this.receivedShadowNode=e.receivedShadowNode,this.castShadowNode=e.castShadowNode,this.outputNode=e.outputNode,this.mrtNode=e.mrtNode,this.fragmentNode=e.fragmentNode,this.vertexNode=e.vertexNode,this.contextNode=e.contextNode,super.copy(e)}}const lS=new ws;class uS extends oS{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(lS),this.setValues(e)}}const cS=new fa;class hS extends oS{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(cS),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?tg(this.offsetNode):lT,t=this.dashScaleNode?tg(this.dashScaleNode):sT,n=this.dashSizeNode?tg(this.dashSizeNode):aT,r=this.gapSizeNode?tg(this.gapSizeNode):oT;jg.assign(n),Wg.assign(r);const i=Yv(Cy("lineDistance").mul(t));(e?i.add(e):i).mod(jg.add(Wg)).greaterThan(jg).discard()}}const dS=new ua;class pS extends oS{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(dS),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?tg(this.opacityNode):Ux;Sg.assign(ey(pg(zm(Lb).mul(.5).add(.5),e),Et))}}const fS=Ym(([e=xb])=>{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 sg(t,n)});class mS extends rs{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 Hi(5,5,5),s=fS(xb),a=new oS;a.colorNode=By(t,s,0),a.side=1,a.blending=0;const o=new Vi(i,a),l=new os;l.add(o),t.minFilter===ye&&(t.minFilter=_e);const u=new ts(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 gS=new WeakMap;class _S extends em{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=Yb(null);const t=new ns;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=Vf}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===le||n===ue){if(gS.has(e)){const t=gS.get(e);yS(t,e.mapping),this._cubeTexture=t}else{const n=e.image;if(function(e){return null!=e&&e.height>0}(n)){const r=new mS(n.height);r.fromEquirectangularTexture(t,e),yS(r.texture,e.mapping),this._cubeTexture=r.texture,gS.set(e,r.texture),e.addEventListener("dispose",vS)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function vS(e){const t=e.target;t.removeEventListener("dispose",vS);const n=gS.get(t);void 0!==n&&(gS.delete(t),n.dispose())}function yS(e,t){t===le?e.mapping=ae:t===ue&&(e.mapping=oe)}const bS=jm(_S).setParameterLength(1);class xS extends FT{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=bS(this.envNode)}}class TS extends FT{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=tg(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class SS{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class MS extends SS{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,n=e.reflectedLight,r=e.irradianceLightMap;n.indirectDiffuse.assign(pg(0)),r?n.indirectDiffuse.addAssign(r):n.indirectDiffuse.addAssign(pg(1,1,1,0)),n.indirectDiffuse.mulAssign(t),n.indirectDiffuse.mulAssign(Sg.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(Lv(r.rgb,r.rgb.mul(i.rgb),kx.mul(zx)));break;case 1:r.rgb.assign(Lv(r.rgb,i.rgb,kx.mul(zx)));break;case 2:r.rgb.addAssign(i.rgb.mul(kx.mul(zx)));break;default:Qt("BasicLightingModel: Unsupported .combine value:",t.combine)}}}const wS=new ui;class ES extends oS{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(wS),this.setValues(e)}setupNormal(){return Eb(Nb)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new xS(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new TS(hT)),t}setupOutgoingLight(){return Sg.rgb}setupLightingModel(){return new MS}}const AS=Ym(({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))}),RS=Ym(e=>e.diffuseColor.mul(1/Math.PI)),CS=Ym(({dotNH:e})=>Gg.mul(tg(.5)).add(1).mul(tg(1/Math.PI)).mul(e.pow(Gg))),NS=Ym(({lightDirection:e})=>{const t=e.add(Sb).normalize(),n=Lb.dot(t).clamp(),r=Sb.dot(t).clamp(),i=AS({f0:kg,f90:1,dotVH:r}),s=tg(.25),a=CS({dotNH:n});return i.mul(s).mul(a)});class PS extends MS{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:n}){const r=Lb.dot(e).clamp().mul(t);n.directDiffuse.addAssign(r.mul(RS({diffuseColor:Sg.rgb}))),!0===this.specular&&n.directSpecular.addAssign(r.mul(NS({lightDirection:e})).mul(kx))}indirect(e){const{ambientOcclusion:t,irradiance:n,reflectedLight:r}=e.context;r.indirectDiffuse.addAssign(n.mul(RS({diffuseColor:Sg}))),r.indirectDiffuse.mulAssign(t)}}const LS=new ca;class DS extends oS{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(LS),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new xS(t):null}setupLightingModel(){return new PS(!1)}}const IS=new oa;class US extends oS{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(IS),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new xS(t):null}setupLightingModel(){return new PS}setupVariants(){const e=(this.shininessNode?tg(this.shininessNode):Dx).max(1e-4);Gg.assign(e);const t=this.specularNode||Ox;kg.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}const OS=Ym(e=>{if(!1===e.geometry.hasAttribute("normal"))return tg(0);const t=Nb.dFdx().abs().max(Nb.dFdy().abs());return t.x.max(t.y).max(t.z)}),FS=Ym(e=>{const{roughness:t}=e,n=OS();let r=t.max(.0525);return r=r.add(n),r=r.min(1),r}),BS=Ym(({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 f_(.5,i.add(s).max(F_))}).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),kS=Ym(({alphaT:e,alphaB:t,dotTV:n,dotBV:r,dotTL:i,dotBL:s,dotNV:a,dotNL:o})=>{const l=o.mul(ug(e.mul(n),t.mul(r),a).length()),u=a.mul(ug(e.mul(i),t.mul(s),o).length());return f_(.5,l.add(u))}).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"}]}),zS=Ym(({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"}]}),VS=tg(1/Math.PI),GS=Ym(({alphaT:e,alphaB:t,dotNH:n,dotTH:r,dotBH:i})=>{const s=e.mul(t),a=ug(t.mul(r),e.mul(i),s.mul(n)),o=a.dot(a),l=s.div(o);return VS.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"}]}),HS=Ym(({lightDirection:e,f0:t,f90:n,roughness:r,f:i,normalView:s=Lb,USE_IRIDESCENCE:a,USE_ANISOTROPY:o})=>{const l=r.pow2(),u=e.add(Sb).normalize(),c=s.dot(e).clamp(),h=s.dot(Sb).clamp(),d=s.dot(u).clamp(),p=Sb.dot(u).clamp();let f,m,g=AS({f0:t,f90:n,dotVH:p});if(Bm(a)&&(g=Lg.mix(g,i)),Bm(o)){const t=Fg.dot(e),n=Fg.dot(Sb),r=Fg.dot(u),i=Bg.dot(e),s=Bg.dot(Sb),a=Bg.dot(u);f=kS({alphaT:Ug,alphaB:l,dotTV:n,dotBV:s,dotTL:t,dotBL:i,dotNV:h,dotNL:c}),m=GS({alphaT:Ug,alphaB:l,dotNH:d,dotTH:r,dotBH:a})}else f=BS({alpha:l,dotNL:c,dotNV:h}),m=zS({alpha:l,dotNH:d});return g.mul(f).mul(m)}),jS=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]);let WS=null;const $S=Ym(({roughness:e,dotNV:t})=>{null===WS&&(WS=new ds(jS,16,16,ze,Ae),WS.name="DFG_LUT",WS.minFilter=_e,WS.magFilter=_e,WS.wrapS=de,WS.wrapT=de,WS.generateMipmaps=!1,WS.needsUpdate=!0);const n=sg(e,t);return By(WS,n).rg}),XS=Ym(({lightDirection:e,f0:t,f90:n,roughness:r,f:i,USE_IRIDESCENCE:s,USE_ANISOTROPY:a})=>{const o=HS({lightDirection:e,f0:t,f90:n,roughness:r,f:i,USE_IRIDESCENCE:s,USE_ANISOTROPY:a}),l=Lb.dot(e).clamp(),u=Lb.dot(Sb).clamp(),c=$S({roughness:r,dotNV:u}),h=$S({roughness:r,dotNV:l}),d=t.mul(c.x).add(n.mul(c.y)),p=t.mul(h.x).add(n.mul(h.y)),f=c.x.add(c.y),m=h.x.add(h.y),g=tg(1).sub(f),_=tg(1).sub(m),v=t.add(t.oneMinus().mul(.047619)),y=d.mul(p).mul(v).div(tg(1).sub(g.mul(_).mul(v).mul(v)).add(F_)),b=g.mul(_),x=y.mul(b);return o.add(x)}),qS=Ym(e=>{const{dotNV:t,specularColor:n,specularF90:r,roughness:i}=e,s=$S({dotNV:t,roughness:i});return n.mul(s.x).add(r.mul(s.y))}),YS=Ym(({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(ug(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"}]}),KS=Ym(({roughness:e,dotNH:t})=>{const n=e.pow2(),r=tg(1).div(n),i=t.pow2().oneMinus().max(.0078125);return tg(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"}]}),ZS=Ym(({dotNV:e,dotNL:t})=>tg(1).div(tg(4).mul(t.add(e).sub(t.mul(e))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),QS=Ym(({lightDirection:e})=>{const t=e.add(Sb).normalize(),n=Lb.dot(e).clamp(),r=Lb.dot(Sb).clamp(),i=Lb.dot(t).clamp(),s=KS({roughness:Pg,dotNH:i}),a=ZS({dotNV:r,dotNL:n});return Ng.mul(s).mul(a)}),JS=Ym(({N:e,V:t,roughness:n})=>{const r=e.dot(t).saturate(),i=sg(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"}]}),eM=Ym(({f:e})=>{const t=e.length();return bv(t.mul(t).add(e.z).div(t.add(1)),0)}).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),tM=Ym(({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,bv(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"}]}),nM=Ym(({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=ug().toVar();return Qm(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(vg(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=ug(0).toVar();g.addAssign(tM({v1:d,v2:p})),g.addAssign(tM({v1:p,v2:f})),g.addAssign(tM({v1:f,v2:m})),g.addAssign(tM({v1:m,v2:d})),h.assign(ug(eM({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"}]}),rM=1/6,iM=e=>p_(rM,p_(e,p_(e,e.negate().add(3)).sub(3)).add(1)),sM=e=>p_(rM,p_(e,p_(e,p_(3,e).sub(6))).add(4)),aM=e=>p_(rM,p_(e,p_(e,p_(-3,e).add(3)).add(3)).add(1)),oM=e=>p_(rM,Av(e,3)),lM=e=>iM(e).add(sM(e)),uM=e=>aM(e).add(oM(e)),cM=e=>h_(-1,sM(e).div(iM(e).add(sM(e)))),hM=e=>h_(1,oM(e).div(aM(e).add(oM(e)))),dM=(e,t,n)=>{const r=e.uvNode,i=p_(r,t.zw).add(.5),s=Y_(i),a=Q_(i),o=lM(a.x),l=uM(a.x),u=cM(a.x),c=hM(a.x),h=cM(a.y),d=hM(a.y),p=sg(s.x.add(u),s.y.add(h)).sub(.5).mul(t.xy),f=sg(s.x.add(c),s.y.add(h)).sub(.5).mul(t.xy),m=sg(s.x.add(u),s.y.add(d)).sub(.5).mul(t.xy),g=sg(s.x.add(c),s.y.add(d)).sub(.5).mul(t.xy),_=lM(a.y).mul(h_(o.mul(e.sample(p).level(n)),l.mul(e.sample(f).level(n)))),v=uM(a.y).mul(h_(o.mul(e.sample(m).level(n)),l.mul(e.sample(g).level(n))));return _.add(v)},pM=Ym(([e,t])=>{const n=sg(e.size(ng(t))),r=sg(e.size(ng(t.add(1)))),i=f_(1,n),s=f_(1,r),a=dM(e,pg(i,n),Y_(t)),o=dM(e,pg(s,r),K_(t));return Q_(t).mix(a,o)}),fM=Ym(([e,t,n,r,i])=>{const s=ug(Uv(t.negate(),Z_(e),f_(1,r))),a=ug(ov(i[0].xyz),ov(i[1].xyz),ov(i[2].xyz));return Z_(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"}]}),mM=Ym(([e,t])=>e.mul(Dv(t.mul(2).sub(2),0,1))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),gM=jT(),_M=jT(),vM=Ym(([e,t,n],{material:r})=>{const i=(1===r.side?gM:_M).sample(e),s=$_(Zy.x).mul(mM(t,n));return pM(i,s)}),yM=Ym(([e,t,n])=>(Qm(n.notEqual(0),()=>{const r=W_(t).negate().div(n);return H_(r.negate().mul(e))}),ug(1))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),bM=Ym(([e,t,n,r,i,s,a,o,l,u,c,h,d,p,f])=>{let m,g;if(f){m=pg().toVar(),g=ug().toVar();const i=c.sub(1).mul(f.mul(.025)),s=ug(c.sub(i),c,c.add(i));PT({start:0,end:3},({i:i})=>{const c=s.element(i),f=fM(e,t,h,c,o),_=a.add(f),v=u.mul(l.mul(pg(_,1))),y=sg(v.xy.div(v.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(sg(y.x,y.y.oneMinus()));const b=vM(y,n,c);m.element(i).assign(b.element(i)),m.a.addAssign(b.a),g.element(i).assign(r.element(i).mul(yM(ov(f),d,p).element(i)))}),m.a.divAssign(3)}else{const i=fM(e,t,h,c,o),s=a.add(i),f=u.mul(l.mul(pg(s,1))),_=sg(f.xy.div(f.w)).toVar();_.addAssign(1),_.divAssign(2),_.assign(sg(_.x,_.y.oneMinus())),m=vM(_,n,c),g=r.mul(yM(ov(i),d,p))}const _=g.rgb.mul(m.rgb),v=e.dot(t).clamp(),y=ug(qS({dotNV:v,specularColor:i,specularF90:s,roughness:n})),b=g.r.add(g.g,g.b).div(3);return pg(y.oneMinus().mul(_),m.a.oneMinus().mul(b).oneMinus())}),xM=vg(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),TM=(e,t)=>e.sub(t).div(e.add(t)).pow2(),SM=Ym(({outsideIOR:e,eta2:t,cosTheta1:n,thinFilmThickness:r,baseF0:i})=>{const s=Lv(e,t,Ov(0,.03,r)),a=e.div(s).pow2().mul(n.pow2().oneMinus()).oneMinus();Qm(a.lessThan(0),()=>ug(1));const o=a.sqrt(),l=TM(s,e),u=AS({f0:l,f90:1,dotVH:n}),c=u.oneMinus(),h=s.lessThan(e).select(Math.PI,0),d=tg(Math.PI).sub(h),p=(e=>{const t=e.sqrt();return ug(1).add(t).div(ug(1).sub(t))})(i.clamp(0,.9999)),f=TM(p,s.toVec3()),m=AS({f0:f,f90:1,dotVH:o}),g=ug(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=ug(d).add(g),y=u.mul(m).clamp(1e-5,.9999),b=y.sqrt(),x=c.pow2().mul(m).div(ug(1).sub(y)),T=u.add(x).toVar(),S=x.sub(c).toVar();return PT({start:1,end:2,condition:"<=",name:"m"},({m:e})=>{S.mulAssign(b);const t=((e,t)=>{const n=e.mul(2*Math.PI*1e-9),r=ug(54856e-17,44201e-17,52481e-17),i=ug(1681e3,1795300,2208400),s=ug(43278e5,93046e5,66121e5),a=tg(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=ug(o.x.add(a),o.y,o.z).div(1.0685e-7),xM.mul(o)})(tg(e).mul(_),tg(e).mul(v)).mul(2);T.addAssign(S.mul(t))}),T.max(ug(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"}]}),MM=Ym(({normal:e,viewDir:t,roughness:n})=>{const r=e.dot(t).saturate(),i=n.mul(n),s=n.add(.1).reciprocal(),a=tg(-1.9362).add(n.mul(1.0678)).add(i.mul(.4573)).sub(s.mul(.8469)),o=tg(-.6014).add(n.mul(.5538)).sub(i.mul(.467)).sub(s.mul(.1255));return a.mul(r).add(o).exp().saturate()}),wM=ug(.04),EM=tg(1);class AM extends SS{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,this.iridescenceF0Dielectric=null,this.iridescenceF0Metallic=null}start(e){if(!0===this.clearcoat&&(this.clearcoatRadiance=ug().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=ug().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=ug().toVar("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=ug().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=ug().toVar("sheenSpecularIndirect")),!0===this.iridescence){const e=Lb.dot(Sb).clamp(),t=SM({outsideIOR:tg(1),eta2:Dg,cosTheta1:e,thinFilmThickness:Ig,baseF0:kg}),n=SM({outsideIOR:tg(1),eta2:Dg,cosTheta1:e,thinFilmThickness:Ig,baseF0:Sg.rgb});this.iridescenceFresnel=Lv(t,n,Ag),this.iridescenceF0Dielectric=YS({f:t,f90:1,dotVH:e}),this.iridescenceF0Metallic=YS({f:n,f90:1,dotVH:e}),this.iridescenceF0=Lv(this.iridescenceF0Dielectric,this.iridescenceF0Metallic,Ag)}if(!0===this.transmission){const t=bb,n=ab.sub(bb).normalize(),r=Db,i=e.context;i.backdrop=bM(r,n,Eg,Mg,zg,Vg,t,hb,sb,ib,$g,qg,Kg,Yg,this.dispersion?Zg:null),i.backdropAlpha=Xg,Sg.a.mulAssign(Lv(1,i.backdrop.a,Xg))}super.start(e)}computeMultiscattering(e,t,n,r,i=null){const s=Lb.dot(Sb).clamp(),a=$S({roughness:Eg,dotNV:s}),o=i?Lg.mix(r,i):r,l=o.mul(a.x).add(n.mul(a.y)),u=a.x.add(a.y).oneMinus(),c=o.add(o.oneMinus().mul(.047619)),h=l.mul(c).div(u.mul(c).oneMinus());e.addAssign(l),t.addAssign(h.mul(u))}direct({lightDirection:e,lightColor:t,reflectedLight:n}){const r=Lb.dot(e).clamp().mul(t).toVar();if(!0===this.sheen){this.sheenSpecularDirect.addAssign(r.mul(QS({lightDirection:e})));const t=MM({normal:Lb,viewDir:Sb,roughness:Pg}),n=MM({normal:Lb,viewDir:e,roughness:Pg}),i=Ng.r.max(Ng.g).max(Ng.b).mul(t.max(n)).oneMinus();r.mulAssign(i)}if(!0===this.clearcoat){const n=Ib.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(n.mul(HS({lightDirection:e,f0:wM,f90:EM,roughness:Cg,normalView:Ib})))}n.directDiffuse.addAssign(r.mul(RS({diffuseColor:Mg}))),n.directSpecular.addAssign(r.mul(XS({lightDirection:e,f0:zg,f90:1,roughness:Eg,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=Lb,d=Sb,p=Tb.toVar(),f=JS({N:h,V:d,roughness:Eg}),m=s.sample(f).toVar(),g=a.sample(f).toVar(),_=vg(ug(m.x,0,m.y),ug(0,1,0),ug(m.z,0,m.w)).toVar(),v=zg.mul(g.x).add(zg.oneMinus().mul(g.y)).toVar();i.directSpecular.addAssign(e.mul(v).mul(nM({N:h,V:d,P:p,mInv:_,p0:o,p1:l,p2:u,p3:c}))),i.directDiffuse.addAssign(e.mul(Mg).mul(nM({N:h,V:d,P:p,mInv:vg(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,r=t.mul(RS({diffuseColor:Mg})).toVar();if(!0===this.sheen){const e=MM({normal:Lb,viewDir:Sb,roughness:Pg}),t=Ng.r.max(Ng.g).max(Ng.b).mul(e).oneMinus();r.mulAssign(t)}n.indirectDiffuse.addAssign(r)}indirectSpecular(e){const{radiance:t,iblIrradiance:n,reflectedLight:r}=e.context;if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(n.mul(Ng,MM({normal:Lb,viewDir:Sb,roughness:Pg}))),!0===this.clearcoat){const e=Ib.dot(Sb).clamp(),t=qS({dotNV:e,specularColor:wM,specularF90:EM,roughness:Cg});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const i=ug().toVar("singleScatteringDielectric"),s=ug().toVar("multiScatteringDielectric"),a=ug().toVar("singleScatteringMetallic"),o=ug().toVar("multiScatteringMetallic");this.computeMultiscattering(i,s,Vg,kg,this.iridescenceF0Dielectric),this.computeMultiscattering(a,o,Vg,Sg.rgb,this.iridescenceF0Metallic);const l=Lv(i,a,Ag),u=Lv(s,o,Ag),c=i.add(s),h=Mg.mul(c.oneMinus()),d=n.mul(1/Math.PI),p=t.mul(l).add(u.mul(d)).toVar(),f=h.mul(d).toVar();if(!0===this.sheen){const e=MM({normal:Lb,viewDir:Sb,roughness:Pg}),t=Ng.r.max(Ng.g).max(Ng.b).mul(e).oneMinus();p.mulAssign(t),f.mulAssign(t)}r.indirectSpecular.addAssign(p),r.indirectDiffuse.addAssign(f)}ambientOcclusion(e){const{ambientOcclusion:t,reflectedLight:n}=e.context,r=Lb.dot(Sb).clamp().add(t),i=Eg.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=Ib.dot(Sb).clamp(),n=AS({dotVH:e,f0:wM,f90:EM}),r=t.mul(Rg.mul(n).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(Rg));t.assign(r)}if(!0===this.sheen){const e=t.add(this.sheenSpecularDirect,this.sheenSpecularIndirect.mul(1/Math.PI));t.assign(e)}}}const RM=tg(1),CM=tg(-2),NM=tg(.8),PM=tg(-1),LM=tg(.4),DM=tg(2),IM=tg(.305),UM=tg(3),OM=tg(.21),FM=tg(4),BM=tg(4),kM=tg(16),zM=Ym(([e])=>{const t=ug(sv(e)).toVar(),n=tg(-1).toVar();return Qm(t.x.greaterThan(t.z),()=>{Qm(t.x.greaterThan(t.y),()=>{n.assign(zv(e.x.greaterThan(0),0,3))}).Else(()=>{n.assign(zv(e.y.greaterThan(0),1,4))})}).Else(()=>{Qm(t.z.greaterThan(t.y),()=>{n.assign(zv(e.z.greaterThan(0),2,5))}).Else(()=>{n.assign(zv(e.y.greaterThan(0),1,4))})}),n}).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),VM=Ym(([e,t])=>{const n=sg().toVar();return Qm(t.equal(0),()=>{n.assign(sg(e.z,e.y).div(sv(e.x)))}).ElseIf(t.equal(1),()=>{n.assign(sg(e.x.negate(),e.z.negate()).div(sv(e.y)))}).ElseIf(t.equal(2),()=>{n.assign(sg(e.x.negate(),e.y).div(sv(e.z)))}).ElseIf(t.equal(3),()=>{n.assign(sg(e.z.negate(),e.y).div(sv(e.x)))}).ElseIf(t.equal(4),()=>{n.assign(sg(e.x.negate(),e.z).div(sv(e.y)))}).Else(()=>{n.assign(sg(e.x,e.y).div(sv(e.z)))}),p_(.5,n.add(1))}).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),GM=Ym(([e])=>{const t=tg(0).toVar();return Qm(e.greaterThanEqual(NM),()=>{t.assign(RM.sub(e).mul(PM.sub(CM)).div(RM.sub(NM)).add(CM))}).ElseIf(e.greaterThanEqual(LM),()=>{t.assign(NM.sub(e).mul(DM.sub(PM)).div(NM.sub(LM)).add(PM))}).ElseIf(e.greaterThanEqual(IM),()=>{t.assign(LM.sub(e).mul(UM.sub(DM)).div(LM.sub(IM)).add(DM))}).ElseIf(e.greaterThanEqual(OM),()=>{t.assign(IM.sub(e).mul(FM.sub(UM)).div(IM.sub(OM)).add(UM))}).Else(()=>{t.assign(tg(-2).mul($_(p_(1.16,e))))}),t}).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),HM=Ym(([e,t])=>{const n=e.toVar();n.assign(p_(2,n).sub(1));const r=ug(n,1).toVar();return Qm(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"}]}),jM=Ym(([e,t,n,r,i,s])=>{const a=tg(n),o=ug(t),l=Dv(GM(a),CM,s),u=Q_(l),c=Y_(l),h=ug(WM(e,o,c,r,i,s)).toVar();return Qm(u.notEqual(0),()=>{const t=ug(WM(e,o,c.add(1),r,i,s)).toVar();h.assign(Lv(h,t,u))}),h}),WM=Ym(([e,t,n,r,i,s])=>{const a=tg(n).toVar(),o=ug(t),l=tg(zM(o)).toVar(),u=tg(bv(BM.sub(a),0)).toVar();a.assign(bv(a,BM));const c=tg(j_(a)).toVar(),h=sg(VM(o,l).mul(c.sub(2)).add(1)).toVar();return Qm(l.greaterThan(2),()=>{h.y.addAssign(c),l.subAssign(3)}),h.x.addAssign(l.mul(c)),h.x.addAssign(u.mul(p_(3,kM))),h.y.addAssign(p_(4,j_(s).sub(c))),h.x.mulAssign(r),h.y.mulAssign(i),e.sample(h).grad(sg(),sg())}),$M=Ym(({envMap:e,mipInt:t,outputDirection:n,theta:r,axis:i,CUBEUV_TEXEL_WIDTH:s,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const l=ev(r),u=n.mul(l).add(i.cross(n).mul(J_(r))).add(i.mul(i.dot(n).mul(l.oneMinus())));return WM(e,u,t,s,a,o)}),XM=Ym(({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=ug(zv(t,n,Ev(n,r))).toVar();Qm(d.equal(ug(0)),()=>{d.assign(ug(r.z,0,r.x.negate()))}),d.assign(Z_(d));const p=ug().toVar();return p.addAssign(i.element(0).mul($M({theta:0,axis:d,outputDirection:r,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:c,CUBEUV_MAX_MIP:h}))),PT({start:ng(1),end:e},({i:e})=>{Qm(e.greaterThanEqual(s),()=>{Sy("break").toStack()});const t=tg(a.mul(tg(e))).toVar();p.addAssign(i.element(e).mul($M({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($M({theta:t,axis:d,outputDirection:r,mipInt:o,envMap:l,CUBEUV_TEXEL_WIDTH:u,CUBEUV_TEXEL_HEIGHT:c,CUBEUV_MAX_MIP:h})))}),pg(p,1)}),qM=Ym(([e])=>{const t=rg(e).toVar();return t.assign(t.shiftLeft(rg(16)).bitOr(t.shiftRight(rg(16)))),t.assign(t.bitAnd(rg(1431655765)).shiftLeft(rg(1)).bitOr(t.bitAnd(rg(2863311530)).shiftRight(rg(1)))),t.assign(t.bitAnd(rg(858993459)).shiftLeft(rg(2)).bitOr(t.bitAnd(rg(3435973836)).shiftRight(rg(2)))),t.assign(t.bitAnd(rg(252645135)).shiftLeft(rg(4)).bitOr(t.bitAnd(rg(4042322160)).shiftRight(rg(4)))),t.assign(t.bitAnd(rg(16711935)).shiftLeft(rg(8)).bitOr(t.bitAnd(rg(4278255360)).shiftRight(rg(8)))),tg(t).mul(2.3283064365386963e-10)}),YM=Ym(([e,t])=>sg(tg(e).div(tg(t)),qM(e))),KM=Ym(([e,t,n])=>{const r=ug(t).toVar(),i=tg(n),s=i.mul(i).toVar(),a=Z_(ug(s.mul(r.x),s.mul(r.y),r.z)).toVar(),o=a.x.mul(a.x).add(a.y.mul(a.y)),l=zv(o.greaterThan(0),ug(a.y.negate(),a.x,0).div(X_(o)),ug(1,0,0)).toVar(),u=Ev(a,l).toVar(),c=X_(e.x),h=p_(2,3.14159265359).mul(e.y),d=c.mul(ev(h)).toVar(),p=c.mul(J_(h)).toVar(),f=p_(.5,a.z.add(1));p.assign(f.oneMinus().mul(X_(d.mul(d).oneMinus())).add(f.mul(p)));const m=l.mul(d).add(u.mul(p)).add(a.mul(X_(bv(0,d.mul(d).add(p.mul(p)).oneMinus()))));return Z_(ug(s.mul(m.x),s.mul(m.y),bv(0,m.z)))}),ZM=Ym(({roughness:e,mipInt:t,envMap:n,N_immutable:r,GGX_SAMPLES:i,CUBEUV_TEXEL_WIDTH:s,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:o})=>{const l=ug(r).toVar(),u=ug(0).toVar(),c=tg(0).toVar();return Qm(e.lessThan(.001),()=>{u.assign(WM(n,l,t,s,a,o))}).Else(()=>{const r=zv(sv(l.z).lessThan(.999),ug(0,0,1),ug(1,0,0)),h=Z_(Ev(r,l)).toVar(),d=Ev(l,h).toVar();PT({start:rg(0),end:i},({i:r})=>{const p=YM(r,i),f=KM(p,ug(0,0,1),e),m=Z_(h.mul(f.x).add(d.mul(f.y)).add(l.mul(f.z))),g=Z_(m.mul(wv(l,m).mul(2)).sub(l)),_=bv(wv(l,g),0);Qm(_.greaterThan(0),()=>{const e=WM(n,g,t,s,a,o);u.addAssign(e.mul(_)),c.addAssign(_)})}),Qm(c.greaterThan(0),()=>{u.assign(u.div(c))})}),pg(u,1)}),QM=[.125,.215,.35,.446,.526,.582],JM=20,ew=new Pa(-1,1,1,-1,0,1),tw=new Ji(90,1),nw=new si;let rw=null,iw=0,sw=0;const aw=new gn,ow=new WeakMap,lw=[3,1,5,0,4,2],uw=HM(Ny(),Cy("faceIndex")).normalize(),cw=ug(uw.x,uw.y,uw.z);class hw{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._blurMaterial=null,this._ggxMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._backgroundBox=null}get _hasInitialized(){return this._renderer.hasInitialized()}fromScene(e,t=0,n=.1,r=100,i={}){const{size:s=256,position:a=aw,renderTarget:o=null}=i;if(this._setSize(s),!1===this._hasInitialized){Qt('PMREMGenerator: ".fromScene()" called before the backend is initialized. Try using "await renderer.init()" instead.');const s=o||this._allocateTarget();return i.renderTarget=s,this.fromSceneAsync(e,t,n,r,i),s}rw=this._renderer.getRenderTarget(),iw=this._renderer.getActiveCubeFace(),sw=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 en('PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this.fromScene(e,t,n,r,i)}fromEquirectangular(e,t=null){if(!1===this._hasInitialized){Qt('PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using "await renderer.init()" 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 en('PMREMGenerator: ".fromEquirectangularAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}fromCubemap(e,t=null){if(!1===this._hasInitialized){Qt("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 en('PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=mw(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=gw(),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===ae||e.mapping===oe?this._setSize(0===e.image.length?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4)}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._ggxMaterial&&this._ggxMaterial.dispose(),null!==this._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let e=0;ee-4?o=QM[a-e+4-1]:0===a&&(o=0),n.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;e2?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=lw[e];_.set(r,f*p*i),v.set(h,m*p*i);const s=[i,i,i,i,i,i];y.set(s,g*p*i)}const b=new Ci;b.setAttribute("position",new _i(_,f)),b.setAttribute("uv",new _i(v,m)),b.setAttribute("faceIndex",new _i(y,g)),r.push(new Vi(b,null)),i>4&&i--}return{lodMeshes:r,sizeLods:t,sigmas:n}}(t)),this._blurMaterial=function(e,t,n){const r=jy(new Array(JM).fill(0)),i=s_(new gn(0,1,0)),s=s_(0),a=tg(JM),o=s_(0),l=s_(1),u=By(),c=s_(0),h=tg(1/t),d=tg(1/n),p=tg(e),f={n:a,latitudinal:o,weights:r,poleAxis:i,outputDirection:cw,dTheta:s,samples:l,envMap:u,mipInt:c,CUBEUV_TEXEL_WIDTH:h,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:p},m=fw("blur");return m.fragmentNode=XM({...f,latitudinal:o.equal(1)}),ow.set(m,f),m}(t,e.width,e.height),this._ggxMaterial=function(e,t,n){const r=By(),i=s_(0),s=s_(0),a=tg(1/t),o=tg(1/n),l=tg(e),u={envMap:r,roughness:i,mipInt:s,CUBEUV_TEXEL_WIDTH:a,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:l},c=fw("ggx");return c.fragmentNode=ZM({...u,N_immutable:cw,GGX_SAMPLES:rg(512)}),ow.set(c,u),c}(t,e.width,e.height)}}async _compileMaterial(e){const t=new Vi(new Ci,e);await this._renderer.compile(t,ew)}_sceneToCubeUV(e,t,n,r,i){const s=tw;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(nw),l.autoClear=!1,null===this._backgroundBox&&(this._backgroundBox=new Vi(new Hi,new ui({name:"PMREM.Background",side:1,depthWrite:!1,depthTest:!1})));const c=this._backgroundBox,h=c.material;let d=!1;const p=e.background;p?p.isColor&&(h.color.copy(p),e.background=null,d=!0):(h.color.copy(nw),d=!0),l.setRenderTarget(r),l.clear(),d&&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;pw(r,n*u,t>2?u:0,u,u),l.render(e,s)}l.autoClear=u,e.background=p}_textureToCubeUV(e,t){const n=this._renderer,r=e.mapping===ae||e.mapping===oe;r?null===this._cubemapMaterial&&(this._cubemapMaterial=mw(e)):null===this._equirectMaterial&&(this._equirectMaterial=gw(e));const i=r?this._cubemapMaterial:this._equirectMaterial;i.fragmentNode.value=e;const s=this._lodMeshes[0];s.material=i;const a=this._cubeSize;pw(t,0,0,3*a,2*a),n.setRenderTarget(t),n.render(s,ew)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;const r=this._lodMeshes.length;for(let t=1;th-4?n-h+4:0),f=4*(this._cubeSize-d);e.texture.frame=(e.texture.frame||0)+1,o.envMap.value=e.texture,o.roughness.value=c,o.mipInt.value=h-t,pw(i,p,f,3*d,2*d),r.setRenderTarget(i),r.render(a,ew),i.texture.frame=(i.texture.frame||0)+1,o.envMap.value=i.texture,o.roughness.value=0,o.mipInt.value=h-n,pw(e,p,f,3*d,2*d),r.setRenderTarget(e),r.render(a,ew)}_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&&Jt("blur direction must be either latitudinal or longitudinal!");const u=this._lodMeshes[r];u.material=l;const c=ow.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):JM;f>JM&&Qt(`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_-4?r-_+4:0),4*(this._cubeSize-v),3*v,2*v),o.setRenderTarget(t),o.render(u,ew)}}function dw(e,t){const n=new On(e,t,{magFilter:_e,minFilter:_e,generateMipmaps:!1,type:Ae,format:Ue,colorSpace:At});return n.texture.mapping=ce,n.texture.name="PMREM.cubeUv",n.texture.isPMREMTexture=!0,n.scissorTest=!0,n}function pw(e,t,n,r,i){e.viewport.set(t,n,r,i),e.scissor.set(t,n,r,i)}function fw(e){const t=new oS;return t.depthTest=!1,t.depthWrite=!1,t.blending=0,t.name=`PMREM_${e}`,t}function mw(e){const t=fw("cubemap");return t.fragmentNode=Yb(e,cw),t}function gw(e){const t=fw("equirect");return t.fragmentNode=By(e,fS(cw),0),t}const _w=new WeakMap;function vw(e,t,n){const r=function(e){let t=_w.get(e);void 0===t&&(t=new WeakMap,_w.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;r0}(t))return null;i=n.fromEquirectangular(e,i)}i.pmremVersion=e.pmremVersion,r.set(e,i)}return i.texture}class yw extends em{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 In;r.isRenderTargetTexture=!0,this._texture=By(r),this._width=s_(0),this._height=s_(0),this._maxMip=s_(0),this.updateBeforeType=Vf}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:vw(r,e.renderer,this._generator),null!==t&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){null===this._generator&&(this._generator=new hw(e.renderer)),this.updateBefore(e);let t=this.uvNode;null===t&&e.context.getUV&&(t=e.context.getUV(this,e)),t=Vb.mul(ug(t.x,t.y.negate(),t.z));let n=this.levelNode;return null===n&&e.context.getTextureLevel&&(n=e.context.getTextureLevel(this)),jM(this._texture,t,n,this._width,this._height,this._maxMip)}dispose(){super.dispose(),null!==this._generator&&this._generator.dispose()}}const bw=jm(yw).setParameterLength(1,3),xw=new WeakMap;class Tw extends FT{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=xw.get(e);void 0===r&&(r=bw(e),xw.set(e,r)),n=r}const r=!0===t.useAnisotropy||t.anisotropy>0?xx:Lb,i=n.context(Sw(Eg,r)).mul(zb),s=n.context(Mw(Db)).mul(Math.PI).mul(zb),a=_y(i),o=_y(s);e.context.radiance.addAssign(a),e.context.iblIrradiance.addAssign(o);const l=e.context.lightingModel.clearcoatRadiance;if(l){const e=n.context(Sw(Cg,Ib)).mul(zb),t=_y(e);l.addAssign(t)}}}const Sw=(e,t)=>{let n=null;return{getUV:()=>(null===n&&(n=Sb.negate().reflect(t),n=Cv(e).mix(n,t).normalize(),n=n.transformDirection(sb)),n),getTextureLevel:()=>e}},Mw=e=>({getUV:()=>e,getTextureLevel:()=>tg(1)}),ww=new sa;class Ew extends oS{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(ww),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return null===t&&e.environmentNode&&(t=e.environmentNode),t?new Tw(t):null}setupLightingModel(){return new AM}setupSpecular(){const e=Lv(ug(.04),Sg.rgb,Ag);kg.assign(ug(.04)),zg.assign(e),Vg.assign(1)}setupVariants(){const e=this.metalnessNode?tg(this.metalnessNode):Gx;Ag.assign(e);let t=this.roughnessNode?tg(this.roughnessNode):Vx;t=FS({roughness:t}),Eg.assign(t),this.setupSpecular(),Mg.assign(Sg.rgb.mul(e.oneMinus()))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}const Aw=new aa;class Rw extends Ew{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(Aw),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?tg(this.iorNode):nT;$g.assign(e),kg.assign(yv(Rv($g.sub(1).div($g.add(1))).mul(Bx),ug(1)).mul(Fx)),zg.assign(Lv(kg,Sg.rgb,Ag)),Vg.assign(Lv(Fx,1,Ag))}setupLightingModel(){return new AM(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?tg(this.clearcoatNode):jx,t=this.clearcoatRoughnessNode?tg(this.clearcoatRoughnessNode):Wx;Rg.assign(e),Cg.assign(FS({roughness:t}))}if(this.useSheen){const e=this.sheenNode?ug(this.sheenNode):qx,t=this.sheenRoughnessNode?tg(this.sheenRoughnessNode):Yx;Ng.assign(e),Pg.assign(t)}if(this.useIridescence){const e=this.iridescenceNode?tg(this.iridescenceNode):Zx,t=this.iridescenceIORNode?tg(this.iridescenceIORNode):Qx,n=this.iridescenceThicknessNode?tg(this.iridescenceThicknessNode):Jx;Lg.assign(e),Dg.assign(t),Ig.assign(n)}if(this.useAnisotropy){const e=(this.anisotropyNode?sg(this.anisotropyNode):Kx).toVar();Og.assign(e.length()),Qm(Og.equal(0),()=>{e.assign(sg(1,0))}).Else(()=>{e.divAssign(sg(Og)),Og.assign(Og.saturate())}),Ug.assign(Og.pow2().mix(Eg.pow2(),1)),Fg.assign(bx[0].mul(e.x).add(bx[1].mul(e.y))),Bg.assign(bx[1].mul(e.x).sub(bx[0].mul(e.y)))}if(this.useTransmission){const e=this.transmissionNode?tg(this.transmissionNode):eT,t=this.thicknessNode?tg(this.thicknessNode):tT,n=this.attenuationDistanceNode?tg(this.attenuationDistanceNode):rT,r=this.attenuationColorNode?ug(this.attenuationColorNode):iT;if(Xg.assign(e),qg.assign(t),Yg.assign(n),Kg.assign(r),this.useDispersion){const e=this.dispersionNode?tg(this.dispersionNode):cT;Zg.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?ug(this.clearcoatNormalNode):$x}setup(e){e.context.setupClearcoatNormal=()=>Xv(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 Cw=Ym(({normal:e,lightDirection:t,builder:n})=>{const r=e.dot(t),i=sg(r.mul(.5).add(.5),0);if(n.material.gradientMap){const e=tx("gradientMap","texture").context({getUV:()=>i});return ug(e.r)}{const e=i.fwidth().mul(.5);return Lv(ug(.7),ug(1),Ov(tg(.7).sub(e.x),tg(.7).add(e.x),i.x))}});class Nw extends SS{direct({lightDirection:e,lightColor:t,reflectedLight:n},r){const i=Cw({normal:Ab,lightDirection:e,builder:r}).mul(t);n.directDiffuse.addAssign(i.mul(RS({diffuseColor:Sg.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:n,reflectedLight:r}=e.context;r.indirectDiffuse.addAssign(n.mul(RS({diffuseColor:Sg}))),r.indirectDiffuse.mulAssign(t)}}const Pw=new la;class Lw extends oS{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Pw),this.setValues(e)}setupLightingModel(){return new Nw}}const Dw=Ym(()=>{const e=ug(Sb.z,0,Sb.x.negate()).normalize(),t=Sb.cross(e);return sg(e.dot(Lb),t.dot(Lb)).mul(.495).add(.5)}).once(["NORMAL","VERTEX"])().toVar("matcapUV"),Iw=new pa;class Uw extends oS{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(Iw),this.setValues(e)}setupVariants(e){const t=Dw;let n;n=e.material.matcap?tx("matcap","texture").context({getUV:()=>t}):ug(Lv(.2,.8,t.y)),Sg.rgb.mulAssign(n.rgb)}}class Ow extends em{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 _g(e,r,r.negate(),e).mul(n)}{const e=t,r=yg(pg(1,0,0,0),pg(0,ev(e.x),J_(e.x).negate(),0),pg(0,J_(e.x),ev(e.x),0),pg(0,0,0,1)),i=yg(pg(ev(e.y),0,J_(e.y),0),pg(0,1,0,0),pg(J_(e.y).negate(),0,ev(e.y),0),pg(0,0,0,1)),s=yg(pg(ev(e.z),J_(e.z).negate(),0,0),pg(J_(e.z),ev(e.z),0,0),pg(0,0,1,0),pg(0,0,0,1));return r.mul(i).mul(s).mul(pg(n,1)).xyz}}}const Fw=jm(Ow).setParameterLength(2),Bw=new hs;class kw extends oS{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(Bw),this.setValues(e)}setupPositionView(e){const{object:t,camera:n}=e,{positionNode:r,rotationNode:i,scaleNode:s,sizeAttenuation:a}=this,o=pb.mul(ug(r||0));let l=sg(hb[0].xyz.length(),hb[1].xyz.length());null!==s&&(l=l.mul(sg(s))),n.isPerspectiveCamera&&!1===a&&(l=l.mul(o.z.negate()));let u=_b.xy;if(t.center&&!0===t.center.isVector2){const e=((e,t,n)=>new ny(e,t,n))("center","vec2",t);u=u.sub(e.sub(.5))}u=u.mul(l);const c=tg(i||Xx),h=Fw(u,c);return pg(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 zw=new Is,Vw=new fn;class Gw extends kw{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(zw),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return pb.mul(ug(e||vb)).xyz}setupVertexSprite(e){const{material:t,camera:n}=e,{rotationNode:r,scaleNode:i,sizeNode:s,sizeAttenuation:a}=this;let o=super.setupVertex(e);if(!0!==t.isNodeMaterial)return o;let l=null!==s?sg(s):uT;l=l.mul(Yy),n.isPerspectiveCamera&&!0===a&&(l=l.mul(Hw.div(Tb.z.negate()))),i&&i.isNode&&(l=l.mul(sg(i)));let u=_b.xy;if(r&&r.isNode){const e=tg(r);u=Fw(u,e)}return u=u.mul(l),u=u.div(eb.div(2)),u=u.mul(o.w),o=o.add(pg(u,0,0)),o}setupVertex(e){return e.object.isPoints?super.setupVertex(e):this.setupVertexSprite(e)}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}}const Hw=s_(1).onFrameUpdate(function({renderer:e}){const t=e.getSize(Vw);this.value=.5*t.y});class jw extends SS{constructor(){super(),this.shadowNode=tg(1).toVar("shadowMask")}direct({lightNode:e}){null!==e.shadowNode&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){Sg.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(Sg.rgb)}}const Ww=new ra;class $w extends oS{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(Ww),this.setValues(e)}setupLightingModel(){return new jw}}xg("vec3"),xg("vec3"),xg("vec3");class Xw{constructor(e,t,n){this.renderer=e,this.nodes=t,this.info=n,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,this.renderer._inspector.begin(),null!==this._animationLoop&&this._animationLoop(t,n),this.renderer._inspector.finish()};e()}stop(){this._context.cancelAnimationFrame(this._requestId),this._requestId=null}getAnimationLoop(){return this._animationLoop}setAnimationLoop(e){this._animationLoop=e}getContext(){return this._context}setContext(e){this._context=e}dispose(){this.stop()}}class qw{constructor(){this.weakMaps={}}_getWeakMap(e){const t=e.length;let n=this.weakMaps[t];return void 0===n&&(n=new WeakMap,this.weakMaps[t]=n),n}get(e){let t=this._getWeakMap(e);for(let n=0;n{this.dispose()},this.onGeometryDispose=()=>{this.attributes=null,this.attributesId=null},this.material.addEventListener("dispose",this.onMaterialDispose),this.geometry.addEventListener("dispose",this.onGeometryDispose)}updateClipping(e){this.clippingContext=e}get clippingNeedsUpdate(){return null!==this.clippingContext&&this.clippingContext.cacheKey!==this.clippingContextCacheKey&&(this.clippingContextCacheKey=this.clippingContext.cacheKey,!0)}get hardwareClippingPlanes(){return!0===this.material.hardwareClipping?this.clippingContext.unionClippingCount:0}getNodeBuilderState(){return this._nodeBuilderState||(this._nodeBuilderState=this._nodes.getForRender(this))}getMonitor(){return this._monitor||(this._monitor=this.getNodeBuilderState().observer)}getBindings(){return this._bindings||(this._bindings=this.getNodeBuilderState().createBindings())}getBindingGroup(e){for(const t of this.getBindings())if(t.name===e)return t}getIndex(){return this._geometries.getIndex(this)}getIndirect(){return this._geometries.getIndirect(this)}getIndirectOffset(){return this._geometries.getIndirectOffset(this)}getChainArray(){return[this.object,this.material,this.context,this.lightsNode]}setGeometry(e){this.geometry=e,this.attributes=null,this.attributesId=null}getAttributes(){if(null!==this.attributes)return this.attributes;const e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,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;e1||Array.isArray(e.morphTargetInfluences))&&(r+=e.uuid+","),r+=this.context.id+",",r+=e.receiveShadow+",",Cf(r)}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=Pf(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=Pf(e,1)),e=Pf(e,this.camera.id,this.renderer.contextNode.id,this.renderer.contextNode.version),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.geometry.removeEventListener("dispose",this.onGeometryDispose),this.onDispose()}}const Zw=[];class Qw{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);Zw[0]=e,Zw[1]=t,Zw[2]=s,Zw[3]=i;let u=l.get(Zw);return void 0===u?(u=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,n,r,i,s,a,o),l.set(Zw,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)),Zw.length=0,u}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new qw)}dispose(){this.chainMaps={}}createRenderObject(e,t,n,r,i,s,a,o,l,u,c){const h=this.getChainMap(c),d=new Kw(e,t,n,r,i,s,a,o,l,u);return d.onDispose=()=>{this.pipelines.delete(d),this.bindings.deleteForRender(d),this.nodes.delete(d),h.delete(d.getChainArray())},d}}class Jw{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 eE=1,tE=2,nE=3,rE=4,iE=16;class sE extends Jw{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===eE?this.backend.createAttribute(e):t===tE?this.backend.createIndexAttribute(e):t===nE?this.backend.createStorageAttribute(e):t===rE&&this.backend.createIndirectStorageAttribute(e),n.version=this._getBufferAttribute(e).version;else{const t=this._getBufferAttribute(e);(n.version{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),this._geometryDisposeListeners.delete(t)};t.addEventListener("dispose",n),this._geometryDisposeListeners.set(t,n)}updateAttributes(e){const t=e.getAttributes();for(const e of t)e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute?this.updateAttribute(e,nE):this.updateAttribute(e,eE);const n=this.getIndex(e);null!==n&&this.updateAttribute(n,tE);const r=e.geometry.indirect;null!==r&&this.updateAttribute(r,rE)}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}getIndirectOffset(e){return e.geometry.indirectOffset}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=oE(t),e.set(t,n)):n.version!==aE(t)&&(this.attributes.delete(n),n=oE(t),e.set(t,n)),r=n}return r}dispose(){for(const[e,t]of this._geometryDisposeListeners.entries())e.removeEventListener("dispose",t);this._geometryDisposeListeners.clear()}}class uE{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):Jt("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 cE{constructor(e){this.cacheKey=e,this.usedTimes=0}}class hE extends cE{constructor(e,t,n){super(e),this.vertexProgram=t,this.fragmentProgram=n}}class dE extends cE{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let pE=0;class fE{constructor(e,t,n,r=null,i=null){this.id=pE++,this.code=e,this.stage=t,this.name=n,this.transforms=r,this.attributes=i,this.usedTimes=0}}class mE extends Jw{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 fE(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 fE(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 fE(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 dE(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 hE(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 gE extends Jw{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))}deleteForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const e of t)this.backend.deleteBindGroupData(e),this.delete(e)}deleteForRender(e){const t=e.getBindings();for(const e of t)this.backend.deleteBindGroupData(e),this.delete(e)}_updateBindings(e){for(const t of e)this._update(t,e)}_init(e){for(const t of e.bindings)if(t.isSampledTexture)this.textures.updateTexture(t.texture);else if(t.isSampler)this.textures.updateSampler(t.texture);else if(t.isStorageBuffer){const e=t.attribute,n=e.isIndirectStorageBufferAttribute?rE:nE;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(!1!==this.nodes.updateGroup(t)){if(t.isStorageBuffer){const e=t.attribute,n=e.isIndirectStorageBufferAttribute?rE:nE;this.attributes.update(e,n)}if(t.isUniformBuffer){t.update()&&n.updateBinding(t)}else if(t.isSampledTexture){const e=t.update(),o=t.texture,l=this.textures.get(o);e&&(this.textures.updateTexture(o),t.generation!==l.generation&&(t.generation=l.generation,r=!0,i=!1));if(void 0!==n.get(o).externalTexture||l.isDefaultTexture?i=!1:(s=10*s+o.id,a+=o.version),!0===o.isStorageTexture&&!0===o.mipmapsAutoUpdate){const e=this.get(o);!0===t.store?e.needsMipmap=!0:this.textures.needsMipmaps(o)&&!0===e.needsMipmap&&(this.backend.generateMipmaps(o),e.needsMipmap=!1)}}else if(t.isSampler){if(t.update()){const e=this.textures.updateSampler(t.texture);t.samplerKey!==e&&(t.samplerKey=e,r=!0,i=!1)}}}}!0===r&&this.backend.updateBindings(e,t,i?s:0,a)}}function _E(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 vE(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 yE(e){return(e.transmission>0||e.transmissionNode&&e.transmissionNode.isNode)&&2===e.side&&!1===e.forceSinglePass}class bE{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||n.transmissionNode&&n.transmissionNode.isNode||n.backdropNode&&n.backdropNode.isNode?(yE(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||n.transmissionNode&&n.transmissionNode.isNode||n.backdropNode&&n.backdropNode.isNode?(yE(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||_E),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||vE),this.transparent.length>1&&this.transparent.sort(t||vE)}finish(){this.lightsNode.setLights(this.lightsArray);for(let e=this.renderItemsIndex,t=this.renderItems.length;e>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?Fe:Oe,u.type=e.stencilBuffer?Ne:we,u.image.width=o,u.image.height=l,u.image.depth=a.depth,u.renderTarget=e,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{this._destroyRenderTarget(e)},e.addEventListener("dispose",n.onDispose))}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.destroyTexture(e),e.isFramebufferTexture){const t=this.renderer.getRenderTarget();e.type=t?t.texture.type:be}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,e.isCubeTexture&&e.mipmaps.length>0&&t.levels++,r||!0===e.isStorageTexture||!0===e.isExternalTexture)i.createTexture(e,t),n.generation=e.version;else if(e.version>0){const r=e.image;if(void 0===r)Qt("Renderer: Texture marked for update but image is undefined.");else if(!1===r.complete)Qt("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);const s=!0===e.isStorageTexture&&!1===e.mipmapsAutoUpdate;t.needsMipmaps&&0===e.mipmaps.length&&!s&&i.generateMipmaps(e),e.onUpdate&&e.onUpdate(e)}}else i.createDefaultTexture(e),n.isDefaultTexture=!0,n.generation=e.version;!0!==n.initialized&&(n.initialized=!0,n.generation=e.version,this.info.memory.textures++,e.isVideoTexture&&!0===Mn.enabled&&Mn.getTransfer(e.colorSpace)!==Ct&&Qt("WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace."),n.onDispose=()=>{this._destroyTexture(e)},e.addEventListener("dispose",n.onDispose)),n.version=e.version}updateSampler(e){return this.backend.updateSampler(e)}getSize(e,t=NE){let n=e.images?e.images[0]:e.image;return n?(void 0!==n.image&&(n=n.image),"undefined"!=typeof HTMLVideoElement&&n instanceof HTMLVideoElement?(t.width=n.videoWidth||1,t.height=n.videoHeight||1,t.depth=1):"undefined"!=typeof VideoFrame&&n instanceof VideoFrame?(t.width=n.displayWidth||1,t.height=n.displayHeight||1,t.depth=1):(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.mipmaps.length>0?e.mipmaps.length:!0===e.isCompressedTexture?1:Math.floor(Math.log2(Math.max(t,n)))+1,r}needsMipmaps(e){return!0===e.generateMipmaps||e.mipmaps.length>0}_destroyRenderTarget(e){if(!0===this.has(e)){const t=this.get(e),n=t.textures,r=t.depthTexture;e.removeEventListener("dispose",t.onDispose);for(let e=0;e=2)for(let n=0;n{if(this._currentNode=t,!t.isVarNode||!t.isIntent(e)||!0===t.isAssign(e))if("setup"===r)t.build(e);else if("analyze"===r)t.build(e,this);else if("generate"===r){const n=e.getDataFromNode(t,"any").stages,r=n&&n[e.shaderStage];if(t.isVarNode&&r&&1===r.length&&r[0]&&r[0].isStackNode)return;t.build(e,"void")}},s=[...this.nodes];for(const e of s)i(e);this._currentNode=null;const a=this.nodes.filter(e=>-1===s.indexOf(e));for(const e of a)i(e);let o;return o=this.hasOutput?this.outputNode.build(e,...t):super.build(e,...t),Km(n),e.removeActiveStack(this),o}}const UE=jm(IE).setParameterLength(0,1);class OE extends em{static get type(){return"BitcastNode"}constructor(e,t,n=null){super(),this.valueNode=e,this.conversionType=t,this.inputType=n,this.isBitcastNode=!0}getNodeType(e){if(null!==this.inputType){const t=this.valueNode.getNodeType(e),n=e.getTypeLength(t);return e.getTypeFromLength(n,this.conversionType)}return this.conversionType}generate(e){const t=this.getNodeType(e);let n="";if(null!==this.inputType){const t=this.valueNode.getNodeType(e);n=1===e.getTypeLength(t)?this.inputType:e.changeComponentType(t,this.inputType)}else n=this.valueNode.getNodeType(e);return`${e.getBitcastMethod(t,n)}( ${this.valueNode.build(e,n)} )`}}const FE=$m(OE).setParameterLength(2),BE={};class kE extends O_{static get type(){return"BitcountNode"}constructor(e,t){super(e,t),this.isBitcountNode=!0}_resolveElementType(e,t,n){"int"===n?t.assign(FE(e,"uint")):t.assign(e)}_returnDataNode(e){switch(e){case"uint":return rg;case"int":return ng;case"uvec2":return og;case"uvec3":return hg;case"uvec4":return mg;case"ivec2":return ag;case"ivec3":return cg;case"ivec4":return fg}}_createTrailingZerosBaseLayout(e,t){const n=this._returnDataNode(t),r=Ym(([e])=>{const r=rg(0);this._resolveElementType(e,r,t);const i=(e=>new OE(e,"uint","float"))(tg(r.bitAnd(lv(r)))),s=i.shiftRight(23).sub(127);return n(s)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]});return r}_createLeadingZerosBaseLayout(e,t){const n=this._returnDataNode(t),r=Ym(([e])=>{Qm(e.equal(rg(0)),()=>rg(32));const r=rg(0),i=rg(0);return this._resolveElementType(e,r,t),Qm(r.shiftRight(16).equal(0),()=>{i.addAssign(16),r.shiftLeftAssign(16)}),Qm(r.shiftRight(24).equal(0),()=>{i.addAssign(8),r.shiftLeftAssign(8)}),Qm(r.shiftRight(28).equal(0),()=>{i.addAssign(4),r.shiftLeftAssign(4)}),Qm(r.shiftRight(30).equal(0),()=>{i.addAssign(2),r.shiftLeftAssign(2)}),Qm(r.shiftRight(31).equal(0),()=>{i.addAssign(1)}),n(i)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]});return r}_createOneBitsBaseLayout(e,t){const n=this._returnDataNode(t),r=Ym(([e])=>{const r=rg(0);this._resolveElementType(e,r,t),r.assign(r.sub(r.shiftRight(rg(1)).bitAnd(rg(1431655765)))),r.assign(r.bitAnd(rg(858993459)).add(r.shiftRight(rg(2)).bitAnd(rg(858993459))));const i=r.add(r.shiftRight(rg(4))).bitAnd(rg(252645135)).mul(rg(16843009)).shiftRight(rg(24));return n(i)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]});return r}_createMainLayout(e,t,n,r){const i=this._returnDataNode(t),s=Ym(([e])=>{if(1===n)return i(r(e));{const t=i(0),s=["x","y","z","w"];for(let i=0;ic(n))()}}kE.COUNT_TRAILING_ZEROS="countTrailingZeros",kE.COUNT_LEADING_ZEROS="countLeadingZeros",kE.COUNT_ONE_BITS="countOneBits",new _s,new gn,new gn,new gn,new pr,new gn(0,0,-1),new Un,new gn,new gn,new Un,new fn;const zE=new On;Ky.flipX(),zE.depthTexture=new Os(1,1);const VE=new Pa(-1,1,1,-1,0,1);class GE extends Ci{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new xi([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new xi(t,2))}}const HE=new GE;class jE extends Vi{constructor(e=null){super(HE,e),this.camera=VE,this.isQuadMesh=!0}async renderAsync(e){en('QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await e.init(),e.render(this,VE)}render(e){e.render(this,VE)}}const WE=Ym(([e])=>Q_(tg(52.9829189).mul(Q_(wv(e,sg(.06711056,.00583715)))))).setLayout({name:"interleavedGradientNoise",type:"float",inputs:[{name:"position",type:"vec2"}]}),$E=Ym(([e,t,n])=>{const r=tg(2.399963229728653),i=X_(tg(e).add(.5).div(tg(t))),s=tg(e).mul(r).add(n);return sg(ev(s),J_(s)).mul(i)}).setLayout({name:"vogelDiskSample",type:"vec2",inputs:[{name:"sampleIndex",type:"int"},{name:"samplesCount",type:"int"},{name:"phi",type:"float"}]});class XE extends Zf{static get type(){return"EventNode"}constructor(e,t){super("void"),this.eventType=e,this.callback=t,e===XE.OBJECT?this.updateType=Gf:e===XE.MATERIAL?this.updateType=Vf:e===XE.BEFORE_OBJECT?this.updateBeforeType=Gf:e===XE.BEFORE_MATERIAL&&(this.updateBeforeType=Vf)}update(e){this.callback(e)}updateBefore(e){this.callback(e)}}XE.OBJECT="object",XE.MATERIAL="material",XE.BEFORE_OBJECT="beforeObject",XE.BEFORE_MATERIAL="beforeMaterial";const qE=new Sr,YE=new pr;class KE extends Zf{static get type(){return"SceneNode"}constructor(e=KE.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===KE.BACKGROUND_BLURRINESS?r=Qb("backgroundBlurriness","float",n):t===KE.BACKGROUND_INTENSITY?r=Qb("backgroundIntensity","float",n):t===KE.BACKGROUND_ROTATION?r=s_("mat4").setName("backgroundRotation").setGroup(n_).onRenderUpdate(()=>{const e=n.background;return null!==e&&e.isTexture&&300!==e.mapping?(qE.copy(n.backgroundRotation),qE.x*=-1,qE.y*=-1,qE.z*=-1,YE.makeRotationFromEuler(qE)):YE.identity(),YE}):Jt("SceneNode: Unknown scope:",t),r}}KE.BACKGROUND_BLURRINESS="backgroundBlurriness",KE.BACKGROUND_INTENSITY="backgroundIntensity",KE.BACKGROUND_ROTATION="backgroundRotation";const ZE=Wm(KE,KE.BACKGROUND_BLURRINESS),QE=Wm(KE,KE.BACKGROUND_INTENSITY),JE=Wm(KE,KE.BACKGROUND_ROTATION),eA=Ym(({texture:e,uv:t})=>{const n=1e-4,r=ug().toVar();return Qm(t.x.lessThan(n),()=>{r.assign(ug(1,0,0))}).ElseIf(t.y.lessThan(n),()=>{r.assign(ug(0,1,0))}).ElseIf(t.z.lessThan(n),()=>{r.assign(ug(0,0,1))}).ElseIf(t.x.greaterThan(.9999),()=>{r.assign(ug(-1,0,0))}).ElseIf(t.y.greaterThan(.9999),()=>{r.assign(ug(0,-1,0))}).ElseIf(t.z.greaterThan(.9999),()=>{r.assign(ug(0,0,-1))}).Else(()=>{const n=.01,i=e.sample(t.add(ug(-.01,0,0))).r.sub(e.sample(t.add(ug(n,0,0))).r),s=e.sample(t.add(ug(0,-.01,0))).r.sub(e.sample(t.add(ug(0,n,0))).r),a=e.sample(t.add(ug(0,0,-.01))).r.sub(e.sample(t.add(ug(0,0,n))).r);r.assign(ug(i,s,a))}),r.normalize()});class tA extends Oy{static get type(){return"Texture3DNode"}constructor(e,t=null,n=null){super(e,t,n),this.isTexture3DNode=!0}getInputType(){return"texture3D"}getDefaultUV(){return ug(.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(ng(Ly(this,this.levelNode).y).sub(t.y).sub(1))),t}generateUV(e,t){return t.build(e,!0===this.sampler?"vec3":"ivec3")}generateOffset(e,t){return t.build(e,"ivec3")}normal(e){return eA({texture:this,uv:e})}}const nA=jm(tA).setParameterLength(1,3),rA=new fn;class iA extends Oy{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.setUpdateMatrix(!1)}setup(e){return this.passNode.build(e),super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class sA extends iA{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.offsetNode=this.offsetNode,e}}class aA extends em{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:Ae,...r});s.texture.name="output",s.depthTexture=i,this.renderTarget=s,this.overrideMaterial=null,this.transparent=!0,this.opaque=!0,this.contextNode=null,this._contextNodeCache=null,this._textures={output:s.texture,depth:i},this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=s_(0),this._cameraFar=s_(0),this._mrt=null,this._layers=null,this._resolutionScale=1,this._viewport=null,this._scissor=null,this.isPassNode=!0,this.updateBeforeType=zf,this.global=!0}setResolutionScale(e){return this._resolutionScale=e,this}getResolutionScale(){return this._resolutionScale}setResolution(e){return Qt("PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead."),this.setResolutionScale(e)}getResolution(){return Qt("PassNode: .getResolution() is deprecated. Use .getResolutionScale() instead."),this.getResolutionScale()}setLayers(e){return this._layers=e,this}getLayers(){return this._layers}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getTexture(e){let t=this._textures[e];if(void 0===t){t=this.renderTarget.texture.clone(),t.name=e,this._textures[e]=t,this.renderTarget.textures.push(t)}return t}getPreviousTexture(e){let t=this._previousTextures[e];return void 0===t&&(t=this.getTexture(e).clone(),this._previousTextures[e]=t),t}toggleTexture(e){const t=this._previousTextures[e];if(void 0!==t){const 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=new sA(this,e),t.updateTexture(),this._textureNodes[e]=t),t}getPreviousTextureNode(e="output"){let t=this._previousTextureNodes[e];return void 0===t&&(void 0===this._textureNodes[e]&&this.getTextureNode(e),t=new sA(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=ZT(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=YT(i,n,r)}return t}async compileAsync(e){const t=e.getRenderTarget(),n=e.getMRT();e.setRenderTarget(this.renderTarget),e.setMRT(this._mrt),await e.compileAsync(this.scene,this.camera),e.setRenderTarget(t),e.setMRT(n)}setup({renderer:e}){return this.renderTarget.samples=void 0===this.options.samples?e.samples:this.options.samples,this.renderTarget.texture.type=e.getOutputBufferType(),this.scope===aA.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),rA.set(s.width,s.height)):(r=this.camera,i=t.getPixelRatio(),t.getSize(rA)),this._pixelRatio=i,this.setSize(rA.width,rA.height);const a=t.getRenderTarget(),o=t.getMRT(),l=t.autoClear,u=t.transparent,c=t.opaque,h=r.layers.mask,d=t.contextNode,p=n.overrideMaterial;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);null!==this.overrideMaterial&&(n.overrideMaterial=this.overrideMaterial),t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.autoClear=!0,t.transparent=this.transparent,t.opaque=this.opaque,null!==this.contextNode&&(null!==this._contextNodeCache&&this._contextNodeCache.version===this.version||(this._contextNodeCache={version:this.version,context:Gv({...t.contextNode.getFlowContextData(),...this.contextNode.getFlowContextData()})}),t.contextNode=this._contextNodeCache.context);const f=n.name;n.name=this.name?this.name:n.name,t.render(n,r),n.name=f,n.overrideMaterial=p,t.setRenderTarget(a),t.setMRT(o),t.autoClear=l,t.transparent=u,t.opaque=c,t.contextNode=d,r.layers.mask=h}setSize(e,t){this._width=e,this._height=t;const n=Math.floor(this._width*this._pixelRatio*this._resolutionScale),r=Math.floor(this._height*this._pixelRatio*this._resolutionScale);this.renderTarget.setSize(n,r),null!==this._scissor&&this.renderTarget.scissor.copy(this._scissor),null!==this._viewport&&this.renderTarget.viewport.copy(this._viewport)}setScissor(e,t,n,r){null===e?this._scissor=null:(null===this._scissor&&(this._scissor=new Un),e.isVector4?this._scissor.copy(e):this._scissor.set(e,t,n,r),this._scissor.multiplyScalar(this._pixelRatio*this._resolutionScale).floor())}setViewport(e,t,n,r){null===e?this._viewport=null:(null===this._viewport&&(this._viewport=new Un),e.isVector4?this._viewport.copy(e):this._viewport.set(e,t,n,r),this._viewport.multiplyScalar(this._pixelRatio*this._resolutionScale).floor())}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}aA.COLOR="color",aA.DEPTH="depth";const oA=Ym(([e,t])=>e.mul(t).clamp()).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),lA=Ym(([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"}]}),uA=Ym(([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"}]}),cA=Ym(([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)}),hA=Ym(([e,t])=>{const n=vg(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),r=vg(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=n.mul(e),e=cA(e),(e=r.mul(e)).clamp()}).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),dA=vg(ug(1.6605,-.1246,-.0182),ug(-.5876,1.1329,-.1006),ug(-.0728,-.0083,1.1187)),pA=vg(ug(.6274,.0691,.0164),ug(.3293,.9195,.088),ug(.0433,.0113,.8956)),fA=Ym(([e])=>{const t=ug(e).toVar(),n=ug(t.mul(t)).toVar(),r=ug(n.mul(n)).toVar();return tg(15.5).mul(r.mul(n)).sub(p_(40.14,r.mul(t))).add(p_(31.96,r).sub(p_(6.868,n.mul(t))).add(p_(.4298,n).add(p_(.1191,t).sub(.00232))))}),mA=Ym(([e,t])=>{const n=ug(e).toVar(),r=vg(ug(.856627153315983,.137318972929847,.11189821299995),ug(.0951212405381588,.761241990602591,.0767994186031903),ug(.0482516061458583,.101439036467562,.811302368396859)),i=vg(ug(1.1271005818144368,-.1413297634984383,-.14132976349843826),ug(-.11060664309660323,1.157823702216272,-.11060664309660294),ug(-.016493938717834573,-.016493938717834257,1.2519364065950405)),s=tg(-12.47393),a=tg(4.026069);return n.mulAssign(t),n.assign(pA.mul(n)),n.assign(r.mul(n)),n.assign(bv(n,1e-10)),n.assign($_(n)),n.assign(n.sub(s).div(a.sub(s))),n.assign(Dv(n,0,1)),n.assign(fA(n)),n.assign(i.mul(n)),n.assign(Av(bv(ug(0),n),ug(2.2))),n.assign(dA.mul(n)),n.assign(Dv(n,0,1)),n}).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),gA=Ym(([e,t])=>{const n=tg(.76),r=tg(.15);e=e.mul(t);const i=yv(e.r,yv(e.g,e.b)),s=zv(i.lessThan(.08),i.sub(p_(6.25,i.mul(i))),.04);e.subAssign(s);const a=bv(e.r,bv(e.g,e.b));Qm(a.lessThan(n),()=>e);const o=d_(1,n),l=d_(1,o.mul(o).div(a.add(o.sub(n))));e.mulAssign(l.div(a));const u=d_(1,f_(1,r.mul(a.sub(l)).add(1)));return Lv(e,ug(l),u)}).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class _A extends Zf{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 vA extends _A{static get type(){return"FunctionNode"}constructor(e="",t=[],n=""){super(e,t,n)}getNodeType(e){return this.getNodeFunction(e).type}getMemberType(e,t){const n=this.getNodeType(e);return e.getStructTypeNode(n).getMemberType(e,t)}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 yA(e){let t;const n=e.context.getViewZ;return void 0!==n&&(t=n(this)),(t||Tb.z).negate()}const bA=Ym(([e,t],n)=>{const r=yA(n);return Ov(e,t,r)}),xA=Ym(([e],t)=>{const n=yA(t);return e.mul(e,n,n).negate().exp().oneMinus()}),TA=Ym(([e,t])=>pg(t.toFloat().mix(Hg.rgb,e.toVec3()),Hg.a));jm(class extends Zf{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 SA extends Zf{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(!(!!n&&(1===n.length&&!0===n[0].isStackNode)))return void 0===t.constNode&&(t.constNode=Sy(u,i).toConst()),t.constNode.build(e);e.addLineFlowCode(u,this)}}SA.ATOMIC_LOAD="atomicLoad",SA.ATOMIC_STORE="atomicStore",SA.ATOMIC_ADD="atomicAdd",SA.ATOMIC_SUB="atomicSub",SA.ATOMIC_MAX="atomicMax",SA.ATOMIC_MIN="atomicMin",SA.ATOMIC_AND="atomicAnd",SA.ATOMIC_OR="atomicOr",SA.ATOMIC_XOR="atomicXor",jm(SA);class MA extends em{static get type(){return"SubgroupFunctionNode"}constructor(e,t=null,n=null){super(),this.method=e,this.aNode=t,this.bNode=n}getInputType(e){const t=this.aNode?this.aNode.getNodeType(e):null,n=this.bNode?this.bNode.getNodeType(e):null;return(e.isMatrix(t)?0:e.getTypeLength(t))>(e.isMatrix(n)?0:e.getTypeLength(n))?t:n}getNodeType(e){const t=this.method;return t===MA.SUBGROUP_ELECT?"bool":t===MA.SUBGROUP_BALLOT?"uvec4":this.getInputType(e)}generate(e,t){const n=this.method,r=this.getNodeType(e),i=this.getInputType(e),s=this.aNode,a=this.bNode,o=[];if(n===MA.SUBGROUP_BROADCAST||n===MA.SUBGROUP_SHUFFLE||n===MA.QUAD_BROADCAST){const t=a.getNodeType(e);o.push(s.build(e,r),a.build(e,"float"===t?"int":r))}else n===MA.SUBGROUP_SHUFFLE_XOR||n===MA.SUBGROUP_SHUFFLE_DOWN||n===MA.SUBGROUP_SHUFFLE_UP?o.push(s.build(e,r),a.build(e,"uint")):(null!==s&&o.push(s.build(e,i)),null!==a&&o.push(a.build(e,i)));const l=0===o.length?"()":`( ${o.join(", ")} )`;return e.format(`${e.getMethod(n,r)}${l}`,r,t)}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}let wA;function EA(e){wA=wA||new WeakMap;let t=wA.get(e);return void 0===t&&wA.set(e,t={}),t}function AA(e){const t=EA(e);return t.shadowMatrix||(t.shadowMatrix=s_("mat4").setGroup(n_).onRenderUpdate(t=>(!0===e.castShadow&&!1!==t.renderer.shadowMap.enabled||(e.shadow.camera.coordinateSystem!==t.camera.coordinateSystem&&(e.shadow.camera.coordinateSystem=t.camera.coordinateSystem,e.shadow.camera.updateProjectionMatrix()),e.shadow.updateMatrices(e)),e.shadow.matrix)))}function RA(e){const t=EA(e);return t.position||(t.position=s_(new gn).setGroup(n_).onRenderUpdate((t,n)=>n.value.setFromMatrixPosition(e.matrixWorld)))}function CA(e){const t=EA(e);return t.viewPosition||(t.viewPosition=s_(new gn).setGroup(n_).onRenderUpdate(({camera:t},n)=>{n.value=n.value||new gn,n.value.setFromMatrixPosition(e.matrixWorld),n.value.applyMatrix4(t.matrixWorldInverse)}))}MA.SUBGROUP_ELECT="subgroupElect",MA.SUBGROUP_BALLOT="subgroupBallot",MA.SUBGROUP_ADD="subgroupAdd",MA.SUBGROUP_INCLUSIVE_ADD="subgroupInclusiveAdd",MA.SUBGROUP_EXCLUSIVE_AND="subgroupExclusiveAdd",MA.SUBGROUP_MUL="subgroupMul",MA.SUBGROUP_INCLUSIVE_MUL="subgroupInclusiveMul",MA.SUBGROUP_EXCLUSIVE_MUL="subgroupExclusiveMul",MA.SUBGROUP_AND="subgroupAnd",MA.SUBGROUP_OR="subgroupOr",MA.SUBGROUP_XOR="subgroupXor",MA.SUBGROUP_MIN="subgroupMin",MA.SUBGROUP_MAX="subgroupMax",MA.SUBGROUP_ALL="subgroupAll",MA.SUBGROUP_ANY="subgroupAny",MA.SUBGROUP_BROADCAST_FIRST="subgroupBroadcastFirst",MA.QUAD_SWAP_X="quadSwapX",MA.QUAD_SWAP_Y="quadSwapY",MA.QUAD_SWAP_DIAGONAL="quadSwapDiagonal",MA.SUBGROUP_BROADCAST="subgroupBroadcast",MA.SUBGROUP_SHUFFLE="subgroupShuffle",MA.SUBGROUP_SHUFFLE_XOR="subgroupShuffleXor",MA.SUBGROUP_SHUFFLE_UP="subgroupShuffleUp",MA.SUBGROUP_SHUFFLE_DOWN="subgroupShuffleDown",MA.QUAD_BROADCAST="quadBroadcast";const NA=e=>sb.transformDirection(RA(e).sub(function(e){const t=EA(e);return t.targetPosition||(t.targetPosition=s_(new gn).setGroup(n_).onRenderUpdate((t,n)=>n.value.setFromMatrixPosition(e.target.matrixWorld)))}(e))),PA=(e,t)=>{for(const n of t)if(n.isAnalyticLightNode&&n.light.id===e)return n;return null},LA=new WeakMap,DA=[];class IA extends Zf{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=xg("vec3","totalDiffuse"),this.totalSpecularNode=xg("vec3","totalSpecular"),this.outgoingLightNode=xg("vec3","outgoingLight"),this._lights=[],this._lightNodes=null,this._lightNodesHash=null,this.global=!0}customCacheKey(){const e=this._lights;for(let t=0;te.sort((e,t)=>e.id-t.id))(this._lights),i=e.renderer.library;for(const e of r)if(e.isNode)t.push(zm(e));else{let r=null;if(null!==n&&(r=PA(e.id,n)),null===r){const n=i.getLightNodeClass(e.constructor);if(null===n){Qt(`LightsNode.setupNodeLights: Light node not found for ${e.constructor.name}`);continue}let r=null;LA.has(e)?r=LA.get(e):(r=new n(e),LA.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=ug(null!==u?u.mix(f,l):l)),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 UA extends Zf{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=Vf,this.isShadowBaseNode=!0}setupShadowPosition({context:e,material:t}){OA.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||bb)}}const OA=xg("vec3","shadowPositionWorld");function FA(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 si),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 BA=new WeakMap,kA=Ym(({depthTexture:e,shadowCoord:t,depthLayer:n})=>{let r=By(e,t.xy).setName("t_basic");return e.isArrayTexture&&(r=r.depth(n)),r.compare(t.z)}),zA=Ym(({depthTexture:e,shadowCoord:t,shadow:n,depthLayer:r})=>{const i=(t,n)=>{let i=By(e,t);return e.isArrayTexture&&(i=i.depth(r)),i.compare(n)},s=Qb("mapSize","vec2",n).setGroup(n_),a=Qb("radius","float",n).setGroup(n_),o=sg(1).div(s),l=a.mul(o.x),u=WE(Qy.xy).mul(6.28318530718);return h_(i(t.xy.add($E(0,5,u).mul(l)),t.z),i(t.xy.add($E(1,5,u).mul(l)),t.z),i(t.xy.add($E(2,5,u).mul(l)),t.z),i(t.xy.add($E(3,5,u).mul(l)),t.z),i(t.xy.add($E(4,5,u).mul(l)),t.z)).mul(.2)}),VA=Ym(({depthTexture:e,shadowCoord:t,shadow:n,depthLayer:r})=>{const i=(t,n)=>{let i=By(e,t);return e.isArrayTexture&&(i=i.depth(r)),i.compare(n)},s=Qb("mapSize","vec2",n).setGroup(n_),a=sg(1).div(s),o=a.x,l=a.y,u=t.xy,c=Q_(u.mul(s).add(.5));return u.subAssign(c.mul(a)),h_(i(u,t.z),i(u.add(sg(o,0)),t.z),i(u.add(sg(0,l)),t.z),i(u.add(a),t.z),Lv(i(u.add(sg(o.negate(),0)),t.z),i(u.add(sg(o.mul(2),0)),t.z),c.x),Lv(i(u.add(sg(o.negate(),l)),t.z),i(u.add(sg(o.mul(2),l)),t.z),c.x),Lv(i(u.add(sg(0,l.negate())),t.z),i(u.add(sg(0,l.mul(2))),t.z),c.y),Lv(i(u.add(sg(o,l.negate())),t.z),i(u.add(sg(o,l.mul(2))),t.z),c.y),Lv(Lv(i(u.add(sg(o.negate(),l.negate())),t.z),i(u.add(sg(o.mul(2),l.negate())),t.z),c.x),Lv(i(u.add(sg(o.negate(),l.mul(2))),t.z),i(u.add(sg(o.mul(2),l.mul(2))),t.z),c.x),c.y)).mul(1/9)}),GA=Ym(({depthTexture:e,shadowCoord:t,depthLayer:n})=>{let r=By(e).sample(t.xy);e.isArrayTexture&&(r=r.depth(n)),r=r.rg;const i=r.x,s=bv(1e-7,r.y.mul(r.y)),a=xv(t.z,i);Qm(a.equal(1),()=>tg(1));const o=t.z.sub(i);let l=s.div(s.add(o.mul(o)));return l=Dv(d_(l,.3).div(.65)),bv(a,l)}),HA=Ym(([e,t,n])=>{let r=bb.sub(e).length();return r=r.sub(t).div(n.sub(t)),r=r.saturate(),r}),jA=e=>{let t=BA.get(e);if(void 0===t){const n=e.isPointLight?(e=>{const t=e.shadow.camera,n=Qb("near","float",t).setGroup(n_),r=Qb("far","float",t).setGroup(n_),i=ub(e);return HA(i,n,r)})(e):null;t=new oS,t.colorNode=pg(0,0,0,1),t.depthNode=n,t.isShadowPassMaterial=!0,t.name="ShadowMaterial",t.fog=!1,BA.set(e,t)}return t},WA=new qw,$A=[],XA=Ym(({samples:e,radius:t,size:n,shadowPass:r,depthLayer:i})=>{const s=tg(0).toVar("meanVertical"),a=tg(0).toVar("squareMeanVertical"),o=e.lessThanEqual(tg(1)).select(tg(0),tg(2).div(e.sub(1))),l=e.lessThanEqual(tg(1)).select(tg(0),tg(-1));PT({start:ng(0),end:ng(e),type:"int",condition:"<"},({i:e})=>{const u=l.add(tg(e).mul(o));let c=r.sample(h_(Qy.xy,sg(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=X_(a.sub(s.mul(s)).max(0));return sg(s,u)}),qA=Ym(({samples:e,radius:t,size:n,shadowPass:r,depthLayer:i})=>{const s=tg(0).toVar("meanHorizontal"),a=tg(0).toVar("squareMeanHorizontal"),o=e.lessThanEqual(tg(1)).select(tg(0),tg(2).div(e.sub(1))),l=e.lessThanEqual(tg(1)).select(tg(0),tg(-1));PT({start:ng(0),end:ng(e),type:"int",condition:"<"},({i:e})=>{const u=l.add(tg(e).mul(o));let c=r.sample(h_(Qy.xy,sg(u,0).mul(t)).div(n));r.value.isArrayTexture&&(c=c.depth(i)),s.addAssign(c.x),a.addAssign(h_(c.y.mul(c.y),c.x.mul(c.x)))}),s.divAssign(e),a.divAssign(e);const u=X_(a.sub(s.mul(s)).max(0));return sg(s,u)}),YA=[kA,zA,VA,GA];let KA;const ZA=new jE;class QA extends UA{static get type(){return"ShadowNode"}constructor(e,t=null){super(e),this.shadow=t||e.shadow,this.shadowMap=null,this.vsmShadowMapVertical=null,this.vsmShadowMapHorizontal=null,this.vsmMaterialVertical=null,this.vsmMaterialHorizontal=null,this._node=null,this._currentShadowType=null,this._cameraFrameId=new WeakMap,this.isShadowNode=!0,this.depthLayer=0}setupShadowFilter(e,{filterFn:t,depthTexture: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,tg(1))}setupShadowCoord(e,t){const{shadow:n}=this,{renderer:r}=e,i=Qb("bias","float",n).setGroup(n_);let s,a=t;if(n.camera.isOrthographicCamera||!0!==r.logarithmicDepthBuffer)a=a.xyz.div(a.w),s=a.z,r.coordinateSystem===Ht&&(s=s.mul(2).sub(1));else{const e=a.w;a=a.xy.div(e);const t=Qb("near","float",n.camera).setGroup(n_),r=Qb("far","float",n.camera).setGroup(n_);s=QT(e.negate(),t,r)}return a=ug(a.x,a.y.oneMinus(),s.add(i)),a}getShadowFilterFn(e){return YA[e]}setupRenderTarget(e,t){const n=new Os(e.mapSize.width,e.mapSize.height);n.name="ShadowDepthTexture",n.compareFunction=Lt;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,camera:n}=e,{light:r,shadow:i}=this,s=t.shadowMap.type,{depthTexture:a,shadowMap:o}=this.setupRenderTarget(i,e);if(i.camera.coordinateSystem=n.coordinateSystem,i.camera.updateProjectionMatrix(),3===s&&!0!==i.isPointLightShadow){a.compareFunction=null,o.depth>1?(o._vsmShadowMapVertical||(o._vsmShadowMapVertical=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:ze,type:Ae,depth:o.depth,depthBuffer:!1}),o._vsmShadowMapVertical.texture.name="VSMVertical"),this.vsmShadowMapVertical=o._vsmShadowMapVertical,o._vsmShadowMapHorizontal||(o._vsmShadowMapHorizontal=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:ze,type:Ae,depth:o.depth,depthBuffer:!1}),o._vsmShadowMapHorizontal.texture.name="VSMHorizontal"),this.vsmShadowMapHorizontal=o._vsmShadowMapHorizontal):(this.vsmShadowMapVertical=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:ze,type:Ae,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(i.mapSize.width,i.mapSize.height,{format:ze,type:Ae,depthBuffer:!1}));let t=By(a);a.isArrayTexture&&(t=t.depth(this.depthLayer));let n=By(this.vsmShadowMapVertical.texture);a.isArrayTexture&&(n=n.depth(this.depthLayer));const r=Qb("blurSamples","float",i).setGroup(n_),s=Qb("radius","float",i).setGroup(n_),l=Qb("mapSize","vec2",i).setGroup(n_);let u=this.vsmMaterialVertical||(this.vsmMaterialVertical=new oS);u.fragmentNode=XA({samples:r,radius:s,size:l,shadowPass:t,depthLayer:this.depthLayer}).context(e.getSharedContext()),u.name="VSMVertical",u=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new oS),u.fragmentNode=qA({samples:r,radius:s,size:l,shadowPass:n,depthLayer:this.depthLayer}).context(e.getSharedContext()),u.name="VSMHorizontal"}const l=Qb("intensity","float",i).setGroup(n_),u=Qb("normalBias","float",i).setGroup(n_),c=AA(r).mul(OA.add(Db.mul(u))),h=this.setupShadowCoord(e,c),d=i.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(null===d)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const p=3===s&&!0!==i.isPointLightShadow?this.vsmShadowMapHorizontal.texture:a,f=this.setupShadowFilter(e,{filterFn:d,shadowTexture:o.texture,depthTexture:p,shadowCoord:h,shadow:i,depthLayer:this.depthLayer});let m;o.texture.isCubeTexture?m=Yb(o.texture,h.xyz):(m=By(o.texture,h),a.isArrayTexture&&(m=m.depth(this.depthLayer)));const g=Lv(1,f.rgb.mix(m,1),l.mul(m.a)).toVar();this.shadowMap=o,this.shadow.map=o;const _=`${this.light.type} Shadow [ ${this.light.name||"ID: "+this.light.id} ]`;return g.toInspector(`${_} / Color`,()=>this.shadowMap.texture.isCubeTexture?Yb(this.shadowMap.texture):By(this.shadowMap.texture)).toInspector(`${_} / Depth`,()=>this.shadowMap.texture.isCubeTexture?Yb(this.shadowMap.texture).r.oneMinus():ky(this.shadowMap.depthTexture,Ny().mul(Ly(By(this.shadowMap.depthTexture)))).r.oneMinus())}setup(e){if(!1!==e.renderer.shadowMap.enabled)return Ym(()=>{const t=e.renderer.shadowMap.type;this._currentShadowType!==t&&(this._reset(),this._node=null);let n=this._node;return this.setupShadowPosition(e),null===n&&(this._node=n=this.setupShadow(e),this._currentShadowType=t),e.material.shadowNode&&Qt('NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.'),e.material.receivedShadowNode&&(n=e.material.receivedShadowNode(n)),n})()}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);const a=s.name;s.name=`Shadow Map [ ${r.name||"ID: "+r.id} ]`,i.render(s,t.camera),s.name=a}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");KA=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=FA(e,n)),n}(i,s,KA),s.overrideMaterial=jA(n),i.setRenderObjectFunction(((e,t,n,r)=>{$A[0]=e,$A[1]=t;let i=WA.get($A);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&&(Ff(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,WA.set($A,i)),$A[0]=null,$A[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,KA)}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),ZA.material=this.vsmMaterialVertical,ZA.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),ZA.material=this.vsmMaterialHorizontal,ZA.render(e)}dispose(){this._reset(),super.dispose()}_reset(){this._currentShadowType=null,(e=>{const t=BA.get(e);void 0!==t&&(t.dispose(),BA.delete(e))})(this.light),this.shadowMap&&(this.shadowMap.dispose(),this.shadowMap=null),null!==this.vsmShadowMapVertical&&(this.vsmShadowMapVertical.dispose(),this.vsmShadowMapVertical=null,this.vsmMaterialVertical.dispose(),this.vsmMaterialVertical=null),null!==this.vsmShadowMapHorizontal&&(this.vsmShadowMapHorizontal.dispose(),this.vsmShadowMapHorizontal=null,this.vsmMaterialHorizontal.dispose(),this.vsmMaterialHorizontal=null)}updateBefore(e){const{shadow:t}=this;let 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 JA=new si,eR=new pr,tR=new gn,nR=new gn,rR=[new gn(1,0,0),new gn(-1,0,0),new gn(0,-1,0),new gn(0,1,0),new gn(0,0,1),new gn(0,0,-1)],iR=[new gn(0,-1,0),new gn(0,-1,0),new gn(0,0,-1),new gn(0,0,1),new gn(0,-1,0),new gn(0,-1,0)],sR=[new gn(1,0,0),new gn(-1,0,0),new gn(0,1,0),new gn(0,-1,0),new gn(0,0,1),new gn(0,0,-1)],aR=[new gn(0,-1,0),new gn(0,-1,0),new gn(0,0,1),new gn(0,0,-1),new gn(0,-1,0),new gn(0,-1,0)],oR=Ym(({depthTexture:e,bd3D:t,dp:n})=>Yb(e,t).compare(n)),lR=Ym(({depthTexture:e,bd3D:t,dp:n,shadow:r})=>{const i=Qb("radius","float",r).setGroup(n_),s=Qb("mapSize","vec2",r).setGroup(n_),a=i.div(s.x),o=sv(t),l=Z_(Ev(t,o.x.greaterThan(o.z).select(ug(0,1,0),ug(1,0,0)))),u=Ev(t,l),c=WE(Qy.xy).mul(6.28318530718),h=$E(0,5,c),d=$E(1,5,c),p=$E(2,5,c),f=$E(3,5,c),m=$E(4,5,c);return Yb(e,t.add(l.mul(h.x).add(u.mul(h.y)).mul(a))).compare(n).add(Yb(e,t.add(l.mul(d.x).add(u.mul(d.y)).mul(a))).compare(n)).add(Yb(e,t.add(l.mul(p.x).add(u.mul(p.y)).mul(a))).compare(n)).add(Yb(e,t.add(l.mul(f.x).add(u.mul(f.y)).mul(a))).compare(n)).add(Yb(e,t.add(l.mul(m.x).add(u.mul(m.y)).mul(a))).compare(n)).mul(.2)}),uR=Ym(({filterFn:e,depthTexture:t,shadowCoord:n,shadow:r})=>{const i=n.xyz.toVar(),s=i.length(),a=s_("float").setGroup(n_).onRenderUpdate(()=>r.camera.near),o=s_("float").setGroup(n_).onRenderUpdate(()=>r.camera.far),l=Qb("bias","float",r).setGroup(n_),u=tg(1).toVar();return Qm(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 c=i.normalize();u.assign(e({depthTexture:t,bd3D:c,dp:n,shadow:r}))}),u});class cR extends QA{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return 0===e?oR:lR}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,depthTexture:n,shadowCoord:r,shadow:i}){return uR({filterFn:t,depthTexture:n,shadowCoord:r,shadow:i})}setupRenderTarget(e,t){const n=new Fs(e.mapSize.width);n.name="PointShadowDepthTexture",n.compareFunction=Lt;const r=t.createCubeRenderTarget(e.mapSize.width);return r.texture.name="PointShadowMap",r.depthTexture=n,{shadowMap:r,depthTexture:n}}renderShadow(e){const{shadow:t,shadowMap:n,light:r}=this,{renderer:i,scene:s}=e,a=t.camera,o=t.matrix,l=i.coordinateSystem===Ht,u=l?rR:sR,c=l?iR:aR;n.setSize(t.mapSize.width,t.mapSize.width);const h=i.autoClear,d=i.getClearColor(JA),p=i.getClearAlpha();i.autoClear=!1,i.setClearColor(t.clearColor,t.clearAlpha);for(let e=0;e<6;e++){i.setRenderTarget(n,e),i.clear();const l=r.distance||a.far;l!==a.far&&(a.far=l,a.updateProjectionMatrix()),tR.setFromMatrixPosition(r.matrixWorld),a.position.copy(tR),nR.copy(a.position),nR.add(u[e]),a.up.copy(c[e]),a.lookAt(nR),a.updateMatrixWorld(),o.makeTranslation(-tR.x,-tR.y,-tR.z),eR.multiplyMatrices(a.projectionMatrix,a.matrixWorldInverse),t._frustum.setFromProjectionMatrix(eR,a.coordinateSystem,a.reversedDepth);const h=s.name;s.name=`Point Light Shadow [ ${r.name||"ID: "+r.id} ] - Face ${e+1}`,i.render(s,a),s.name=h}i.autoClear=h,i.setClearColor(d,p)}}class hR extends FT{static get type(){return"AnalyticLightNode"}constructor(e=null){super(),this.light=e,this.color=new si,this.colorNode=e&&e.colorNode||s_(this.color).setGroup(n_),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=zf,e&&e.shadow&&(this._shadowDisposeListener=()=>{this.disposeShadow()},e.addEventListener("dispose",this._shadowDisposeListener))}dispose(){this._shadowDisposeListener&&this.light.removeEventListener("dispose",this._shadowDisposeListener),super.dispose()}disposeShadow(){null!==this.shadowNode&&(this.shadowNode.dispose(),this.shadowNode=null),this.shadowColorNode=null,null!==this.baseColorNode&&(this.colorNode=this.baseColorNode,this.baseColorNode=null)}getHash(){return this.light.uuid}getLightVector(e){return CA(this.light).sub(e.context.positionView||Tb)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return((e,t)=>new QA(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?zm(e):this.setupShadowNode(),this.shadowNode=t,this.shadowColorNode=n=this.colorNode.mul(t),this.baseColorNode=this.colorNode}e.context.getShadow&&(n=e.context.getShadow(this,e)),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 dR=Ym(({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 pR extends hR{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=s_(0).setGroup(n_),this.decayExponentNode=s_(2).setGroup(n_)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return((e,t)=>new cR(e,t))(this.light)}setupDirect(e){return(({color:e,lightVector:t,cutoffDistance:n,decayExponent:r})=>{const i=t.normalize(),s=t.length(),a=dR({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})}}Ym(([e=Ny()],{renderer:t,material:n})=>{const r=Pv(e.mul(2).sub(1));let i;if(n.alphaToCoverage&&t.currentSamples>0){const e=tg(r.fwidth()).toVar();i=Ov(e.oneMinus(),e.add(1),r).oneMinus()}else i=zv(r.greaterThan(1),0,1);return i});const fR=Ym(([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(p_(n,n).sub(p_(r,r)))),s}),mR=new LE;class gR extends Jw{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(mR),mR.a=r._clearColor.a;else if(!0===i.isColor)i.getRGB(mR),mR.a=1,s=!0;else if(!0===i.isNode){const o=this.get(e),l=i;mR.copy(r._clearColor);let u=o.backgroundMesh;if(void 0===u){const h=pg(l).mul(QE).context({getUV:()=>JE.mul(Pb),getTextureLevel:()=>ZE}),d=ib.element(3).element(3).equal(1),p=f_(1,ib.element(1).element(1)).mul(3),f=d.select(vb.mul(p),vb);let m=ib.mul(pb.mul(pg(f,0)));m=m.setZ(m.w);const g=new oS;function _(){i.removeEventListener("dispose",_),u.material.dispose(),u.geometry.dispose()}g.name="Background.material",g.side=1,g.depthTest=!1,g.depthWrite=!1,g.allowOverride=!1,g.fog=!1,g.lights=!1,g.vertexNode=m,g.colorNode=h,o.backgroundMeshNode=h,o.backgroundMesh=u=new Vi(new ta(1,32,32),g),u.frustumCulled=!1,u.name="Background.mesh",i.addEventListener("dispose",_)}const c=l.getCacheKey();o.backgroundCacheKey!==c&&(o.backgroundMeshNode.node=pg(l).mul(QE),o.backgroundMeshNode.needsUpdate=!0,u.material.needsUpdate=!0,o.backgroundCacheKey=c),t.unshift(u,u.geometry,u.material,0,0,null,null)}else Jt("Renderer: Unsupported background configuration.",i);const a=r.xr.getEnvironmentBlendMode();if("additive"===a?mR.set(0,0,0,1):"alpha-blend"===a&&mR.set(0,0,0,0),!0===r.autoClear||!0===s){const v=n.clearColorValue;v.r=mR.r,v.g=mR.g,v.b=mR.b,v.a=mR.a,!0!==r.backend.isWebGLBackend&&!0!==r.alpha||(v.r*=v.a,v.g*=v.a,v.b*=v.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 _R=0;class vR{constructor(e="",t=[],n=0,r=[]){this.name=e,this.bindings=t,this.index=n,this.bindingsReference=r,this.id=_R++}}class yR{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 vR(t.name,[],t.index,t.bindingsReference);e.push(n);for(const e of t.bindings)n.bindings.push(e.clone())}else e.push(t)}return e}}class bR{constructor(e,t,n=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=n}}class xR{constructor(e,t,n){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=n}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 TR{constructor(e,t,n=!1,r=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=n,this.count=r}}class SR extends TR{constructor(e,t,n=null,r=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=n,this.interpolationSampling=r}}class MR{constructor(e,t,n=""){this.name=e,this.type=t,this.code=n,Object.defineProperty(this,"isNodeCode",{value:!0})}}let wR=0;class ER{constructor(e=null){this.id=wR++,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 AR{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class RR{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 CR extends RR{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class NR extends RR{constructor(e,t=new fn){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class PR extends RR{constructor(e,t=new gn){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class LR extends RR{constructor(e,t=new Un){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class DR extends RR{constructor(e,t=new si){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class IR extends RR{constructor(e,t=new $a){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}}class UR extends RR{constructor(e,t=new yn){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class OR extends RR{constructor(e,t=new pr){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class FR extends CR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class BR extends NR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class kR extends PR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class zR extends LR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class VR extends DR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class GR extends IR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class HR extends UR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class jR extends OR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}let WR=0;const $R=new WeakMap,XR=new WeakMap,qR=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),YR=e=>/e/g.test(e)?String(e).replace(/\+/g,""):(e=Number(e))+(e%1?"":".0");class KR{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.types={vertex:[],fragment:[],compute:[],index:0},this.bindings={vertex:{},fragment:{},compute:{}},this.bindingsIndexes={},this.bindGroups=null,this.attributes=[],this.bufferAttributes=[],this.varyings=[],this.codes={},this.vars={},this.declarations={},this.flow={code:""},this.chaining=[],this.stack=UE(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new ER,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null,this.subBuildLayers=[],this.activeStacks=[],this.subBuildFn=null,this.fnCall=null,Object.defineProperty(this,"id",{value:WR++})}isOpaque(){const e=this.material;return!1===e.transparent&&1===e.blending&&!1===e.alphaToCoverage}getBindGroupsCache(){let e=XR.get(this.renderer);return void 0===e&&(e=new qw,XR.set(this.renderer,e)),e}createRenderTarget(e,t,n){return new On(e,t,n)}createCubeRenderTarget(e,t){return new mS(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 vR(e,r,this.bindingsIndexes[e].group,r),n.set(r,i))):i=new vR(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 Xf)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=0?`${Math.round(t)}u`:"0u";if("bool"===e)return t?"true":"false";if("color"===e)return`${this.getType("vec3")}( ${YR(t.r)}, ${YR(t.g)}, ${YR(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 bR(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===Me)return"int";if(t===we)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=If(e);const r="float"===t?"":t[0];return!0===/mat2/.test(t)&&(n=n.replace("vec","mat")),r+n}getTypeFromArray(e){return qR.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 bi||!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")}setActiveStack(e){this.activeStacks.push(e)}removeActiveStack(e){if(this.activeStacks[this.activeStacks.length-1]!==e)throw new Error("NodeBuilder: Invalid active stack removal.");this.activeStacks.pop()}getActiveStack(){return this.activeStacks[this.activeStacks.length-1]}getBaseStack(){return this.activeStacks[0]}addStack(){this.stack=UE(this.stack);const e=Zm();return this.stacks.push(e),Km(this.stack),this.stack}removeStack(){const e=this.stack;for(const t of e.nodes){this.getDataFromNode(t).stack=e}return this.stack=e.parent,Km(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,"vertex");let r=n.bufferAttribute;if(void 0===r){const i=this.uniforms.index++;r=new bR("nodeAttribute"+i,t,e),this.bufferAttributes.push(r),n.bufferAttribute=r}return r}getStructTypeNode(e,t=this.shaderStage){return this.types[t][e]||null}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 a=this.structs.index++;null===n&&(n="StructType"+a),s=new AR(n,t),this.structs[r].push(s),this.types[r][n]=e,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 xR(r||"nodeUniform"+a,t,e),this.uniforms[n].push(s),this.registerDeclaration(s),i.uniform=s}return s}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=e.getArrayCount(this);o=new TR(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 SR(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,Qt(`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 MR("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 vA,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 DE(e.type,e.name);e.layout=null;const r=e.call(n),i=this.flowStagesNode(r,t.type);return e.layout=t,i}flowBuildStage(e,t,n=null){const r=this.getBuildStage();this.setBuildStage(t);const i=e.build(this,n);return this.setBuildStage(r),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 ER,this.stack=UE();for(const n of $f)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(){Qt("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(){Qt("Abstract function.")}getVaryings(){Qt("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(){Qt("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(){Qt("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&&(Jt(`NodeMaterial: Material "${t.type}" is not compatible.`),e=new oS),e.build(this)}else this.addFlow("compute",e);for(const e of $f){this.setBuildStage(e),this.context.vertex&&this.context.vertex.isNode&&this.flowNodeFromShaderStage("vertex",this.context.vertex);for(const t of Xf){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}getSharedDataFromNode(e){let t=$R.get(e);return void 0===t&&(t={}),t}getNodeUniform(e,t){const n=this.getSharedDataFromNode(e);let r=n.cache;if(void 0===r){if("float"===t||"int"===t||"uint"===t)r=new FR(e);else if("vec2"===t||"ivec2"===t||"uvec2"===t)r=new BR(e);else if("vec3"===t||"ivec3"===t||"uvec3"===t)r=new kR(e);else if("vec4"===t||"ivec4"===t||"uvec4"===t)r=new zR(e);else if("color"===t)r=new VR(e);else if("mat2"===t)r=new GR(e);else if("mat3"===t)r=new HR(e);else{if("mat4"!==t)throw new Error(`Uniform "${t}" not implemented.`);r=new jR(e)}n.cache=r}return r}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${h} - Node System\n`}}class ZR{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={renderId:0,frameId:0},e.set(t,n)),n}updateBeforeNode(e){const t=e.getUpdateBeforeType(),n=e.updateReference(this);if(t===zf){const t=this._getMaps(this.updateBeforeMap,n);if(t.frameId!==this.frameId){const n=t.frameId;t.frameId=this.frameId,!1===e.updateBefore(this)&&(t.frameId=n)}}else if(t===Vf){const t=this._getMaps(this.updateBeforeMap,n);if(t.renderId!==this.renderId){const n=t.renderId;t.renderId=this.renderId,!1===e.updateBefore(this)&&(t.renderId=n)}}else t===Gf&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),n=e.updateReference(this);if(t===zf){const t=this._getMaps(this.updateAfterMap,n);t.frameId!==this.frameId&&!1!==e.updateAfter(this)&&(t.frameId=this.frameId)}else if(t===Vf){const t=this._getMaps(this.updateAfterMap,n);t.renderId!==this.renderId&&!1!==e.updateAfter(this)&&(t.renderId=this.renderId)}else t===Gf&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),n=e.updateReference(this);if(t===zf){const t=this._getMaps(this.updateMap,n);t.frameId!==this.frameId&&!1!==e.update(this)&&(t.frameId=this.frameId)}else if(t===Vf){const t=this._getMaps(this.updateMap,n);t.renderId!==this.renderId&&!1!==e.update(this)&&(t.renderId=this.renderId)}else t===Gf&&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 QR{constructor(e,t,n=null,r="",i=!1){this.type=e,this.name=t,this.count=n,this.qualifier=r,this.isConst=i}}QR.isNodeFunctionInput=!0;class JR extends hR{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:NA(this.light),lightColor:e}}}const eC=new pr,tC=new pr;let nC=null;class rC extends hR{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=s_(new gn).setGroup(n_),this.halfWidth=s_(new gn).setGroup(n_),this.updateType=Vf}update(e){super.update(e);const{light:t}=this,n=e.camera.matrixWorldInverse;tC.identity(),eC.copy(t.matrixWorld),eC.premultiply(n),tC.extractRotation(eC),this.halfWidth.value.set(.5*t.width,0,0),this.halfHeight.value.set(0,.5*t.height,0),this.halfWidth.value.applyMatrix4(tC),this.halfHeight.value.applyMatrix4(tC)}setupDirectRectArea(e){let t,n;e.isAvailable("float32Filterable")?(t=By(nC.LTC_FLOAT_1),n=By(nC.LTC_FLOAT_2)):(t=By(nC.LTC_HALF_1),n=By(nC.LTC_HALF_2));const{colorNode:r,light:i}=this;return{lightColor:r,lightPosition:CA(i),halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:n}}static setLTC(e){nC=e}}class iC extends hR{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=s_(0).setGroup(n_),this.penumbraCosNode=s_(0).setGroup(n_),this.cutoffDistanceNode=s_(0).setGroup(n_),this.decayExponentNode=s_(0).setGroup(n_),this.colorNode=s_(this.color).setGroup(n_)}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 Ov(n,r,t)}getLightCoord(e){const t=e.getNodeProperties(this);let n=t.projectionUV;return void 0===n&&(n=function(e,t=bb){const n=AA(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(NA(i)),l=this.getSpotAttenuation(e,o),u=s.length(),c=dR({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=By(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 sC extends iC{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=By(n,sg(e,0),0).r}else r=super.getSpotAttenuation(t);return r}}const aC=Ym(([e,t])=>{const n=e.abs().sub(t);return ov(bv(n,0)).add(yv(bv(n.x,n.y),0))});class oC extends iC{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=tg(0),n=this.penumbraCosNode,r=AA(this.light).mul(e.context.positionWorld||bb);return Qm(r.w.greaterThan(0),()=>{const e=r.xyz.div(r.w),i=aC(e.xy.sub(sg(.5)),sg(.5)),s=f_(-1,d_(1,rv(n)).sub(1));t.assign(Iv(i.mul(-2).mul(s)))}),t}}class lC extends hR{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class uC extends hR{static get type(){return"HemisphereLightNode"}constructor(e=null){super(e),this.lightPositionNode=RA(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=s_(new si).setGroup(n_)}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=Db.dot(r).mul(.5).add(.5),s=Lv(n,t,i);e.context.irradiance.addAssign(s)}}class cC extends hR{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let e=0;e<9;e++)t.push(new gn);this.lightProbe=jy(t)}update(e){const{light:t}=this;super.update(e);for(let e=0;e<9;e++)this.lightProbe.array[e].copy(t.sh.coefficients[e]).multiplyScalar(t.intensity)}setup(e){const t=fR(Db,this.lightProbe);e.context.irradiance.addAssign(t)}}class hC{parseFunction(){Qt("Abstract function.")}}class dC{constructor(e,t,n="",r=""){this.type=e,this.inputs=t,this.name=n,this.precision=r}getCode(){Qt("Abstract function.")}}dC.isNodeFunction=!0;const pC=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,fC=/[a-z_0-9]+/gi,mC="#pragma main";class gC extends dC{constructor(e){const{type:t,inputs:n,name:r,precision:i,inputsCode:s,blockCode:a,headerCode:o}=(e=>{const t=(e=e.trim()).indexOf(mC),n=-1!==t?e.slice(t+12):e,r=n.match(pC);if(null!==r&&5===r.length){const i=r[4],s=[];let a=null;for(;null!==(a=fC.exec(i));)s.push(a);const o=[];let l=0;for(;l{const n=this.backend.createNodeBuilder(e.object,this.renderer);return n.scene=e.scene,n.material=t,n.camera=e.camera,n.context.material=t,n.lightsNode=e.lightsNode,n.environmentNode=this.getEnvironmentNode(e.scene),n.fogNode=this.getFogNode(e.scene),n.clippingContext=e.clippingContext,this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview&&n.enableMultiview(),n};let s=t(e.material);try{s.build()}catch(e){s=t(new oS),s.build(),Jt("TSL: "+e)}n=this._createNodeBuilderState(s),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 yR(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){yC[0]=e,yC[1]=t;const n=this.renderer.info.calls,r=this.callHashCache.get(yC)||{};if(r.callId!==n){const i=this.getEnvironmentNode(e),s=this.getFogNode(e);t&&bC.push(t.getCacheKey(!0)),i&&bC.push(i.getCacheKey()),s&&bC.push(s.getCacheKey()),bC.push(this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview?1:0),bC.push(this.renderer.shadowMap.enabled?1:0),bC.push(this.renderer.shadowMap.type),r.callId=n,r.cacheKey=Nf(bC),this.callHashCache.set(yC,r),bC.length=0}return yC.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===le||n.mapping===ue||n.mapping===ce){if(e.backgroundBlurriness>0||n.mapping===ce)return bw(n);{let e;return e=!0===n.isCubeTexture?Yb(n):By(n),bS(e)}}if(!0===n.isTexture)return By(n,Ky.flipY()).setUpdateMatrix(!0);!0!==n.isColor&&Jt("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=Qb("color","color",n).setGroup(n_),t=Qb("density","float",n).setGroup(n_);return TA(e,xA(t))}if(n.isFog){const e=Qb("color","color",n).setGroup(n_),t=Qb("near","float",n).setGroup(n_),r=Qb("far","float",n).setGroup(n_);return TA(e,bA(t,r))}Jt("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?Yb(n):!0===n.isTexture?By(n):void Jt("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 vC.get(e)!==this.getOutputCacheKey()}getOutputNode(e){const t=this.renderer,n=this.getOutputCacheKey(),r=e.isArrayTexture?nA(e,ug(Ky,Wy("gl_ViewID_OVR"))).renderOutput(t.toneMapping,t.currentColorSpace):By(e,Ky).renderOutput(t.toneMapping,t.currentColorSpace);return vC.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 ZR,this.nodeBuilderCache=new Map,this.cacheLib={}}}const TC=new _s;class SC{constructor(e=null){this.version=0,this.clipIntersection=null,this.cacheKey="",this.shadowPass=!1,this.viewNormalMatrix=new yn,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;i0,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 PC(i.framebufferWidth,i.framebufferHeight,{format:Ue,type:be,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),i.layers.mask=6|e.layers.mask,s.layers.mask=3&i.layers.mask,a.layers.mask=5&i.layers.mask;const o=e.parent,l=i.cameras;UC(i,o);for(let e=0;e=0&&(n[s]=null,t[s].disconnect(i))}for(let r=0;r=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 kC(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 zC(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{await this.compileAsync(e,t);const r=this._renderLists.get(e,t),i=this._renderContexts.get(e,t,this._renderTarget,this._mrt),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(){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 xC(this,n),this._animation=new Xw(this,this._nodes,this.info),this._attributes=new sE(n),this._background=new gR(this,this._nodes),this._geometries=new lE(this._attributes,this.info),this._textures=new PE(this,n,this.info),this._pipelines=new mE(n,this._nodes),this._bindings=new gE(n,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new Qw(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new TE(this.lighting),this._bundles=new EC,this._renderContexts=new CE,this._animation.start(),this._initialized=!0,this._inspector.init(),e(this)})),this._initPromise}get domElement(){return this._canvasTarget.domElement}get coordinateSystem(){return this.backend.coordinateSystem}async compileAsync(e,t,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:GC;null===n&&(n=e);const u=this._renderTarget,c=this._renderContexts.get(n,t,u,this._mrt),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 SC),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){en('Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.render(e,t)}async waitForGPU(){Jt("Renderer: waitForGPU() has been removed. Read https://github.com/mrdoob/three.js/issues/32012 for more information.")}set inspector(e){null!==this._inspector&&this._inspector.setRenderer(null),this._inspector=e,this._inspector.setRenderer(this)}get inspector(){return this._inspector}set highPrecision(e){const t=this.contextNode.value;!0===e?(t.modelViewMatrix=mb,t.modelNormalViewMatrix=gb):this.highPrecision&&(delete t.modelViewMatrix,delete t.modelNormalViewMatrix)}get highPrecision(){const e=this.contextNode.value;return e.modelViewMatrix===mb&&e.modelNormalViewMatrix===gb}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getOutputBufferType(){return this._outputBufferType}getColorBufferType(){return en('Renderer: ".getColorBufferType()" has been renamed to ".getOutputBufferType()".'),this.getOutputBufferType()}_onDeviceLost(e){let t=`THREE.WebGPURenderer: ${e.api} Device Lost:\n\nMessage: ${e.message}`;e.reason&&(t+=`\nReason: ${e.reason}`),Jt(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>=h,p.viewportValue.height>>=h,p.viewportValue.minDepth=b,p.viewportValue.maxDepth=x,p.viewport=!1===p.viewportValue.equals(jC),p.scissorValue.copy(v).multiplyScalar(y).floor(),p.scissor=g._scissorTest&&!1===p.scissorValue.equals(jC),p.scissorValue.width>>=h,p.scissorValue.height>>=h,p.clippingContext||(p.clippingContext=new SC),p.clippingContext.updateGlobal(l,t),l.onBeforeRender(this,e,t,d);const T=t.isArrayCamera?$C:WC;t.isArrayCamera||(XC.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),T.setFromProjectionMatrix(XC,t.coordinateSystem,t.reversedDepth));const S=this._renderLists.get(e,t);if(S.begin(),this._projectObject(e,t,0,S,p.clippingContext),S.finish(),!0===this.sortObjects&&S.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=HC.width,p.height=HC.height,p.depth=this.depth,p.stencil=this.stencil;p.width>>=h,p.height>>=h,p.activeCubeFace=c,p.activeMipmapLevel=h,p.occlusionQueryCount=S.occlusionQueryCount,p.scissorValue.max(qC.set(0,0,0,0)),p.scissorValue.x+p.scissorValue.width>p.width&&(p.scissorValue.width=Math.max(p.width-p.scissorValue.x,0)),p.scissorValue.y+p.scissorValue.height>p.height&&(p.scissorValue.height=Math.max(p.height-p.scissorValue.y,0)),this._background.update(l,S,p),p.camera=t,this.backend.beginRender(p);const{bundles:M,lightsNode:w,transparentDoublePass:E,transparent:A,opaque:R}=S;return M.length>0&&this._renderBundles(M,l,w),!0===this.opaque&&R.length>0&&this._renderObjects(R,t,l,w),!0===this.transparent&&A.length>0&&this._renderTransparents(A,E,t,l,w),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),this.inspector.finishRender(this.backend.getTimestampUID(p)),p}_setXRLayerSize(e,t){this._canvasTarget._width=e,this._canvasTarget._height=t,this.setViewport(0,0,e,t)}_renderOutput(e){const t=this._quad;this._nodes.hasOutputChange(e.texture)&&(t.material.fragmentNode=this._nodes.getOutputNode(e.texture),t.material.needsUpdate=!0);const 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)}getAnimationLoop(){return this._animation.getAnimationLoop()}async getArrayBufferAsync(e){return await this.backend.getArrayBufferAsync(e)}getContext(){return this.backend.getContext()}getPixelRatio(){return this._canvasTarget.getPixelRatio()}getDrawingBufferSize(e){return this._canvasTarget.getDrawingBufferSize(e)}getSize(e){return this._canvasTarget.getSize(e)}setPixelRatio(e=1){this._canvasTarget.setPixelRatio(e)}setDrawingBufferSize(e,t,n){this.xr&&this.xr.isPresenting||this._canvasTarget.setDrawingBufferSize(e,t,n)}setSize(e,t,n=!0){this.xr&&this.xr.isPresenting||this._canvasTarget.setSize(e,t,n)}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}getScissor(e){return this._canvasTarget.getScissor(e)}setScissor(e,t,n,r){this._canvasTarget.setScissor(e,t,n,r)}getScissorTest(){return this._canvasTarget.getScissorTest()}setScissorTest(e){this._canvasTarget.setScissorTest(e),this.backend.setScissorTest(e)}getViewport(e){return this._canvasTarget.getViewport(e)}setViewport(e,t,n,r,i=0,s=1){this._canvasTarget.setViewport(e,t,n,r,i,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)throw new Error('Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before before using this method.');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(){this.clear(!0,!1,!1)}clearDepth(){this.clear(!1,!0,!1)}clearStencil(){this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,n=!0){en('Renderer: "clearAsync()" has been deprecated. Use "clear()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.clear(e,t,n)}async clearColorAsync(){en('Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.'),this.clear(!0,!1,!1)}async clearDepthAsync(){en('Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!0,!1)}async clearStencilAsync(){en('Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!1,!0)}get needsFrameBufferTarget(){const e=0!==this.currentToneMapping,t=this.currentColorSpace!==Mn.workingColorSpace;return e||t}get samples(){return this._samples}get currentSamples(){let e=this._samples;return null!==this._renderTarget?e=this._renderTarget.samples:this.needsFrameBufferTarget&&(e=0),e}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:0}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:Mn.workingColorSpace}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||null===this._renderTarget}dispose(){!0===this._initialized&&(this.info.dispose(),this.backend.dispose(),this._animation.dispose(),this._objects.dispose(),this._geometries.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose(),this._textures.dispose(),null!==this._frameBufferTarget&&this._frameBufferTarget.dispose(),Object.values(this.backend.timestampQueryPool).forEach(e=>{null!==e&&e.dispose()})),this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,n=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=n}getRenderTarget(){return this._renderTarget}setOutputRenderTarget(e){this._outputRenderTarget=e}getOutputRenderTarget(){return this._outputRenderTarget}setCanvasTarget(e){this._canvasTarget.removeEventListener("resize",this._onCanvasTargetResize),this._canvasTarget=e,this._canvasTarget.addEventListener("resize",this._onCanvasTargetResize)}getCanvasTarget(){return this._canvasTarget}_resetXRState(){this.backend.setXRTarget(null),this.setOutputRenderTarget(null),this.setRenderTarget(null),this._frameBufferTarget.dispose(),this._frameBufferTarget=null}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}compute(e,t=null){if(!0===this._isDeviceLost)return;if(!1===this._initialized)return Qt("Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead."),this.computeAsync(e,t);const n=this._nodes.nodeFrame,r=n.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,n.renderId=this.info.calls,this.backend.updateTimeStampUID(e),this.inspector.beginCompute(this.backend.getTimestampUID(e),e);const i=this.backend,s=this._pipelines,a=this._bindings,o=this._nodes,l=Array.isArray(e)?e:[e];if(void 0===l[0]||!0!==l[0].isComputeNode)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");i.beginCompute(e);for(const n of l){if(!1===s.has(n)){const e=()=>{n.removeEventListener("dispose",e),s.delete(n),a.deleteForCompute(n),o.delete(n)};n.addEventListener("dispose",e);const t=n.onInitFunction;null!==t&&t.call(n,{renderer:this})}o.updateForCompute(n),a.updateForCompute(n);const r=a.getForCompute(n),l=s.getForCompute(n,r);i.compute(e,n,r,l,t)}i.finishCompute(e),n.renderId=r,this.inspector.finishCompute(this.backend.getTimestampUID(e))}async computeAsync(e,t=null){!1===this._initialized&&await this.init(),this.compute(e,t)}async hasFeatureAsync(e){return en('Renderer: "hasFeatureAsync()" has been deprecated. Use "hasFeature()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.hasFeature(e)}async resolveTimestampsAsync(e="render"){return!1===this._initialized&&await this.init(),this.backend.resolveTimestampsAsync(e)}hasFeature(e){if(!1===this._initialized)throw new Error('Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before before using this method.');return this.backend.hasFeature(e)}hasInitialized(){return this._initialized}async initTextureAsync(e){en('Renderer: "initTextureAsync()" has been deprecated. Use "initTexture()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.initTexture(e)}initTexture(e){if(!1===this._initialized)throw new Error('Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before before using this method.');this._textures.updateTexture(e)}copyFramebufferToTexture(e,t=null){if(null!==t)if(t.isVector2)t=qC.set(t.x,t.y,e.image.width,e.image.height).floor();else{if(!t.isVector4)return void Jt("Renderer.copyFramebufferToTexture: Invalid rectangle.");t=qC.copy(t).floor()}else t=qC.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),this._inspector.copyFramebufferToTexture(e)}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),this._inspector.copyTextureToTexture(e,t)}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?$C:WC;if(!e.frustumCulled||s.intersectsSprite(e,t)){!0===this.sortObjects&&qC.setFromMatrixPosition(e.matrixWorld).applyMatrix4(XC);const{geometry:t,material:s}=e;s.visible&&r.push(e,t,s,n,qC.z,null,i)}}else if(e.isLineLoop)Jt("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?$C:WC;if(!e.frustumCulled||s.intersectsObject(e,t)){const{geometry:t,material:s}=e;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),qC.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(XC)),Array.isArray(s)){const a=t.groups;for(let o=0,l=a.length;o0){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;s0||i.transmissionNode&&i.transmissionNode.isNode||i.backdropNode&&i.backdropNode.isNode,e.isShadowPassMaterial){const{colorNode:t,depthNode:n,positionNode:r}=this._getShadowNodes(i);e.side=null===i.shadowSide?i.side:i.shadowSide,null!==t&&(e.colorNode=t),null!==n&&(e.depthNode=n),null!==r&&(e.positionNode=r)}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),p&&(t.overrideMaterial.colorNode=u,t.overrideMaterial.depthNode=c,t.overrideMaterial.positionNode=h,t.overrideMaterial.side=d),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)}_onCanvasTargetResize(){this._initialized&&this.backend.updateSize()}get compile(){return this.compileAsync}}class KC{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}getVisibility(){return this.visibility}clone(){return Object.assign(new this.constructor,this)}}class ZC extends KC{constructor(e,t=null){super(e),this.isBuffer=!0,this.bytesPerElement=Float32Array.BYTES_PER_ELEMENT,this._buffer=t,this._updateRanges=[]}get updateRanges(){return this._updateRanges}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}get byteLength(){return(e=this._buffer.byteLength)+(iE-e%iE)%iE;var e}get buffer(){return this._buffer}update(){return!0}}class QC extends ZC{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let JC=0;class eN extends QC{constructor(e,t){super("UniformBuffer_"+JC++,e?e.value:null),this.nodeUniform=e,this.groupNode=t,this.isNodeUniformBuffer=!0}set updateRanges(e){this.nodeUniform.updateRanges=e}get updateRanges(){return this.nodeUniform.updateRanges}addUpdateRange(e,t){this.nodeUniform.addUpdateRange(e,t)}clearUpdateRanges(){this.nodeUniform.clearUpdateRanges()}get buffer(){return this.nodeUniform.value}}class tN extends QC{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{this.generation=null,this.version=0},this.texture=t,this.version=t?t.version:0,this.generation=null,this.samplerKey="",this.isSampler=!0}set texture(e){this._texture!==e&&(this._texture&&this._texture.removeEventListener("dispose",this._onTextureDispose),this._texture=e,this.generation=null,this.version=0,this._texture&&this._texture.addEventListener("dispose",this._onTextureDispose))}get texture(){return this._texture}update(){const{texture:e,version:t}=this;return t!==e.version&&(this.version=e.version,!0)}clone(){const e=super.clone();return e._texture=null,e._onTextureDispose=()=>{e.generation=null,e.version=0},e.texture=this.texture,e}}let sN=0;class aN extends iN{constructor(e,t){super(e,t),this.id=sN++,this.store=!1,this.mipLevel=0,this.isSampledTexture=!0}}class oN extends aN{constructor(e,t,n,r=null){super(e,t?t.value:null),this.textureNode=t,this.groupNode=n,this.access=r}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class lN extends oN{constructor(e,t,n,r=null){super(e,t,n,r),this.isSampledCubeTexture=!0}}class uN extends oN{constructor(e,t,n,r=null){super(e,t,n,r),this.isSampledTexture3D=!0}}const cN={bitcast_int_uint:new _A("uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }"),bitcast_uint_int:new _A("uint tsl_bitcast_uint_to_int ( uint x ) { return floatBitsToInt( uintBitsToFloat ( x ) ); }")},hN={textureDimensions:"textureSize",equals:"equal",bitcast_float_int:"floatBitsToInt",bitcast_int_float:"intBitsToFloat",bitcast_uint_float:"uintBitsToFloat",bitcast_float_uint:"floatBitsToUint",bitcast_uint_int:"tsl_bitcast_uint_to_int",bitcast_int_uint:"tsl_bitcast_int_to_uint",floatpack_snorm_2x16:"packSnorm2x16",floatpack_unorm_2x16:"packUnorm2x16",floatpack_float16_2x16:"packHalf2x16",floatunpack_snorm_2x16:"unpackSnorm2x16",floatunpack_unorm_2x16:"unpackUnorm2x16",floatunpack_float16_2x16:"unpackHalf2x16"},dN={low:"lowp",medium:"mediump",high:"highp"},pN={swizzleAssign:!0,storageBuffer:!1},fN={perspective:"smooth",linear:"noperspective"},mN={centroid:"centroid"},gN="\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 _N extends KR{constructor(e,t){super(e,t,new _C),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]}}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==wt}_include(e){const t=cN[e];return t.build(this),this.addInclude(t),t}getMethod(e){return void 0!==cN[e]&&this._include(e),hN[e]||e}getBitcastMethod(e,t){return this.getMethod(`bitcast_${t}_${e}`)}getFloatPackingMethod(e){return this.getMethod(`floatpack_${e}_2x16`)}getFloatUnpackingMethod(e){return this.getMethod(`floatunpack_${e}_2x16`)}getTernary(e,t,n){return`${e} ? ${t} : ${n}`}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?ke:Be;2===r?s=i?Ve:ze:3===r?s=i?1032:Ie:4===r&&(s=i?Ge:Ue);const a={Float32Array:Ee,Uint8Array:be,Uint16Array:Se,Uint32Array:we,Int8Array:xe,Int16Array:Te,Int32Array:Me,Uint8ClampedArray:be},o=Math.pow(2,Math.ceil(Math.log2(Math.sqrt(n/r))));let l=Math.ceil(n/r/o);o*l*r0?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=dN[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!==Me){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+=`${fN[r.interpolationType]||r.interpolationType} ${mN[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+=`${fN[e.interpolationType]||e.interpolationType} ${mN[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`}getSubgroupSize(){Jt("GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node")}getInvocationSubgroupIndex(){Jt("GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node")}getSubgroupIndex(){Jt("GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node")}getDrawIndex(){return this.renderer.backend.extensions.has("WEBGL_multi_draw")?"uint( gl_DrawID )":null}getFrontFacing(){return"gl_FrontFacing"}getFragCoord(){return"gl_FragCoord.xy"}getFragDepth(){return"gl_FragDepth"}enableExtension(e,t,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=pN[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)}pN[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;n0&&(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 oN(i.name,i.node,r),l.push(a);else if("cubeTexture"===t||"cubeDepthTexture"===t)a=new lN(i.name,i.node,r),l.push(a);else if("texture3D"===t)a=new uN(i.name,i.node,r),l.push(a);else if("buffer"===t){i.name=`buffer${e.id}`;const t=this.getSharedDataFromNode(e);let n=t.buffer;void 0===n&&(e.name=`NodeBuffer_${e.id}`,n=new eN(e,r),n.name=e.name,t.buffer=n),l.push(n),a=n}else{const e=this.uniformGroups[n]||(this.uniformGroups[n]={});let s=e[o];void 0===s&&(s=new rN(n+"_"+o,r),e[o]=s,l.push(s)),a=this.getNodeUniform(i,t),s.addUniform(a)}s.uniformGPU=a}return i}}let vN=null,yN=null;class bN{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={[Wt]:null,[jt]:null},this.trackTimestamp=!0===e.trackTimestamp}async init(e){this.renderer=e}get coordinateSystem(){}beginRender(){}finishRender(){}beginCompute(){}finishCompute(){}draw(){}compute(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}updateBinding(){}createRenderPipeline(){}createComputePipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}updateSampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}updateTimeStampUID(e){const t=this.get(e),n=this.renderer.info.frame;let r;r=!0===e.isComputeNode?"c:"+this.renderer.info.compute.frameCalls:"r:"+this.renderer.info.render.frameCalls,t.timestampUID=r+":"+e.id+":f"+n}getTimestampUID(e){return this.get(e).timestampUID}getTimestampFrames(e){const t=this.timestampQueryPool[e];return t?t.getTimestampFrames():[]}_getQueryPool(e){const t=e.startsWith("c:")?jt:Wt;return this.timestampQueryPool[t]}getTimestamp(e){return this._getQueryPool(e).getTimestamp(e)}hasTimestamp(e){return this._getQueryPool(e).hasTimestamp(e)}isOccluded(){}async resolveTimestampsAsync(e="render"){if(!this.trackTimestamp)return void en("WebGPURenderer: Timestamp tracking is disabled.");const t=this.timestampQueryPool[e];if(!t)return;const n=await t.resolveQueriesAsync();return this.renderer.info[e].timestamp=n,n}async getArrayBufferAsync(){}async hasFeatureAsync(){}hasFeature(){}getMaxAnisotropy(){}getDrawingBufferSize(){return vN=vN||new fn,this.renderer.getDrawingBufferSize(vN)}setScissorTest(){}getClearColor(){const e=this.renderer;return yN=yN||new LE,e.getClearColor(yN),yN.getRGB(yN),yN}getDomElement(){let e=this.domElement;return null===e&&(e=void 0!==this.parameters.canvas?this.parameters.canvas:Yt(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${h} webgpu`),this.domElement=e),e}set(e,t){this.data.set(e,t)}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}has(e){return this.data.has(e)}delete(e){this.data.delete(e)}deleteBindGroupData(){}dispose(){}}let xN,TN,SN=0;class MN{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 wN{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===Me,id:SN++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(r,t,i,s);c=new MN(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;e0?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{!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 RN,CN,NN,PN=!1;class LN{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},this._srcFramebuffer=null,this._dstFramebuffer=null,!1===PN&&(this._init(),PN=!0)}_init(){const e=this.gl;RN={[he]:e.REPEAT,[de]:e.CLAMP_TO_EDGE,[pe]:e.MIRRORED_REPEAT},CN={[fe]:e.NEAREST,[me]:e.NEAREST_MIPMAP_NEAREST,[ge]:e.NEAREST_MIPMAP_LINEAR,[_e]:e.LINEAR,[ve]:e.LINEAR_MIPMAP_NEAREST,[ye]:e.LINEAR_MIPMAP_LINEAR},NN={[Pt]:e.NEVER,[Bt]:e.ALWAYS,[Lt]:e.LESS,[It]:e.LEQUAL,[Dt]:e.EQUAL,[Ft]:e.GEQUAL,[Ut]:e.GREATER,[Ot]: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];Qt("WebGLBackend: 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?Rt:Mn.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===Ct?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),n===s.UNSIGNED_INT_10F_11F_11F_REV&&(o=s.R11F_G11F_B10F)}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?Rt:Mn.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===Ct?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=Mn.getPrimaries(Mn.workingColorSpace),a=t.colorSpace===wt?null:Mn.getPrimaries(t.colorSpace),o=t.colorSpace===wt||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,RN[t.wrapS]),n.texParameteri(e,n.TEXTURE_WRAP_T,RN[t.wrapT]),e!==n.TEXTURE_3D&&e!==n.TEXTURE_2D_ARRAY||t.isArrayTexture||n.texParameteri(e,n.TEXTURE_WRAP_R,RN[t.wrapR]),n.texParameteri(e,n.TEXTURE_MAG_FILTER,CN[t.magFilter]);const l=void 0!==t.mipmaps&&t.mipmaps.length>0,u=t.minFilter===_e&&l?ye:t.minFilter;if(n.texParameteri(e,n.TEXTURE_MIN_FILTER,CN[u]),t.compareFunction&&(n.texParameteri(e,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE),n.texParameteri(e,n.TEXTURE_COMPARE_FUNC,NN[t.compareFunction])),!0===r.has("EXT_texture_filter_anisotropic")){if(t.magFilter===fe)return;if(t.minFilter!==ge&&t.minFilter!==ye)return;if(t.type===Ee&&!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})}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;t0){const t=qa(r.width,r.height,e.format,e.type);for(const i of e.layerUpdates){const e=r.data.subarray(i*t/r.data.BYTES_PER_ELEMENT,(i+1)*t/r.data.BYTES_PER_ELEMENT);n.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,i,r.width,r.height,1,o,l,e)}e.clearLayerUpdates()}else n.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,0,r.width,r.height,r.depth,o,l,r.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 s=e.mipmaps;if(s.length>0)for(let e=0,t=s.length;e0,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();a.state.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),a.state.bindFramebuffer(o.READ_FRAMEBUFFER,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}dispose(){const{gl:e}=this;null!==this._srcFramebuffer&&e.deleteFramebuffer(this._srcFramebuffer),null!==this._dstFramebuffer&&e.deleteFramebuffer(this._dstFramebuffer)}}function DN(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 IN{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 UN{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 ON={WEBGL_multi_draw:"WEBGL_multi_draw",WEBGL_compressed_texture_astc:"texture-compression-astc",WEBGL_compressed_texture_etc:"texture-compression-etc2",WEBGL_compressed_texture_etc1:"texture-compression-etc1",WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBGL_compressed_texture_s3tc:"texture-compression-s3tc",EXT_texture_compression_bptc:"texture-compression-bc",EXT_disjoint_timer_query_webgl2:"timestamp-query",OVR_multiview2:"OVR_multiview2"};class FN{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;rthis.maxQueries)return en(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryStates.set(t,"inactive"),this.queryOffsets.set(e,t),t}beginQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e);if(null==t)return;if(null!==this.activeQuery)return;const 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){Jt("Error in beginQuery:",e),this.activeQuery=null,this.queryStates.set(t,"inactive")}}endQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e);if(null!=t&&this.activeQuery===t)try{this.gl.endQuery(this.ext.TIME_ELAPSED_EXT),this.queryStates.set(t,"ended"),this.activeQuery=null}catch(e){Jt("Error in endQuery:",e),this.queryStates.set(t,"inactive"),this.activeQuery=null}}async resolveQueriesAsync(){if(!this.trackTimestamp||this.pendingResolve)return this.lastValue;this.pendingResolve=!0;try{const e=new Map;for(const[t,n]of this.queryOffsets){if("ended"===this.queryStates.get(n)){const r=this.queries[n];e.set(t,this.resolveQuery(r))}}if(0===e.size)return this.lastValue;const t={},n=[];for(const[r,i]of e){const e=r.match(/^(.*):f(\d+)$/),s=parseInt(e[2]);!1===n.includes(s)&&n.push(s),void 0===t[s]&&(t[s]=0);const a=await i;this.timestamps.set(r,a),t[s]+=a}const r=t[n[n.length-1]];return this.lastValue=r,this.frames=n,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,r}catch(e){return Jt("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){Jt("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}}}class zN extends bN{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.currentSamples>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 IN(this),this.capabilities=new UN(this),this.attributeUtils=new wN(this),this.textureUtils=new LN(this),this.bufferRenderer=new FN(this),this.state=new EN(this),this.utils=new AN(this),this.extensions.get("EXT_color_buffer_float"),this.extensions.get("WEBGL_clip_cull_distance"),this.extensions.get("OES_texture_float_linear"),this.extensions.get("EXT_color_buffer_half_float"),this.extensions.get("WEBGL_multisampled_render_to_texture"),this.extensions.get("WEBGL_render_shared_exponent"),this.extensions.get("WEBGL_multi_draw"),this.extensions.get("OVR_multiview2"),this.disjoint=this.extensions.get("EXT_disjoint_timer_query_webgl2"),this.parallel=this.extensions.get("KHR_parallel_shader_compile"),this.drawBuffersIndexedExt=this.extensions.get("OES_draw_buffers_indexed")}get coordinateSystem(){return Gt}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}async makeXRCompatible(){!0!==this.gl.getContextAttributes().xrCompatible&&await this.gl.makeXRCompatible()}setXRTarget(e){this._xrFramebuffer=e}setXRRenderTargetTextures(e,t,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&&Qt("WebGLBackend: Render-to-texture extension was disabled because an external texture was provided"),e._autoAllocateDepthBuffer=!1}}initTimestampQuery(e,t){if(!this.disjoint||!this.trackTimestamp)return;this.timestampQueryPool[e]||(this.timestampQueryPool[e]=new kN(this.gl,e,2048));const n=this.timestampQueryPool[e];null!==n.allocateQueriesForContext(t)&&n.beginQuery(t)}prepareTimestampBuffer(e,t){if(!this.disjoint||!this.trackTimestamp)return;this.timestampQueryPool[e].endQuery(t)}getContext(){return this.gl}beginRender(e){const{state:t}=this,n=this.get(e);if(e.viewport)this.updateViewport(e);else{const{width:e,height:n}=this.getDrawingBufferSize();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(Wt,this.getTimestampUID(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{let a=0;for(let t=0;t1&&l.setMRTBlending(i.textures),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:b}=c;let{firstVertex:x}=c;if(v.object=t,null!==m){x*=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?(en("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):en("WebGLBackend: WEBGL_multi_draw not supported."):b>1?v.renderInstances(x,y,b):v.render(x,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{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":" "} ${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");Jt("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&&Qt("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;eON[t]===e),n=this.extensions;for(let e=0;e1,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=wE(e);let b;if(u?(s.cubeFramebuffers||(s.cubeFramebuffers={}),b=s.cubeFramebuffers[y]):d&&!1===p?b=this._xrFramebuffer:(s.framebuffers||(s.framebuffers={}),b=s.framebuffers[y]),void 0===b){b=t.createFramebuffer(),n.bindFramebuffer(t.FRAMEBUFFER,b);const r=e.textures,o=[];if(u){s.cubeFramebuffers[y]=b;const{textureGPU:e}=this.get(r[0]),n=this.renderer._activeCubeFace,i=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+n,e,i)}else{s.framebuffers[y]=b;for(let n=0;n0&&!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;n0&&!1===this._useMultisampledExtension(r)){const s=i.framebuffers[e.getCacheKey()];let a=t.COLOR_BUFFER_BIT;r.resolveDepthBuffer&&(r.depthBuffer&&(a|=t.DEPTH_BUFFER_BIT),r.stencilBuffer&&r.resolveStencilBuffer&&(a|=t.STENCIL_BUFFER_BIT));const o=i.msaaFrameBuffer,l=i.msaaRenderbuffers,u=e.textures,c=u.length>1;if(n.bindFramebuffer(t.READ_FRAMEBUFFER,o),n.bindFramebuffer(t.DRAW_FRAMEBUFFER,s),c)for(let e=0;e0&&!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!1!==e._autoAllocateDepthBuffer}dispose(){null!==this.textureUtils&&this.textureUtils.dispose();const e=this.extensions.get("WEBGL_lose_context");e&&e.loseContext(),this.renderer.domElement.removeEventListener("webglcontextlost",this._onContextLost)}}const VN="point-list",GN="line-list",HN="line-strip",jN="triangle-list",WN="triangle-strip",$N="undefined"!=typeof self?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},XN="never",qN="less",YN="equal",KN="less-equal",ZN="greater",QN="not-equal",JN="greater-equal",eP="always",tP="store",nP="load",rP="clear",iP="ccw",sP="cw",aP="none",oP="back",lP="uint16",uP="uint32",cP="r8unorm",hP="r8snorm",dP="r8uint",pP="r8sint",fP="r16uint",mP="r16sint",gP="r16float",_P="rg8unorm",vP="rg8snorm",yP="rg8uint",bP="rg8sint",xP="r32uint",TP="r32sint",SP="r32float",MP="rg16uint",wP="rg16sint",EP="rg16float",AP="rgba8unorm",RP="rgba8unorm-srgb",CP="rgba8snorm",NP="rgba8uint",PP="rgba8sint",LP="bgra8unorm",DP="bgra8unorm-srgb",IP="rgb9e5ufloat",UP="rgb10a2unorm",OP="rg11b10ufloat",FP="rg32uint",BP="rg32sint",kP="rg32float",zP="rgba16uint",VP="rgba16sint",GP="rgba16float",HP="rgba32uint",jP="rgba32sint",WP="rgba32float",$P="depth16unorm",XP="depth24plus",qP="depth24plus-stencil8",YP="depth32float",KP="depth32float-stencil8",ZP="bc1-rgba-unorm",QP="bc1-rgba-unorm-srgb",JP="bc2-rgba-unorm",eL="bc2-rgba-unorm-srgb",tL="bc3-rgba-unorm",nL="bc3-rgba-unorm-srgb",rL="bc4-r-unorm",iL="bc4-r-snorm",sL="bc5-rg-unorm",aL="bc5-rg-snorm",oL="bc6h-rgb-ufloat",lL="bc6h-rgb-float",uL="bc7-rgba-unorm",cL="bc7-rgba-unorm-srgb",hL="etc2-rgb8unorm",dL="etc2-rgb8unorm-srgb",pL="etc2-rgb8a1unorm",fL="etc2-rgb8a1unorm-srgb",mL="etc2-rgba8unorm",gL="etc2-rgba8unorm-srgb",_L="eac-r11unorm",vL="eac-r11snorm",yL="eac-rg11unorm",bL="eac-rg11snorm",xL="astc-4x4-unorm",TL="astc-4x4-unorm-srgb",SL="astc-5x4-unorm",ML="astc-5x4-unorm-srgb",wL="astc-5x5-unorm",EL="astc-5x5-unorm-srgb",AL="astc-6x5-unorm",RL="astc-6x5-unorm-srgb",CL="astc-6x6-unorm",NL="astc-6x6-unorm-srgb",PL="astc-8x5-unorm",LL="astc-8x5-unorm-srgb",DL="astc-8x6-unorm",IL="astc-8x6-unorm-srgb",UL="astc-8x8-unorm",OL="astc-8x8-unorm-srgb",FL="astc-10x5-unorm",BL="astc-10x5-unorm-srgb",kL="astc-10x6-unorm",zL="astc-10x6-unorm-srgb",VL="astc-10x8-unorm",GL="astc-10x8-unorm-srgb",HL="astc-10x10-unorm",jL="astc-10x10-unorm-srgb",WL="astc-12x10-unorm",$L="astc-12x10-unorm-srgb",XL="astc-12x12-unorm",qL="astc-12x12-unorm-srgb",YL="clamp-to-edge",KL="repeat",ZL="mirror-repeat",QL="linear",JL="nearest",eD="zero",tD="one",nD="src",rD="one-minus-src",iD="src-alpha",sD="one-minus-src-alpha",aD="dst",oD="one-minus-dst",lD="dst-alpha",uD="one-minus-dst-alpha",cD="src-alpha-saturated",hD="constant",dD="one-minus-constant",pD="add",fD="subtract",mD="reverse-subtract",gD="min",_D="max",vD=0,yD=15,bD="keep",xD="zero",TD="replace",SD="invert",MD="increment-clamp",wD="decrement-clamp",ED="increment-wrap",AD="decrement-wrap",RD="storage",CD="read-only-storage",ND="write-only",PD="read-only",LD="read-write",DD="non-filtering",ID="comparison",UD="float",OD="unfilterable-float",FD="depth",BD="sint",kD="uint",zD="2d",VD="3d",GD="2d",HD="2d-array",jD="cube",WD="3d",$D="all",XD="vertex",qD="instance",YD={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"},KD={"texture-compression-s3tc":"texture-compression-bc","texture-compression-etc1":"texture-compression-etc2"};class ZD extends iN{constructor(e,t,n){super(e,t?t.value:null),this.textureNode=t,this.groupNode=n}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class QD extends ZC{constructor(e,t){super(e,t?t.array:null),this.attribute=t,this.isStorageBuffer=!0}}let JD=0;class eI extends QD{constructor(e,t){super("StorageBuffer_"+JD++,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:Wf,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class tI extends Jw{constructor(e){super(),this.device=e;this.mipmapSampler=e.createSampler({minFilter:QL}),this.flipYSampler=e.createSampler({minFilter:JL}),this.transferPipelines={},this.flipYPipelines={},this.mipmapVertexShaderModule=e.createShaderModule({label:"mipmapVertex",code:"\nstruct VarysStruct {\n\t@builtin( position ) Position: vec4,\n\t@location( 0 ) vTex : vec2\n};\n\n@vertex\nfn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {\n\n\tvar Varys : VarysStruct;\n\n\tvar pos = array< vec2, 4 >(\n\t\tvec2( -1.0, 1.0 ),\n\t\tvec2( 1.0, 1.0 ),\n\t\tvec2( -1.0, -1.0 ),\n\t\tvec2( 1.0, -1.0 )\n\t);\n\n\tvar tex = array< vec2, 4 >(\n\t\tvec2( 0.0, 0.0 ),\n\t\tvec2( 1.0, 0.0 ),\n\t\tvec2( 0.0, 1.0 ),\n\t\tvec2( 1.0, 1.0 )\n\t);\n\n\tVarys.vTex = tex[ vertexIndex ];\n\tVarys.Position = vec4( 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;\n\n@fragment\nfn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 {\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;\n\n@fragment\nfn main( @location( 0 ) vTex : vec2 ) -> @location( 0 ) vec4 {\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:WN,stripIndexFormat:uP},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:WN,stripIndexFormat:uP},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:GD,baseArrayLayer:n}),c=l.createView({baseMipLevel:0,mipLevelCount:1,dimension:GD,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:rP,storeOp:tP,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,r=null){const i=this.get(e);void 0===i.layers&&(i.layers=[]);const s=i.layers[n]||this._mipmapCreateBundles(e,t,n),a=r||this.device.createCommandEncoder({label:"mipmapEncoder"});this._mipmapRunBundles(a,s),null===r&&this.device.queue.submit([a.finish()]),i.layers[n]=s}_mipmapCreateBundles(e,t,n){const r=this.getTransferPipeline(t.format),i=r.getBindGroupLayout(0);let s=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:GD,baseArrayLayer:n});const a=[];for(let o=1;o0)for(let t=0,s=r.length;t0)for(let t=0,s=r.length;t0?e.width:n.size.width,u=a>0?e.height:n.size.height;try{o.queue.copyExternalImageToTexture({source:e,flipY:i},{texture:t,mipLevel:a,origin:{x:0,y:0,z:r},premultipliedAlpha:s},{width:l,height:u,depthOrArrayLayers:1})}catch(e){}}_getPassUtils(){let e=this._passUtils;return null===e&&(this._passUtils=e=new tI(this.backend.device)),e}_generateMipmaps(e,t,n=0,r=null){this._getPassUtils().generateMipmaps(e,t,n,r)}_flipY(e,t,n=0){this._getPassUtils().flipY(e,t,n)}_copyBufferToTexture(e,t,n,r,i,s=0,a=0){const o=this.backend.device,l=e.data,u=this._getBytesPerTexel(n.format),c=e.width*u;o.queue.writeTexture({texture:t,mipLevel:a,origin:{x:0,y:0,z:r}},l,{offset:e.width*e.height*u*s,bytesPerRow:c},{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]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,oI=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,lI={f32:"float",i32:"int",u32:"uint",bool:"bool","vec2":"vec2","vec2":"ivec2","vec2":"uvec2","vec2":"bvec2",vec2f:"vec2",vec2i:"ivec2",vec2u:"uvec2",vec2b:"bvec2","vec3":"vec3","vec3":"ivec3","vec3":"uvec3","vec3":"bvec3",vec3f:"vec3",vec3i:"ivec3",vec3u:"uvec3",vec3b:"bvec3","vec4":"vec4","vec4":"ivec4","vec4":"uvec4","vec4":"bvec4",vec4f:"vec4",vec4i:"ivec4",vec4u:"uvec4",vec4b:"bvec4","mat2x2":"mat2",mat2x2f:"mat2","mat3x3":"mat3",mat3x3f:"mat3","mat4x4":"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 uI extends dC{constructor(e){const{type:t,inputs:n,name:r,inputsCode:i,blockCode:s,outputType:a}=(e=>{const t=(e=e.trim()).match(aI);if(null!==t&&4===t.length){const n=t[2],r=[];let i=null;for(;null!==(i=oI.exec(n));)r.push({name:i[1],type:i[2]});const s=[];for(let e=0;e "+this.outputType:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class cI extends hC{parseFunction(e){return new uI(e)}}const hI={[Hf]:"read",[jf]:"write",[Wf]:"read_write"},dI={[he]:"repeat",[de]:"clamp",[pe]:"mirror"},pI={vertex:$N.VERTEX,fragment:$N.FRAGMENT,compute:$N.COMPUTE},fI={instance:!0,swizzleAssign:!1,storageBuffer:!0},mI={"^^":"tsl_xor"},gI={float:"f32",int:"i32",uint:"u32",bool:"bool",color:"vec3",vec2:"vec2",ivec2:"vec2",uvec2:"vec2",bvec2:"vec2",vec3:"vec3",ivec3:"vec3",uvec3:"vec3",bvec3:"vec3",vec4:"vec4",ivec4:"vec4",uvec4:"vec4",bvec4:"vec4",mat2:"mat2x2",mat3:"mat3x3",mat4:"mat4x4"},_I={},vI={tsl_xor:new _A("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new _A("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new _A("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new _A("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new _A("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new _A("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new _A("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2 { return vec2( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new _A("fn tsl_equals_bvec3( a : vec3f, b : vec3f ) -> vec3 { return vec3( a.x == b.x, a.y == b.y, a.z == b.z ); }"),equals_bvec4:new _A("fn tsl_equals_bvec4( a : vec4f, b : vec4f ) -> vec4 { return vec4( a.x == b.x, a.y == b.y, a.z == b.z, a.w == b.w ); }"),repeatWrapping_float:new _A("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new _A("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 _A("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),biquadraticTexture:new _A("\nfn tsl_biquadraticTexture( map : texture_2d, 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")},yI={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",floatpack_snorm_2x16:"pack2x16snorm",floatpack_unorm_2x16:"pack2x16unorm",floatpack_float16_2x16:"pack2x16float",floatunpack_snorm_2x16:"unpack2x16snorm",floatunpack_unorm_2x16:"unpack2x16unorm",floatunpack_float16_2x16:"unpack2x16float"};let bI="";!0!==("undefined"!=typeof navigator&&/Firefox|Deno/g.test(navigator.userAgent))&&(bI+="diagnostic( off, derivative_uniformity );\n");class xI extends KR{constructor(e,t){super(e,t,new cI),this.uniformGroups={},this.builtins={},this.directives={},this.scopedArrays=new Map}_generateTextureSample(e,t,n,r,i,s=this.shaderStage){return"fragment"===s?r?i?`textureSample( ${t}, ${t}_sampler, ${n}, ${r}, ${i} )`:`textureSample( ${t}, ${t}_sampler, ${n}, ${r} )`:i?`textureSample( ${t}, ${t}_sampler, ${n}, ${i} )`:`textureSample( ${t}, ${t}_sampler, ${n} )`:this.generateTextureSampleLevel(e,t,n,"0",r)}generateTextureSampleLevel(e,t,n,r,i,s){return!1===this.isUnfilterable(e)?s?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${r}, ${s} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${r} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,n,s,r):this.generateTextureLod(e,t,n,i,s,r)}generateWrapFunction(e){const t=`tsl_coord_${dI[e.wrapS]}S_${dI[e.wrapT]}_${e.is3DTexture||e.isData3DTexture?"3d":"2d"}T`;let n=_I[t];if(void 0===n){const r=[],i=e.is3DTexture||e.isData3DTexture?"vec3f":"vec2f";let s=`fn ${t}( coord : ${i} ) -> ${i} {\n\n\treturn ${i}(\n`;const a=(e,t)=>{e===he?(r.push(vI.repeatWrapping_float),s+=`\t\ttsl_repeatWrapping_float( coord.${t} )`):e===de?(r.push(vI.clampWrapping_float),s+=`\t\ttsl_clampWrapping_float( coord.${t} )`):e===pe?(r.push(vI.mirrorWrapping_float),s+=`\t\ttsl_mirrorWrapping_float( coord.${t} )`):(s+=`\t\tcoord.${t}`,Qt(`WebGPURenderer: Unsupported texture wrap type "${e}" for vertex shader.`))};a(e.wrapS,"x"),s+=",\n",a(e.wrapT,"y"),(e.is3DTexture||e.isData3DTexture)&&(s+=",\n",a(e.wrapR,"z")),s+="\n\t);\n\n}\n",_I[t]=n=new _A(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.is3DTexture||e.isData3DTexture?"vec3":"vec2",s=l||e.isStorageTexture?t:`${t}${n?`, u32( ${n} )`:""}`,i=new jv(new Ty(`textureDimensions( ${s} )`,a)),r.dimensionsSnippet[n]=i,(e.isArrayTexture||e.isDataArrayTexture||e.is3DTexture||e.isData3DTexture)&&(r.arrayLayerCount=new jv(new Ty(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(r.cubeFaceCount=new jv(new Ty("6u","u32")))}return i.build(this)}generateFilteredTexture(e,t,n,r,i="0u"){this._include("biquadraticTexture");const s=this.generateWrapFunction(e),a=this.generateTextureDimension(e,t,i);return r&&(n=`${n} + vec2(${r}) / ${a}`),`tsl_biquadraticTexture( ${t}, ${s}( ${n} ), ${a}, u32( ${i} ) )`}generateTextureLod(e,t,n,r,i,s="0u"){const a=this.generateWrapFunction(e),o=this.generateTextureDimension(e,t,s),l=e.is3DTexture||e.isData3DTexture?"vec3":"vec2";i&&(n=`${n} + ${l}(${i}) / ${l}( ${o} )`);const u=`${l}( ${a}( ${n} ) * ${l}( ${o} ) )`;return this.generateTextureLoad(e,t,u,s,r,null)}generateTextureLoad(e,t,n,r,i,s){let a;return null===r&&(r="0u"),s&&(n=`${n} + ${s}`),i?a=`textureLoad( ${t}, ${n}, ${i}, u32( ${r} ) )`:(a=`textureLoad( ${t}, ${n}, u32( ${r} ) )`,this.renderer.backend.compatibilityMode&&e.isDepthTexture&&(a+=".x")),a}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===Ee||!1===this.isSampleCompare(e)&&e.minFilter===fe&&e.magFilter===fe||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1}generateTexture(e,t,n,r,i,s=this.shaderStage){let a=null;return a=this.isUnfilterable(e)?this.generateTextureLod(e,t,n,r,i,"0",s):this._generateTextureSample(e,t,n,r,i,s),a}generateTextureGrad(e,t,n,r,i,s,a=this.shaderStage){if("fragment"===a)return s?`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${r[0]}, ${r[1]}, ${s} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${r[0]}, ${r[1]} )`;Jt(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${a} shader.`)}generateTextureCompare(e,t,n,r,i,s,a=this.shaderStage){if("fragment"===a)return!0===e.isDepthTexture&&!0===e.isArrayTexture?s?`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${i}, ${r}, ${s} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${i}, ${r} )`:s?`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${r}, ${s} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${r} )`;Jt(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${a} shader.`)}generateTextureLevel(e,t,n,r,i,s){return!1===this.isUnfilterable(e)?s?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${r}, ${s} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${r} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,n,s,r):this.generateTextureLod(e,t,n,i,s,r)}generateTextureBias(e,t,n,r,i,s,a=this.shaderStage){if("fragment"===a)return s?`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${r}, ${s} )`:`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${r} )`;Jt(`WebGPURenderer: THREE.TextureNode.biasNode does not support ${a} shader.`)}getPropertyName(e,t=this.shaderStage){if(!0===e.isNodeVarying&&!0===e.needsInterpolation){if("vertex"===t)return`varyings.${e.name}`}else if(!0===e.isNodeUniform){const t=e.name,n=e.type;return"texture"===n||"cubeTexture"===n||"cubeDepthTexture"===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=mI[e];return void 0!==t?(this._include(t),t):null}getNodeAccess(e,t){return"compute"!==t?!0===e.isAtomic?(Qt("WebGPURenderer: Atomic operations are only supported in compute shaders."),Wf):Hf:e.access}getStorageAccess(e,t){return hI[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||"cubeDepthTexture"===t||"storageTexture"===t||"texture3D"===t){let r=null;const s=this.getNodeAccess(e,n);if("texture"===t||"storageTexture"===t?r=!0===e.value.is3DTexture?new uN(i.name,i.node,o,s):new oN(i.name,i.node,o,s):"cubeTexture"===t||"cubeDepthTexture"===t?r=new lN(i.name,i.node,o,s):"texture3D"===t&&(r=new uN(i.name,i.node,o,s)),r.store=!0===e.isStorageTextureNode,r.mipLevel=r.store?e.mipLevel:0,r.setVisibility(pI[n]),!1===this.isUnfilterable(e.value)&&!1===r.store){const e=new ZD(`${i.name}_sampler`,i.node,o);e.setVisibility(pI[n]),u.push(e,r),a=[e,r]}else u.push(r),a=[r]}else if("buffer"===t||"storageBuffer"===t||"indirectStorageBuffer"===t){const s=this.getSharedDataFromNode(e);let l=s.buffer;if(void 0===l){l=new("buffer"===t?eN:eI)(e,o),s.buffer=l}l.setVisibility(l.getVisibility()|pI[n]),u.push(l),a=l,i.name=r||"NodeBuffer_"+i.id}else{const e=this.uniformGroups[n]||(this.uniformGroups[n]={});let r=e[l];void 0===r&&(r=new rN(l,o),r.setVisibility(pI[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")+".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`,"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","attribute"),this.getBuiltin("workgroup_id","workgroupId","vec3","attribute"),this.getBuiltin("local_invocation_id","localId","vec3","attribute"),this.getBuiltin("num_workgroups","numWorkgroups","vec3","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"),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","vertex"),"vertex"===e||"fragment"===e){const n=this.varyings,r=this.vars[e];for(let i=0;in.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||"cubeDepthTexture"===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&&!0===t.isDepthTexture)r="texture_depth_cube";else if(!0===t.isCubeTexture)r="texture_cube";else if(!0===t.isDepthTexture)r=this.renderer.backend.compatibilityMode&&null===t.compareFunction?`texture${s}_2d`:`texture_depth${s}_2d${!0===t.isArrayTexture?"_array":""}`;else if(!0===i.node.isStorageTextureNode){const n=sI(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";else if(!0===t.is3DTexture||!0===t.isData3DTexture)r="texture_3d";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))}return[...n,...r,...i].join("\n")}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 output : "+n.returnType+";",r+=`return ${i.result};`;else{let e="\t@location(0) color: vec4";const t=this.getBuiltins("output");t&&(e+=",\n\t"+t),n.returnType="OutputStruct",n.structs+=this._getWGSLStruct("OutputStruct",e),n.structs+="\nvar output : OutputStruct;",r+=`output.color = ${i.result};\n\n\treturn output;`}}n.flow=r}if(this.shaderStage=null,null!==this.material)this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment);else{const t=this.object.workgroupSize;this.computeShader=this._getWGSLComputeCode(e.compute,t)}}getMethod(e,t=null){let n;return null!==t&&(n=this._getWGSLMethod(e+"_"+t)),void 0===n&&(n=this._getWGSLMethod(e)),n||e}getBitcastMethod(e){return`bitcast<${this.getType(e)}>`}getFloatPackingMethod(e){return this.getMethod(`floatpack_${e}_2x16`)}getFloatUnpackingMethod(e){return this.getMethod(`floatunpack_${e}_2x16`)}getTernary(e,t,n){return`select( ${n}, ${t}, ${e} )`}getType(e){return gI[e]||e}isAvailable(e){let t=fI[e];return void 0===t&&("float32Filterable"===e?t=this.renderer.hasFeature("float32-filterable"):"clipDistance"===e&&(t=this.renderer.hasFeature("clip-distances")),fI[e]=t),t}_getWGSLMethod(e){return void 0!==vI[e]&&this._include(e),yI[e]}_include(e){const t=vI[e];return t.build(this),this.addInclude(t),t}_getWGSLVertexCode(e){return`${this.getSignature()}\n// directives\n${e.directives}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\nvar 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${bI}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@fragment\nfn main( ${e.varyings} ) -> ${e.returnType} {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLComputeCode(e,t){const[n,r,i]=t;return`${this.getSignature()}\n// directives\n${e.directives}\n\n// system\nvar 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( ${n}, ${r}, ${i} )\nfn main( ${e.attributes} ) {\n\n\t// system\n\tinstanceIndex = globalId.x\n\t\t+ globalId.y * ( ${n} * numWorkgroups.x )\n\t\t+ globalId.z * ( ${n} * numWorkgroups.x ) * ( ${r} * numWorkgroups.y );\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLStruct(e,t){return`\nstruct ${e} {\n${t}\n};`}_getWGSLStructBinding(e,t,n,r=0,i=0){const s=e+"Struct";return`${this._getWGSLStruct(s,t)}\n@binding( ${r} ) @group( ${i} )\nvar<${n}> ${e} : ${s};`}}class TI{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return null!==e.depthTexture?t=this.getTextureFormatGPU(e.depthTexture):e.depth&&e.stencil?t=qP:e.depth&&(t=XP),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.currentSamples}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}getCurrentColorFormats(e){return null!==e.textures?e.textures.map(e=>this.getTextureFormatGPU(e)):[this.getPreferredCanvasFormat()]}getCurrentColorSpace(e){return null!==e.textures?e.textures[0].colorSpace:this.backend.renderer.outputColorSpace}getPrimitiveTopology(e,t){return e.isPoints?VN:e.isLineSegments||e.isMesh&&!0===t.wireframe?GN:e.isLine?HN:e.isMesh?jN:void 0}getSampleCount(e){return e>=4?4:1}getSampleCountRenderContext(e){return null!==e.textures?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.currentSamples)}getPreferredCanvasFormat(){const e=this.backend.parameters.outputType;if(void 0===e)return navigator.gpu.getPreferredCanvasFormat();if(e===be)return LP;if(e===Ae)return GP;throw new Error("Unsupported output buffer type.")}}const SI=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&&SI.set(Float16Array,["float16"]);const MI=new Map([[bi,["float16"]]]),wI=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class EI{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;e0&&(void 0===s.groups&&(s.groups=[],s.versions=[]),s.versions[n]===r&&(o=s.groups[n])),void 0===o&&(o=this.createBindGroup(e,a),n>0&&(s.groups[n]=o,s.versions[n]=r)),s.group=o}updateBinding(e){const t=this.backend,n=t.device,r=e.buffer,i=t.get(e).buffer,s=e.updateRanges;if(0===s.length)n.queue.writeBuffer(i,0,r,0);else{const t=Xt(r),a=t?1:r.BYTES_PER_ELEMENT;for(let e=0,o=s.length;e1&&(i+=`-${e.texture.depthOrArrayLayers}`),i+=`-${n}-${r}`,a=e[i],void 0===a){const s=$D;let o;o=t.isSampledCubeTexture?jD:t.isSampledTexture3D?WD:t.texture.isArrayTexture||t.texture.isDataArrayTexture||t.texture.isCompressedArrayTexture?HD:GD,a=e[i]=e.texture.createView({aspect:s,dimension:o,mipLevelCount:n,baseMipLevel:r})}}s.push({binding:i,resource:a})}else if(t.isSampler){const e=n.get(t.texture);s.push({binding:i,resource:e.sampler})}i++}return r.createBindGroup({label:"bindGroup_"+e.name,layout:t,entries:s})}_createLayoutEntries(e){const t=[];let n=0;for(const r of e.bindings){const e=this.backend,i={binding:n,visibility:r.visibility};if(r.isUniformBuffer||r.isStorageBuffer){const e={};r.isStorageBuffer&&(r.visibility&$N.COMPUTE&&(r.access===Wf||r.access===jf)?e.type=RD:e.type=CD),i.buffer=e}else if(r.isSampledTexture&&r.store){const e={};e.format=this.backend.get(r.texture).texture.format;const t=r.access;e.access=t===Wf?LD:t===jf?ND:PD,r.texture.isArrayTexture?e.viewDimension=HD:r.texture.is3DTexture&&(e.viewDimension=WD),i.storageTexture=e}else if(r.isSampledTexture){const t={},{primarySamples:n}=e.utils.getTextureSampleData(r.texture);if(n>1&&(t.multisampled=!0,r.texture.isDepthTexture||(t.sampleType=OD)),r.texture.isDepthTexture)e.compatibilityMode&&null===r.texture.compareFunction?t.sampleType=OD:t.sampleType=FD;else if(r.texture.isDataTexture||r.texture.isDataArrayTexture||r.texture.isData3DTexture){const e=r.texture.type;e===Me?t.sampleType=BD:e===we?t.sampleType=kD:e===Ee&&(this.backend.hasFeature("float32-filterable")?t.sampleType=UD:t.sampleType=OD)}r.isSampledCubeTexture?t.viewDimension=jD:r.texture.isArrayTexture||r.texture.isDataArrayTexture||r.texture.isCompressedArrayTexture?t.viewDimension=HD:r.isSampledTexture3D&&(t.viewDimension=WD),i.texture=t}else if(r.isSampler){const t={};r.texture.isDepthTexture&&(null!==r.texture.compareFunction?t.type=ID:e.compatibilityMode&&(t.type=DD)),i.sampler=t}else Jt(`WebGPUBindingUtils: Unsupported binding "${r}".`);t.push(i),n++}return t}deleteBindGroupData(e){const{backend:t}=this,n=t.get(e);n.layout&&(n.layout.usedTimes--,0===n.layout.usedTimes&&this._bindGroupLayoutCache.delete(n.layoutKey),n.layout=void 0,n.layoutKey=void 0)}dispose(){this._bindGroupLayoutCache.clear()}}class CI{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),{layoutGPU:n}=e.layout;d.push(n)}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;e1},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=x),!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),u.pushErrorScope("validation"),null===t)h.pipeline=u.createRenderPipeline(M),u.popErrorScope().then(e=>{null!==e&&(h.error=!0,Jt(e.message))});else{const e=new Promise(async e=>{try{h.pipeline=await u.createRenderPipelineAsync(M)}catch(e){}const t=await u.popErrorScope();null!==t&&(h.error=!0,Jt(t.message)),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.getCurrentColorFormats(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),{layoutGPU:r}=t.layout;a.push(r)}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:pD},n={srcFactor:i,dstFactor:s,operation:pD}};if(e.premultipliedAlpha)switch(r){case 1:i(tD,sD,tD,sD);break;case 2:i(tD,tD,tD,tD);break;case 3:i(eD,rD,eD,tD);break;case 4:i(aD,sD,eD,tD)}else switch(r){case 1:i(iD,sD,tD,sD);break;case 2:i(iD,tD,tD,tD);break;case 3:Jt("WebGPURenderer: SubtractiveBlending requires material.premultipliedAlpha = true");break;case 4:Jt("WebGPURenderer: MultiplyBlending requires material.premultipliedAlpha = true")}}if(void 0!==t&&void 0!==n)return{color:t,alpha:n};Jt("WebGPURenderer: Invalid blending: ",r)}_getBlendFactor(e){let t;switch(e){case A:t=eD;break;case 201:t=tD;break;case 202:t=nD;break;case 203:t=rD;break;case P:t=iD;break;case L:t=sD;break;case 208:t=aD;break;case 209:t=oD;break;case 206:t=lD;break;case 207:t=uD;break;case 210:t=cD;break;case 211:t=hD;break;case 212:t=dD;break;default:Jt("WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const n=e.stencilFunc;switch(n){case 512:t=XN;break;case 519:t=eP;break;case 513:t=qN;break;case 515:t=KN;break;case 514:t=YN;break;case 518:t=JN;break;case 516:t=ZN;break;case 517:t=QN;break;default:Jt("WebGPURenderer: Invalid stencil function.",n)}return t}_getStencilOperation(e){let t;switch(e){case Nt:t=bD;break;case 0:t=xD;break;case 7681:t=TD;break;case 5386:t=SD;break;case 7682:t=MD;break;case 7683:t=wD;break;case 34055:t=ED;break;case 34056:t=AD;break;default:Jt("WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case M:t=pD;break;case 101:t=fD;break;case 102:t=mD;break;case 103:t=gD;break;case 104:t=_D;break;default:Jt("WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,n){const r={},i=this.backend.utils;r.topology=i.getPrimitiveTopology(e,n),null!==t.index&&!0===e.isLine&&!0!==e.isLineSegments&&(r.stripIndexFormat=t.index.array instanceof Uint16Array?lP:uP);let s=1===n.side;return e.isMesh&&e.matrixWorld.determinant()<0&&(s=!s),r.frontFace=!0===s?sP:iP,r.cullMode=2===n.side?aP:oP,r}_getColorWriteMask(e){return!0===e.colorWrite?yD:vD}_getDepthCompare(e){let t;if(!1===e.depthTest)t=eP;else{const n=e.depthFunc;switch(n){case 0:t=XN;break;case 1:t=eP;break;case 2:t=qN;break;case 3:t=KN;break;case 4:t=YN;break;case 5:t=JN;break;case 6:t=ZN;break;case 7:t=QN;break;default:Jt("WebGPUPipelineUtils: Invalid depth function.",n)}}return t}}class NI extends BN{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 en(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryOffsets.set(e,t),t}async resolveQueriesAsync(){if(!this.trackTimestamp||0===this.currentQueryIndex||this.isDisposed)return this.lastValue;if(this.pendingResolve)return this.pendingResolve;this.pendingResolve=this._resolveQueries();try{return await this.pendingResolve}finally{this.pendingResolve=null}}async _resolveQueries(){if(this.isDisposed)return this.lastValue;try{if("unmapped"!==this.resultBuffer.mapState)return this.lastValue;const e=new Map(this.queryOffsets),t=this.currentQueryIndex,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)),a={},o=[];for(const[t,n]of e){const e=t.match(/^(.*):f(\d+)$/),r=parseInt(e[2]);!1===o.includes(r)&&o.push(r),void 0===a[r]&&(a[r]=0);const i=s[n],l=s[n+1],u=Number(l-i)/1e6;this.timestamps.set(t,u),a[r]+=u}const l=a[o[o.length-1]];return this.resultBuffer.unmap(),this.lastValue=l,this.frames=o,l}catch(e){return Jt("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){Jt("Error waiting for pending resolve:",e)}if(this.resultBuffer&&"mapped"===this.resultBuffer.mapState)try{this.resultBuffer.unmap()}catch(e){Jt("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 PI extends bN{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=void 0===e.alpha||e.alpha,this.parameters.compatibilityMode=void 0!==e.compatibilityMode&&e.compatibilityMode,this.parameters.requiredLimits=void 0===e.requiredLimits?{}:e.requiredLimits,this.compatibilityMode=this.parameters.compatibilityMode,this.device=null,this.defaultRenderPassdescriptor=null,this.utils=new TI(this),this.attributeUtils=new EI(this),this.bindingUtils=new RI(this),this.pipelineUtils=new CI(this),this.textureUtils=new iI(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(YD),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=>{if("destroyed"===t.reason)return;const n={api:"WebGPU",message:t.message||"Unknown reason",reason:t.reason||null,originalEvent:t};e.onDeviceLost(n)}),this.device=n,this.trackTimestamp=this.trackTimestamp&&this.hasFeature(YD.TimestampQuery),this.updateSize()}get context(){const e=this.renderer.getCanvasTarget(),t=this.get(e);let n=t.context;if(void 0===n){const r=this.parameters;n=!0===e.isDefaultCanvasTarget&&void 0!==r.context?r.context:e.domElement.getContext("webgpu"),"setAttribute"in e.domElement&&e.domElement.setAttribute("data-engine",`three.js r${h} webgpu`);const i=r.alpha?"premultiplied":"opaque",s=r.outputType===Ae?"extended":"standard";n.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:i,toneMapping:{mode:s}}),t.context=n}return n}get coordinateSystem(){return Ht}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){const e=this.renderer,t=e.getCanvasTarget(),n=this.get(t),r=e.currentSamples;let i=n.descriptor;if(void 0===i||n.samples!==r){i={colorAttachments:[{view:null}]},!0!==e.depth&&!0!==e.stencil||(i.depthStencilAttachment={view:this.textureUtils.getDepthBuffer(e.depth,e.stencil).createView()});const t=i.colorAttachments[0];r>0?t.view=this.textureUtils.getColorBuffer().createView():t.resolveTarget=void 0,n.descriptor=i,n.samples=r}const s=i.colorAttachments[0];return r>0?s.resolveTarget=this.context.getCurrentTexture().createView():s.view=this.context.getCurrentTexture().createView(),i}_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;void 0!==i&&r.width===n.width&&r.height===n.height&&r.samples===n.samples||(i={},r.descriptors=i);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;r1)if(!0===u){const t=e.camera.cameras;for(let e=0;e0&&(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:nP}),this.initTimestampQuery(Wt,this.getTimestampUID(e),s),s.occlusionQuerySet=i;const a=s.depthStencilAttachment;if(null!==e.textures){const t=s.colorAttachments;for(let n=0;n0&&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;e0){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;eo&&(i[0]=Math.min(a,o),i[1]=Math.ceil(a/o)),s.dispatchSize=i}i=s.dispatchSize}a.dispatchWorkgroups(i[0],i[1]||1,i[2]||1)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),this.device.queue.submit([t.cmdEncoderGPU.finish()])}draw(e,t){const{object:n,material:r,context:i,pipeline:s}=e,a=e.getBindings(),o=this.get(i),l=this.get(s),u=l.pipeline;if(!0===l.error)return;const c=e.getIndex(),h=null!==c,d=e.getDrawParameters();if(null===d)return;const p=(t,n)=>{this.pipelineUtils.setPipeline(t,u),n.pipeline=u;const s=n.bindingGroups;for(let e=0,n=a.length;e{if(p(r,i),!0===n.isBatchedMesh){const e=n._multiDrawStarts,i=n._multiDrawCounts,s=n._multiDrawCount,a=n._multiDrawInstances;null!==a&&en("WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.");for(let o=0;o1?0:o;!0===h?r.drawIndexed(i[o],s,e[o]/c.array.BYTES_PER_ELEMENT,0,l):r.draw(i[o],s,e[o],l),t.update(n,i[o],s)}}else if(!0===h){const{vertexCount:i,instanceCount:s,firstVertex:a}=d,o=e.getIndirect();if(null!==o){const t=this.get(o).buffer,n=e.getIndirectOffset(),i=Array.isArray(n)?n:[n];for(let e=0;e0){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(Qt("WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new zN(e)));super(new t(e),e),this.library=new II,this.isWebGPURenderer=!0,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}}const OI={type:"change"},FI={type:"start"},BI={type:"end"},kI=1e-6,zI=-1,VI=0,GI=1,HI=2,jI=3,WI=4,$I=new fn,XI=new fn,qI=new gn,YI=new gn,KI=new gn,ZI=new mn,QI=new gn,JI=new gn,eU=new gn,tU=new gn;class nU extends Xa{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:d,MIDDLE:p,RIGHT:f},this.target=new gn,this.state=zI,this.keyState=zI,this._lastPosition=new gn,this._lastZoom=1,this._touchZoomDistanceStart=0,this._touchZoomDistanceEnd=0,this._lastAngle=0,this._eye=new gn,this._movePrev=new fn,this._moveCurr=new fn,this._lastAxis=new gn,this._zoomStart=new fn,this._zoomEnd=new fn,this._panStart=new fn,this._panEnd=new fn,this._pointers=[],this._pointerPositions={},this._onPointerMove=iU.bind(this),this._onPointerDown=rU.bind(this),this._onPointerUp=sU.bind(this),this._onPointerCancel=aU.bind(this),this._onContextMenu=pU.bind(this),this._onMouseWheel=dU.bind(this),this._onKeyDown=lU.bind(this),this._onKeyUp=oU.bind(this),this._onTouchStart=fU.bind(this),this._onTouchMove=mU.bind(this),this._onTouchEnd=gU.bind(this),this._onMouseDown=uU.bind(this),this._onMouseMove=cU.bind(this),this._onMouseUp=hU.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="proxy.php?url=none"}disconnect(){window.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("keyup",this._onKeyUp),this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerCancel),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchaction="proxy.php?url=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)>kI&&(this.dispatchEvent(OI),this._lastPosition.copy(this.object.position))):this.object.isOrthographicCamera?(this.object.lookAt(this.target),(this._lastPosition.distanceToSquared(this.object.position)>kI||this._lastZoom!==this.object.zoom)&&(this.dispatchEvent(OI),this._lastPosition.copy(this.object.position),this._lastZoom=this.object.zoom)):console.warn("THREE.TrackballControls: Unsupported camera type.")}reset(){this.state=zI,this.keyState=zI,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(OI),this._lastPosition.copy(this.object.position),this._lastZoom=this.object.zoom}_panCamera(){if(XI.copy(this._panEnd).sub(this._panStart),XI.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;XI.x*=e,XI.y*=t}XI.multiplyScalar(this._eye.length()*this.panSpeed),YI.copy(this._eye).cross(this.object.up).setLength(XI.x),YI.add(qI.copy(this.object.up).setLength(XI.y)),this.object.position.add(YI),this.target.add(YI),this.staticMoving?this._panStart.copy(this._panEnd):this._panStart.add(XI.subVectors(this._panEnd,this._panStart).multiplyScalar(this.dynamicDampingFactor))}}_rotateCamera(){tU.set(this._moveCurr.x-this._movePrev.x,this._moveCurr.y-this._movePrev.y,0);let e=tU.length();e?(this._eye.copy(this.object.position).sub(this.target),QI.copy(this._eye).normalize(),JI.copy(this.object.up).normalize(),eU.crossVectors(JI,QI).normalize(),JI.setLength(this._moveCurr.y-this._movePrev.y),eU.setLength(this._moveCurr.x-this._movePrev.x),tU.copy(JI.add(eU)),KI.crossVectors(tU,this._eye).normalize(),e*=this.rotateSpeed,ZI.setFromAxisAngle(KI,e),this._eye.applyQuaternion(ZI),this.object.up.applyQuaternion(ZI),this._lastAxis.copy(KI),this._lastAngle=e):!this.staticMoving&&this._lastAngle&&(this._lastAngle*=Math.sqrt(1-this.dynamicDampingFactor),this._eye.copy(this.object.position).sub(this.target),ZI.setFromAxisAngle(this._lastAxis,this._lastAngle),this._eye.applyQuaternion(ZI),this.object.up.applyQuaternion(ZI)),this._movePrev.copy(this._moveCurr)}_zoomCamera(){let e;this.state===WI?(e=this._touchZoomDistanceStart/this._touchZoomDistanceEnd,this._touchZoomDistanceStart=this._touchZoomDistanceEnd,this.object.isPerspectiveCamera?this._eye.multiplyScalar(e):this.object.isOrthographicCamera?(this.object.zoom=pn.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=pn.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 $I.set((e-this.screen.left)/this.screen.width,(t-this.screen.top)/this.screen.height),$I}_getMouseOnCircle(e,t){return $I.set((e-.5*this.screen.width-this.screen.left)/(.5*this.screen.width),(this.screen.height+2*(this.screen.top-t))/this.screen.width),$I}_addPointer(e){this._pointers.push(e)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;tthis.maxDistance*this.maxDistance&&(this.object.position.addVectors(this.target,this._eye.setLength(this.maxDistance)),this._zoomStart.copy(this._zoomEnd)),this._eye.lengthSq()Math.PI&&(n-=MU),r<-Math.PI?r+=MU:r>Math.PI&&(r-=MU),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(SU.setFromSpherical(this._spherical),SU.applyQuaternion(this._quatInverse),t.copy(this.target).add(SU),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=SU.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 gn(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 gn(this._mouse.x,this._mouse.y,0);r.unproject(this.object),this.object.position.sub(r).add(t),this.object.updateMatrixWorld(),e=SU.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):(bU.origin.copy(this.object.position),bU.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(bU.direction))DU||8*(1-this._lastQuaternion.dot(this.object.quaternion))>DU||this._lastTargetPosition.distanceToSquared(this.target)>DU)&&(this.dispatchEvent(_U),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0)}_getAutoRotationAngle(e){return null!==e?MU/60*this.autoRotateSpeed*e:MU/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){SU.setFromMatrixColumn(t,0),SU.multiplyScalar(-e),this._panOffset.add(SU)}_panUp(e,t){!0===this.screenSpacePanning?SU.setFromMatrixColumn(t,1):(SU.setFromMatrixColumn(t,0),SU.crossVectors(this.object.up,SU)),SU.multiplyScalar(e),this._panOffset.add(SU)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const r=this.object.position;SU.copy(r).sub(this.target);let i=SU.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(MU*this._rotateDelta.x/t.clientHeight),this._rotateUp(MU*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(MU*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(-MU*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(MU*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(-MU*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(MU*this._rotateDelta.x/t.clientHeight),this._rotateUp(MU*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;tqU||8*(1-this._lastQuaternion.dot(t.quaternion))>qU)&&(this.dispatchEvent(XU),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 ZU(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 QU(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 JU(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 eO(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 tO(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 nO(){!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 rO(e){!1!==this.enabled&&e.preventDefault()}const iO={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 sO{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 aO=new Pa(-1,1,1,-1,0,1);const oO=new class extends Ci{constructor(){super(),this.setAttribute("position",new xi([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new xi([0,2,0,0,2,0],2))}};class lO{constructor(e){this._mesh=new Vi(oO,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,aO)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}class uO extends sO{constructor(e,t="tDiffuse"){super(),this.textureID=t,this.uniforms=null,this.material=null,e instanceof qi?(this.uniforms=e.uniforms,this.material=e):e&&(this.uniforms=Xi.clone(e.uniforms),this.material=new qi({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 lO(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 cO extends sO{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 hO extends sO{constructor(){super(),this.needsSwap=!1}render(e){e.state.buffers.stencil.setLocked(!1),e.state.buffers.stencil.setTest(!1)}}class dO{constructor(e,t){if(this.renderer=e,this._pixelRatio=e.getPixelRatio(),void 0===t){const n=e.getSize(new fn);this._width=n.width,this._height=n.height,(t=new Fn(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:Ae})).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 uO(iO),this.copyPass.material.blending=0,this.clock=new ka}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;t1?n-1:0),i=1;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 wO={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 EO=/^#[a-fA-F0-9]{6}$/,AO=/^#[a-fA-F0-9]{8}$/,RO=/^#[a-fA-F0-9]{3}$/,CO=/^#[a-fA-F0-9]{4}$/,NO=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,PO=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,LO=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,DO=/^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 IO(e){if("string"!=typeof e)throw new xO(3);var t=function(e){if("string"!=typeof e)return e;var t=e.toLowerCase();return wO[t]?"#"+wO[t]:e}(e);if(t.match(EO))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(AO)){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(RO))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(CO)){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=NO.exec(t);if(i)return{red:parseInt(""+i[1],10),green:parseInt(""+i[2],10),blue:parseInt(""+i[3],10)};var s=PO.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=LO.exec(t);if(a){var o="rgb("+MO(parseInt(""+a[1],10),parseInt(""+a[2],10)/100,parseInt(""+a[3],10)/100)+")",l=NO.exec(o);if(!l)throw new xO(4,t,o);return{red:parseInt(""+l[1],10),green:parseInt(""+l[2],10),blue:parseInt(""+l[3],10)}}var u=DO.exec(t.substring(0,50));if(u){var c="rgb("+MO(parseInt(""+u[1],10),parseInt(""+u[2],10)/100,parseInt(""+u[3],10)/100)+")",h=NO.exec(c);if(!h)throw new xO(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 xO(5)}function UO(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=1?VO(e.red,e.green,e.blue):"rgba("+e.red+","+e.green+","+e.blue+","+e.alpha+")";throw new xO(7)}function HO(e){if("object"!=typeof e)throw new xO(8);if(function(e){return"number"==typeof e.red&&"number"==typeof e.green&&"number"==typeof e.blue&&"number"==typeof e.alpha}(e))return GO(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 VO(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?zO(e.hue,e.saturation,e.lightness):"rgba("+MO(e.hue,e.saturation,e.lightness)+","+e.alpha+")";throw new xO(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 zO(e.hue,e.saturation,e.lightness);throw new xO(1)}(e);throw new xO(8)}function jO(e,t,n){return function(){var r=n.concat(Array.prototype.slice.call(arguments));return r.length>=t?e.apply(this,r):jO(e,t,r)}}function WO(e){return jO(e,e.length,[])}function $O(e,t,n){return Math.max(e,Math.min(t,n))}WO(function(e,t){if("transparent"===t)return t;var n=UO(t);return HO(fO({},n,{hue:n.hue+parseFloat(e)}))}),WO(function(e,t){if("transparent"===t)return t;var n=UO(t);return HO(fO({},n,{lightness:$O(0,1,n.lightness-parseFloat(e))}))}),WO(function(e,t){if("transparent"===t)return t;var n=UO(t);return HO(fO({},n,{saturation:$O(0,1,n.saturation-parseFloat(e))}))}),WO(function(e,t){if("transparent"===t)return t;var n=UO(t);return HO(fO({},n,{lightness:$O(0,1,n.lightness+parseFloat(e))}))});var XO=WO(function(e,t,n){if("transparent"===t)return n;if("transparent"===n)return t;if(0===e)return n;var r=IO(t),i=fO({},r,{alpha:"number"==typeof r.alpha?r.alpha:1}),s=IO(n),a=fO({},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 GO({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))})}),qO=XO;var YO=WO(function(e,t){if("transparent"===t)return t;var n=IO(t);return GO(fO({},n,{alpha:$O(0,1,(100*("number"==typeof n.alpha?n.alpha:1)+100*parseFloat(e))/100)}))}),KO=YO;WO(function(e,t){if("transparent"===t)return t;var n=UO(t);return HO(fO({},n,{saturation:$O(0,1,n.saturation+parseFloat(e))}))}),WO(function(e,t){return"transparent"===t?t:HO(fO({},UO(t),{hue:parseFloat(e)}))}),WO(function(e,t){return"transparent"===t?t:HO(fO({},UO(t),{lightness:parseFloat(e)}))}),WO(function(e,t){return"transparent"===t?t:HO(fO({},UO(t),{saturation:parseFloat(e)}))}),WO(function(e,t){return"transparent"===t?t:qO(parseFloat(e),"rgb(0, 0, 0)",t)}),WO(function(e,t){return"transparent"===t?t:qO(parseFloat(e),"rgb(255, 255, 255)",t)}),WO(function(e,t){if("transparent"===t)return t;var n=IO(t);return GO(fO({},n,{alpha:$O(0,1,+(100*("number"==typeof n.alpha?n.alpha:1)-100*parseFloat(e)).toFixed(2)/100)}))});var ZO=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-ZO.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*ZO.Bounce.In(2*e):.5*ZO.Bounce.Out(2*e-1)+.5}}),generatePow:function(e){return void 0===e&&(e=4),e=(e=e1e4?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}}}}),QO=function(){return performance.now()},JO=function(){function e(){for(var e=[],t=0;t0;){this._tweensAddedDuringUpdate={};for(var r=0;r1?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}}},tF=function(){function e(){}return e.nextId=function(){return e._nextId++},e._nextId=0,e}(),nF=new JO,rF=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=ZO.Linear.None,this._interpolationFunction=eF.Linear,this._chainedTweens=[],this._onStartCallbackFired=!1,this._onEveryStartCallbackFired=!1,this._id=tF.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=nF,nF.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=QO()),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;hl)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=0&&"xmlns"!==(t=e.slice(0,n))&&(e=e.slice(n+1)),aF.hasOwnProperty(t)?{space:aF[t],local:e}:e}function lF(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===sF&&t.documentElement.namespaceURI===sF?t.createElement(e):t.createElementNS(n,e)}}function uF(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function cF(e){var t=oF(e);return(t.local?uF:lF)(t)}function hF(){}function dF(e){return null==e?hF:function(){return this.querySelector(e)}}function pF(){return[]}function fF(e){return function(){return function(e){return null==e?[]:Array.isArray(e)?e:Array.from(e)}(e.apply(this,arguments))}}function mF(e){return function(t){return t.matches(e)}}var gF=Array.prototype.find;function _F(){return this.firstElementChild}var vF=Array.prototype.filter;function yF(){return Array.from(this.children)}function bF(e){return new Array(e.length)}function xF(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}function TF(e,t,n,r,i,s){for(var a,o=0,l=t.length,u=s.length;ot?1:e>=t?0:NaN}function AF(e){return function(){this.removeAttribute(e)}}function RF(e){return function(){this.removeAttributeNS(e.space,e.local)}}function CF(e,t){return function(){this.setAttribute(e,t)}}function NF(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function PF(e,t){return function(){var n=t.apply(this,arguments);null==n?this.removeAttribute(e):this.setAttribute(e,n)}}function LF(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 DF(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function IF(e){return function(){this.style.removeProperty(e)}}function UF(e,t,n){return function(){this.style.setProperty(e,t,n)}}function OF(e,t,n){return function(){var r=t.apply(this,arguments);null==r?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function FF(e){return function(){delete this[e]}}function BF(e,t){return function(){this[e]=t}}function kF(e,t){return function(){var n=t.apply(this,arguments);null==n?delete this[e]:this[e]=n}}function zF(e){return e.trim().split(/^|\s+/)}function VF(e){return e.classList||new GF(e)}function GF(e){this._node=e,this._names=zF(e.getAttribute("class")||"")}function HF(e,t){for(var n=VF(e),r=-1,i=t.length;++r=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(e){return this._names.indexOf(e)>=0}};var hB=[null];function dB(e,t){this._groups=e,this._parents=t}dB.prototype={constructor:dB,select:function(e){"function"!=typeof e&&(e=dF(e));for(var t=this._groups,n=t.length,r=new Array(n),i=0;i=b&&(b=y+1);!(v=g[b])&&++b=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=EF);for(var n=this._groups,r=n.length,i=new Array(r),s=0;s1?this.each((null==t?IF:"function"==typeof t?OF:UF)(e,t,null==n?"":n)):function(e,t){return e.style.getPropertyValue(t)||DF(e).getComputedStyle(e,null).getPropertyValue(t)}(this.node(),e)},property:function(e,t){return arguments.length>1?this.each((null==t?FF:"function"==typeof t?kF:BF)(e,t)):this.node()[e]},classed:function(e,t){var n=zF(e+"");if(arguments.length<2){for(var r=VF(this.node()),i=-1,s=n.length;++i=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?oB:aB,r=0;ro&&_B.sort(bB),e=_B.shift(),o=_B.length,e.__d&&(n=void 0,r=void 0,i=(r=(t=e).__v).__e,s=[],a=[],t.__P&&((n=CB({},r)).__v=r.__v+1,fB.vnode&&fB.vnode(n),WB(t.__P,n,r,t.__n,t.__P.namespaceURI,32&r.__u?[i]:null,s,null==i?IB(r):i,!!(32&r.__u),a),n.__v=r.__v,n.__.__k[n.__i]=n,XB(s,n,a),r.__e=r.__=null,n.__e!=i&&UB(n)));FB.__r=0}function BB(e,t,n,r,i,s,a,o,l,u,c){var h,d,p,f,m,g,_,v=r&&r.__k||EB,y=t.length;for(l=kB(n,t,v,l,y),h=0;h0?a=e.__k[s]=PB(a.type,a.props,a.key,a.ref?a.ref:null,a.__v):e.__k[s]=a,l=s+d,a.__=e,a.__b=e.__b+1,o=null,-1!=(u=a.__i=VB(a,n,l,h))&&(h--,(o=n[u])&&(o.__u|=2)),null==o||null==o.__v?(-1==u&&(i>c?d--:il?d--:d++,a.__u|=4))):e.__k[s]=null;if(h)for(s=0;s(c?1:0))for(i=n-1,s=n+1;i>=0||s=0?i--:s++])&&!(2&u.__u)&&o==u.key&&l==u.type)return a;return-1}function GB(e,t,n){"-"==t[0]?e.setProperty(t,null==n?"":n):e[t]=null==n?"":"number"!=typeof n||AB.test(t)?n:n+"px"}function HB(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||GB(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||GB(e.style,t,n[t])}else if("o"==t[0]&&"n"==t[1])s=t!=(t=t.replace(xB,"$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=TB,e.addEventListener(t,s?MB:SB,s)):e.removeEventListener(t,s?MB:SB,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 jB(e){return function(t){if(this.l){var n=this.l[t.type+e];if(null==t.t)t.t=TB++;else if(t.t0?e:RB(e)?e.map(qB):CB({},e)}function YB(e,t,n,r,i,s,a,o,l){var u,c,h,d,p,f,m,g=n.props||wB,_=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;u2&&(a.children=arguments.length>3?pB.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 PB(e,a,r,i,null)}(LB,null,[e]),r||wB,wB,t.namespaceURI,r?null:t.firstChild?pB.call(t.childNodes):null,i,r?r.__e:t.firstChild,false,s),XB(i,e,s)}function ek(e,t,n){var r,i,s,a,o=CB({},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?pB.call(arguments,2):n),PB(e.type,o,r||e.key,i||e.ref,null)}function tk(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n2&&void 0!==arguments[2]?arguments[2]:{}).style,r=void 0===n?{}:n,i=function(e){return"string"==typeof e?new dB([[document.querySelector(e)]],[document.documentElement]):new dB([[e]],hB)}(!!e&&"object"===sk(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=ik(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 gB(ek(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,JB(ak(t),n)):e.tooltipEl.text("")}});function lk(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n0),h=!!n.morphAttributes.position,d=!!n.morphAttributes.normal,p=!!n.morphAttributes.color;let f=0;r.toneMapped&&(null!==C&&!0!==C.isXRRenderTarget||(f=w.toneMapping));const m=n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color,g=void 0!==m?m.length:0,_=ie.get(r),v=x.state.lights;if(!0===$&&(!0===X||e!==P)){const t=e===P&&r.id===N;ge.setState(r,e,t)}let y=!1;r.version===_.__version?_.needsLights&&_.lightsStateVersion!==v.state.version||_.outputColorSpace!==o||i.isBatchedMesh&&!1===_.batching?y=!0:i.isBatchedMesh||!0!==_.batching?i.isBatchedMesh&&!0===_.batchingColor&&null===i.colorTexture||i.isBatchedMesh&&!1===_.batchingColor&&null!==i.colorTexture||i.isInstancedMesh&&!1===_.instancing?y=!0:i.isInstancedMesh||!0!==_.instancing?i.isSkinnedMesh&&!1===_.skinning?y=!0:i.isSkinnedMesh||!0!==_.skinning?i.isInstancedMesh&&!0===_.instancingColor&&null===i.instanceColor||i.isInstancedMesh&&!1===_.instancingColor&&null!==i.instanceColor||i.isInstancedMesh&&!0===_.instancingMorph&&null===i.morphTexture||i.isInstancedMesh&&!1===_.instancingMorph&&null!==i.morphTexture||_.envMap!==l||!0===r.fog&&_.fog!==s?y=!0:void 0===_.numClippingPlanes||_.numClippingPlanes===ge.numPlanes&&_.numIntersection===ge.numIntersection?(_.vertexAlphas!==u||_.vertexTangents!==c||_.morphTargets!==h||_.morphNormals!==d||_.morphColors!==p||_.toneMapping!==f||_.morphTargetsCount!==g)&&(y=!0):y=!0:y=!0:y=!0:y=!0:(y=!0,_.__version=r.version);let b=_.currentProgram;!0===y&&(b=nt(r,t,i));let T=!1,S=!1,M=!1;const E=b.getUniforms(),A=_.uniforms;ne.useProgram(b.program)&&(T=!0,S=!0,M=!0);r.id!==N&&(N=r.id,S=!0);if(T||P!==e){ne.buffers.depth.getReversed()&&!0!==e.reversedDepth&&(e._reversedDepth=!0,e.updateProjectionMatrix()),E.setValue(Ie,"projectionMatrix",e.projectionMatrix),E.setValue(Ie,"viewMatrix",e.matrixWorldInverse);const t=E.map.cameraPosition;void 0!==t&&t.setValue(Ie,Y.setFromMatrixPosition(e.matrixWorld)),te.logarithmicDepthBuffer&&E.setValue(Ie,"logDepthBufFC",2/(Math.log(e.far+1)/Math.LN2)),(r.isMeshPhongMaterial||r.isMeshToonMaterial||r.isMeshLambertMaterial||r.isMeshBasicMaterial||r.isMeshStandardMaterial||r.isShaderMaterial)&&E.setValue(Ie,"isOrthographic",!0===e.isOrthographicCamera),P!==e&&(P=e,S=!0,M=!0)}_.needsLights&&(v.state.directionalShadowMap.length>0&&E.setValue(Ie,"directionalShadowMap",v.state.directionalShadowMap,se),v.state.spotShadowMap.length>0&&E.setValue(Ie,"spotShadowMap",v.state.spotShadowMap,se),v.state.pointShadowMap.length>0&&E.setValue(Ie,"pointShadowMap",v.state.pointShadowMap,se));if(i.isSkinnedMesh){E.setOptional(Ie,i,"bindMatrix"),E.setOptional(Ie,i,"bindMatrixInverse");const e=i.skeleton;e&&(null===e.boneTexture&&e.computeBoneTexture(),E.setValue(Ie,"boneTexture",e.boneTexture,se))}i.isBatchedMesh&&(E.setOptional(Ie,i,"batchingTexture"),E.setValue(Ie,"batchingTexture",i._matricesTexture,se),E.setOptional(Ie,i,"batchingIdTexture"),E.setValue(Ie,"batchingIdTexture",i._indirectTexture,se),E.setOptional(Ie,i,"batchingColorTexture"),null!==i._colorsTexture&&E.setValue(Ie,"batchingColorTexture",i._colorsTexture,se));const R=n.morphAttributes;void 0===R.position&&void 0===R.normal&&void 0===R.color||Te.update(i,n,b);(S||_.receiveShadow!==i.receiveShadow)&&(_.receiveShadow=i.receiveShadow,E.setValue(Ie,"receiveShadow",i.receiveShadow));r.isMeshGouraudMaterial&&null!==r.envMap&&(A.envMap.value=l,A.flipEnvMap.value=l.isCubeTexture&&!1===l.isRenderTargetTexture?-1:1);r.isMeshStandardMaterial&&null===r.envMap&&null!==t.environment&&(A.envMapIntensity.value=t.environmentIntensity);void 0!==A.dfgLUT&&(A.dfgLUT.value=(null===Gu&&(Gu=new ds(Vu,16,16,ze,Ae),Gu.name="DFG_LUT",Gu.minFilter=_e,Gu.magFilter=_e,Gu.wrapS=de,Gu.wrapT=de,Gu.generateMipmaps=!1,Gu.needsUpdate=!0),Gu));S&&(E.setValue(Ie,"toneMappingExposure",w.toneMappingExposure),_.needsLights&&(D=M,(L=A).ambientLightColor.needsUpdate=D,L.lightProbe.needsUpdate=D,L.directionalLights.needsUpdate=D,L.directionalLightShadows.needsUpdate=D,L.pointLights.needsUpdate=D,L.pointLightShadows.needsUpdate=D,L.spotLights.needsUpdate=D,L.spotLightShadows.needsUpdate=D,L.rectAreaLights.needsUpdate=D,L.hemisphereLights.needsUpdate=D),s&&!0===r.fog&&pe.refreshFogUniforms(A,s),pe.refreshMaterialUniforms(A,r,k,B,x.state.transmissionRenderTarget[e.id]),Bl.upload(Ie,rt(_),A,se));var L,D;r.isShaderMaterial&&!0===r.uniformsNeedUpdate&&(Bl.upload(Ie,rt(_),A,se),r.uniformsNeedUpdate=!1);r.isSpriteMaterial&&E.setValue(Ie,"center",i.center);if(E.setValue(Ie,"modelViewMatrix",i.modelViewMatrix),E.setValue(Ie,"normalMatrix",i.normalMatrix),E.setValue(Ie,"modelMatrix",i.matrixWorld),r.isShaderMaterial||r.isRawShaderMaterial){const e=r.uniformsGroups;for(let t=0,n=e.length;t{function n(){r.forEach(function(e){ie.get(e).currentProgram.isReady()&&r.delete(e)}),0!==r.size?setTimeout(n,10):t(e)}null!==ee.get("KHR_parallel_shader_compile")?n():setTimeout(n,10)})};let Xe=null;function qe(){Ke.stop()}function Ye(){Ke.start()}const Ke=new Ya;function Ze(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)x.pushLight(e),e.castShadow&&x.pushShadow(e);else if(e.isSprite){if(!e.frustumCulled||W.intersectsSprite(e)){r&&K.setFromMatrixPosition(e.matrixWorld).applyMatrix4(q);const t=ce.update(e),i=e.material;i.visible&&b.push(e,t,i,n,K.z,null)}}else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||W.intersectsObject(e))){const t=ce.update(e),i=e.material;if(r&&(void 0!==e.boundingSphere?(null===e.boundingSphere&&e.computeBoundingSphere(),K.copy(e.boundingSphere.center)):(null===t.boundingSphere&&t.computeBoundingSphere(),K.copy(t.boundingSphere.center)),K.applyMatrix4(e.matrixWorld).applyMatrix4(q)),Array.isArray(i)){const r=t.groups;for(let s=0,a=r.length;s0&&et(i,t,n),s.length>0&&et(s,t,n),a.length>0&&et(a,t,n),ne.buffers.depth.setTest(!0),ne.buffers.depth.setMask(!0),ne.buffers.color.setMask(!0),ne.setPolygonOffset(!1)}function Je(e,t,n,r){if(null!==(!0===n.isScene?n.overrideMaterial:null))return;if(void 0===x.state.transmissionRenderTarget[r.id]){const e=ee.has("EXT_color_buffer_half_float")||ee.has("EXT_color_buffer_float");x.state.transmissionRenderTarget[r.id]=new Fn(1,1,{generateMipmaps:!0,type:e?Ae:be,minFilter:ye,samples:te.samples,stencilBuffer:i,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Mn.workingColorSpace})}const s=x.state.transmissionRenderTarget[r.id],a=r.viewport||L;s.setSize(a.z*w.transmissionResolutionScale,a.w*w.transmissionResolutionScale);const o=w.getRenderTarget(),l=w.getActiveCubeFace(),u=w.getActiveMipmapLevel();w.setRenderTarget(s),w.getClearColor(U),O=w.getClearAlpha(),O<1&&w.setClearColor(16777215,.5),w.clear(),Q&&xe.render(n);const c=w.toneMapping;w.toneMapping=0;const h=r.viewport;if(void 0!==r.viewport&&(r.viewport=void 0),x.setupLightsView(r),!0===$&&ge.setGlobalState(w.clippingPlanes,r),et(e,n,r),se.updateMultisampleRenderTarget(s),se.updateRenderTargetMipmap(s),!1===ee.has("WEBGL_multisampled_render_to_texture")){let e=!1;for(let i=0,s=t.length;i0)for(let t=0,s=i.length;t0&&Je(n,r,e,t),Q&&xe.render(e),Qe(b,e,t)}null!==C&&0===R&&(se.updateMultisampleRenderTarget(C),se.updateRenderTargetMipmap(C)),r&&M.end(w),!0===e.isScene&&e.onAfterRender(w,e,t),Le.resetDefaultState(),N=-1,P=null,S.pop(),S.length>0?(x=S[S.length-1],!0===$&&ge.setGlobalState(w.clippingPlanes,x.state.camera)):x=null,T.pop(),b=T.length>0?T[T.length-1]:null},this.getActiveCubeFace=function(){return A},this.getActiveMipmapLevel=function(){return R},this.getRenderTarget=function(){return C},this.setRenderTargetTextures=function(e,t,n){const r=ie.get(e);r.__autoAllocateDepthBuffer=!1===e.resolveDepthBuffer,!1===r.__autoAllocateDepthBuffer&&(r.__useRenderToTexture=!1),ie.get(e.texture).__webglTexture=t,ie.get(e.depthTexture).__webglTexture=r.__autoAllocateDepthBuffer?void 0:n,r.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(e,t){const n=ie.get(e);n.__webglFramebuffer=t,n.__useDefaultFramebuffer=void 0===t};const st=Ie.createFramebuffer();this.setRenderTarget=function(e,t=0,n=0){C=e,A=t,R=n;let r=null,i=!1,s=!1;if(e){const a=ie.get(e);if(void 0!==a.__useDefaultFramebuffer)return ne.bindFramebuffer(Ie.FRAMEBUFFER,a.__webglFramebuffer),L.copy(e.viewport),D.copy(e.scissor),I=e.scissorTest,ne.viewport(L),ne.scissor(D),ne.setScissorTest(I),void(N=-1);if(void 0===a.__webglFramebuffer)se.setupRenderTarget(e);else if(a.__hasExternalTextures)se.rebindTextures(e,ie.get(e.texture).__webglTexture,ie.get(e.depthTexture).__webglTexture);else if(e.depthBuffer){const t=e.depthTexture;if(a.__boundDepthTexture!==t){if(null!==t&&ie.has(t)&&(e.width!==t.image.width||e.height!==t.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");se.setupDepthRenderbuffer(e)}}const o=e.texture;(o.isData3DTexture||o.isDataArrayTexture||o.isCompressedArrayTexture)&&(s=!0);const l=ie.get(e).__webglFramebuffer;e.isWebGLCubeRenderTarget?(r=Array.isArray(l[t])?l[t][n]:l[t],i=!0):r=e.samples>0&&!1===se.useMultisampledRTT(e)?ie.get(e).__webglMultisampledFramebuffer:Array.isArray(l)?l[n]:l,L.copy(e.viewport),D.copy(e.scissor),I=e.scissorTest}else L.copy(G).multiplyScalar(k).floor(),D.copy(H).multiplyScalar(k).floor(),I=j;0!==n&&(r=st);if(ne.bindFramebuffer(Ie.FRAMEBUFFER,r)&&ne.drawBuffers(e,r),ne.viewport(L),ne.scissor(D),ne.setScissorTest(I),i){const r=ie.get(e.texture);Ie.framebufferTexture2D(Ie.FRAMEBUFFER,Ie.COLOR_ATTACHMENT0,Ie.TEXTURE_CUBE_MAP_POSITIVE_X+t,r.__webglTexture,n)}else if(s){const r=t;for(let t=0;t=0&&t<=e.width-r&&n>=0&&n<=e.height-i&&(e.textures.length>1&&Ie.readBuffer(Ie.COLOR_ATTACHMENT0+o),Ie.readPixels(t,n,r,i,Pe.convert(l),Pe.convert(u),s))}finally{const e=null!==C?ie.get(C).__webglFramebuffer:null;ne.bindFramebuffer(Ie.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=ie.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){ne.bindFramebuffer(Ie.FRAMEBUFFER,l);const a=e.textures[o],u=a.format,c=a.type;if(!te.textureFormatReadable(u))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!te.textureTypeReadable(c))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const h=Ie.createBuffer();Ie.bindBuffer(Ie.PIXEL_PACK_BUFFER,h),Ie.bufferData(Ie.PIXEL_PACK_BUFFER,s.byteLength,Ie.STREAM_READ),e.textures.length>1&&Ie.readBuffer(Ie.COLOR_ATTACHMENT0+o),Ie.readPixels(t,n,r,i,Pe.convert(u),Pe.convert(c),0);const d=null!==C?ie.get(C).__webglFramebuffer:null;ne.bindFramebuffer(Ie.FRAMEBUFFER,d);const p=Ie.fenceSync(Ie.SYNC_GPU_COMMANDS_COMPLETE,0);return Ie.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)})}(Ie,p,4),Ie.bindBuffer(Ie.PIXEL_PACK_BUFFER,h),Ie.getBufferSubData(Ie.PIXEL_PACK_BUFFER,0,s),Ie.deleteBuffer(h),Ie.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;se.setTexture2D(e,0),Ie.copyTexSubImage2D(Ie.TEXTURE_2D,n,0,0,a,o,i,s),ne.unbindTexture()};const at=Ie.createFramebuffer(),ot=Ie.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?(en("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=Pe.convert(t.format),_=Pe.convert(t.type);let v;t.isData3DTexture?(se.setTexture3D(t,0),v=Ie.TEXTURE_3D):t.isDataArrayTexture||t.isCompressedArrayTexture?(se.setTexture2DArray(t,0),v=Ie.TEXTURE_2D_ARRAY):(se.setTexture2D(t,0),v=Ie.TEXTURE_2D),Ie.pixelStorei(Ie.UNPACK_FLIP_Y_WEBGL,t.flipY),Ie.pixelStorei(Ie.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),Ie.pixelStorei(Ie.UNPACK_ALIGNMENT,t.unpackAlignment);const y=Ie.getParameter(Ie.UNPACK_ROW_LENGTH),b=Ie.getParameter(Ie.UNPACK_IMAGE_HEIGHT),x=Ie.getParameter(Ie.UNPACK_SKIP_PIXELS),T=Ie.getParameter(Ie.UNPACK_SKIP_ROWS),S=Ie.getParameter(Ie.UNPACK_SKIP_IMAGES);Ie.pixelStorei(Ie.UNPACK_ROW_LENGTH,m.width),Ie.pixelStorei(Ie.UNPACK_IMAGE_HEIGHT,m.height),Ie.pixelStorei(Ie.UNPACK_SKIP_PIXELS,u),Ie.pixelStorei(Ie.UNPACK_SKIP_ROWS,c),Ie.pixelStorei(Ie.UNPACK_SKIP_IMAGES,h);const M=e.isDataArrayTexture||e.isData3DTexture,w=t.isDataArrayTexture||t.isData3DTexture;if(e.isDepthTexture){const n=ie.get(e),r=ie.get(t),m=ie.get(n.__renderTarget),g=ie.get(r.__renderTarget);ne.bindFramebuffer(Ie.READ_FRAMEBUFFER,m.__webglFramebuffer),ne.bindFramebuffer(Ie.DRAW_FRAMEBUFFER,g.__webglFramebuffer);for(let n=0;n=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&&Dd(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 rF(o).to(s,r).easing(ZO.Quadratic.Out).onUpdate(u).start()),e.tweenGroup.add(new rF(l).to(a,r/3).easing(ZO.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 pk.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 pk.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;s2&&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 pk.Vector3(0,0,0),a=2*Math.max.apply(Math,hk(Object.entries(t).map(function(e){var t=ck(e,2),n=t[0],r=t[1];return Math.max.apply(Math,hk(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 pk.Box3(new pk.Vector3(0,0,0),new pk.Vector3(0,0,0)),r=e.objects.filter(t);return r.length?(r.forEach(function(e){return n.expandByObject(e)}),Object.assign.apply(Object,hk(["x","y","z"].map(function(e){return uk({},e,[n.min[e],n.max[e]])})))):null},getScreenCoords:function(e,t,n,r){var i=new pk.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 pk.Vector2(t/e.width*2-1,-n/e.height*2+1),s=new pk.Raycaster;return s.setFromCamera(i,e.camera),Object.assign({},s.ray.at(r,new pk.Vector3))},intersectingObjects:function(e,t,n){var r=new pk.Vector2(t/e.width*2-1,-n/e.height*2+1),i=new pk.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 pk.Scene,camera:new pk.PerspectiveCamera,clock:new pk.Clock,tweenGroup:new JO,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 ok(t.container),t.pointerPos=new pk.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)&&("mouse"===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?UI:pk.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 dO(t.renderer),t.postProcessingComposer.addPass(new pO(t.scene,t.camera)),t.controls=new{trackball:nU,orbit:IU,fly:KU}[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(hk(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 pk.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(hk(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(hk(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(hk(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 pk.SphereGeometry(e.skyRadius)),t.hasOwnProperty("backgroundColor")){var c=IO(e.backgroundColor).alpha;void 0===c&&(c=1),e.renderer.setClearColor(new pk.Color(KO(1,e.backgroundColor)),c)}function h(){e.loadComplete=e.scene.visible=!0}t.hasOwnProperty("backgroundImageUrl")&&(e.backgroundImageUrl?(new pk.TextureLoader).load(e.backgroundImageUrl,function(t){t.colorSpace=pk.SRGBColorSpace,e.skysphere.material=new pk.MeshBasicMaterial({map:t,side:pk.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 mk(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n1?i-1:0),a=1;a3?i-3:0),a=3;a1?"Invalid arguments supplied to oneOf, expected an array, got "+arguments.length+" arguments. A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z]).":"Invalid argument supplied to oneOf, expected an array."),a;return f(function(e,n,r,i,s){for(var a=e[n],o=0;o0?", expected one of type ["+l.join(", ")+"]":"")+".")})},shape:function(e){return f(function(t,n,i,s,a){var o=t[n],l=v(o);if("object"!==l)return new p("Invalid "+s+" `"+a+"` of type `"+l+"` supplied to `"+i+"`, expected `object`.");for(var u in e){var c=e[u];if("function"!=typeof c)return g(i,s,a,u,y(c));var h=c(o,u,i,s,a+"."+u,r);if(h)return h}return null})},exact:function(e){return f(function(t,s,a,o,l){var u=t[s],c=v(u);if("object"!==c)return new p("Invalid "+o+" `"+l+"` of type `"+c+"` supplied to `"+a+"`, expected `object`.");var h=n({},t[s],e);for(var d in h){var f=e[d];if(i(e,d)&&"function"!=typeof f)return g(a,o,l,d,y(f));if(!f)return new p("Invalid "+o+" `"+l+"` key `"+d+"` supplied to `"+a+"`.\nBad object: "+JSON.stringify(t[s],null," ")+"\nValid keys: "+JSON.stringify(Object.keys(e),null," "));var m=f(u,d,a,o,l+"."+d,r);if(m)return m}return null})}};function d(e,t){return e===t?0!==e||1/e==1/t:e!=e&&t!=t}function p(e,t){this.message=e,this.data=t&&"object"==typeof t?t:{},this.stack=""}function f(t){var n={},i=0;function s(s,a,o,u,h,d,f){if(u=u||c,d=d||o,f!==r){if(l){var m=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use `PropTypes.checkPropTypes()` to call them. Read more at http://fb.me/use-check-prop-types");throw m.name="Invariant Violation",m}if("undefined"!=typeof console){var g=u+":"+o;!n[g]&&i<3&&(e("You are manually calling a React.PropTypes validation function for the `"+d+"` prop on `"+u+"`. This is deprecated and will throw in the standalone `prop-types` package. You may be seeing this warning due to a third-party PropTypes library. See https://fb.me/react-warning-dont-call-proptypes for details."),n[g]=!0,i++)}}return null==a[o]?s?null===a[o]?new p("The "+h+" `"+d+"` is marked as required in `"+u+"`, but its value is `null`."):new p("The "+h+" `"+d+"` is marked as required in `"+u+"`, but its value is `undefined`."):null:t(a,o,u,h,d)}var a=s.bind(null,!1);return a.isRequired=s.bind(null,!0),a}function m(e){return f(function(t,n,r,i,s,a){var o=t[n];return v(o)!==e?new p("Invalid "+i+" `"+s+"` of type `"+y(o)+"` supplied to `"+r+"`, expected `"+e+"`.",{expectedType:e}):null})}function g(e,t,n,r,i){return new p((e||"React class")+": "+t+" type `"+n+"."+r+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+i+"`.")}function _(e){switch(typeof e){case"number":case"string":case"undefined":return!0;case"boolean":return!e;case"object":if(Array.isArray(e))return e.every(_);if(null===e||o(e))return!0;var t=function(e){var t=e&&(u&&e[u]||e["@@iterator"]);if("function"==typeof t)return t}(e);if(!t)return!1;var n,r=t.call(e);if(t!==e.entries){for(;!(n=r.next()).done;)if(!_(n.value))return!1}else for(;!(n=r.next()).done;){var i=n.value;if(i&&!_(i[1]))return!1}return!0;default:return!1}}function v(e){var t=typeof e;return Array.isArray(e)?"array":e instanceof RegExp?"object":function(e,t){return"symbol"===e||!!t&&("Symbol"===t["@@toStringTag"]||"function"==typeof Symbol&&t instanceof Symbol)}(t,e)?"symbol":t}function y(e){if(null==e)return""+e;var t=v(e);if("object"===t){if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return t}function b(e){var t=y(e);switch(t){case"array":case"object":return"an "+t;case"boolean":case"date":case"regexp":return"a "+t;default:return t}}return p.prototype=Error.prototype,h.checkPropTypes=s,h.resetWarningCache=s.resetWarningCache,h.PropTypes=h,h},zk}function Qk(){if(Gk)return Hk.exports;Gk=1;var e=$k();return Hk.exports=Zk()(e.isElement,true),Hk.exports}var Jk=Sh(Qk());const ez={width:Jk.number,height:Jk.number,graphData:Jk.shape({nodes:Jk.arrayOf(Jk.object).isRequired,links:Jk.arrayOf(Jk.object).isRequired}),backgroundColor:Jk.string,nodeRelSize:Jk.number,nodeId:Jk.string,nodeLabel:Jk.oneOfType([Jk.string,Jk.func]),nodeVal:Jk.oneOfType([Jk.number,Jk.string,Jk.func]),nodeVisibility:Jk.oneOfType([Jk.bool,Jk.string,Jk.func]),nodeColor:Jk.oneOfType([Jk.string,Jk.func]),nodeAutoColorBy:Jk.oneOfType([Jk.string,Jk.func]),onNodeHover:Jk.func,onNodeClick:Jk.func,linkSource:Jk.string,linkTarget:Jk.string,linkLabel:Jk.oneOfType([Jk.string,Jk.func]),linkVisibility:Jk.oneOfType([Jk.bool,Jk.string,Jk.func]),linkColor:Jk.oneOfType([Jk.string,Jk.func]),linkAutoColorBy:Jk.oneOfType([Jk.string,Jk.func]),linkWidth:Jk.oneOfType([Jk.number,Jk.string,Jk.func]),linkCurvature:Jk.oneOfType([Jk.number,Jk.string,Jk.func]),linkDirectionalArrowLength:Jk.oneOfType([Jk.number,Jk.string,Jk.func]),linkDirectionalArrowColor:Jk.oneOfType([Jk.string,Jk.func]),linkDirectionalArrowRelPos:Jk.oneOfType([Jk.number,Jk.string,Jk.func]),linkDirectionalParticles:Jk.oneOfType([Jk.number,Jk.string,Jk.func]),linkDirectionalParticleSpeed:Jk.oneOfType([Jk.number,Jk.string,Jk.func]),linkDirectionalParticleOffset:Jk.oneOfType([Jk.number,Jk.string,Jk.func]),linkDirectionalParticleWidth:Jk.oneOfType([Jk.number,Jk.string,Jk.func]),linkDirectionalParticleColor:Jk.oneOfType([Jk.string,Jk.func]),onLinkHover:Jk.func,onLinkClick:Jk.func,dagMode:Jk.oneOf(["td","bu","lr","rl","zin","zout","radialin","radialout"]),dagLevelDistance:Jk.number,dagNodeFilter:Jk.func,onDagError:Jk.func,d3AlphaMin:Jk.number,d3AlphaDecay:Jk.number,d3VelocityDecay:Jk.number,warmupTicks:Jk.number,cooldownTicks:Jk.number,cooldownTime:Jk.number,onEngineTick:Jk.func,onEngineStop:Jk.func,getGraphBbox:Jk.func},tz={zoomToFit:Jk.func,onNodeRightClick:Jk.func,onNodeDrag:Jk.func,onNodeDragEnd:Jk.func,onLinkRightClick:Jk.func,linkHoverPrecision:Jk.number,onBackgroundClick:Jk.func,onBackgroundRightClick:Jk.func,showPointerCursor:Jk.oneOfType([Jk.bool,Jk.func]),enablePointerInteraction:Jk.bool,enableNodeDrag:Jk.bool},nz={showNavInfo:Jk.bool,nodeOpacity:Jk.number,nodeResolution:Jk.number,nodeThreeObject:Jk.oneOfType([Jk.object,Jk.string,Jk.func]),nodeThreeObjectExtend:Jk.oneOfType([Jk.bool,Jk.string,Jk.func]),nodePositionUpdate:Jk.func,linkOpacity:Jk.number,linkResolution:Jk.number,linkCurveRotation:Jk.oneOfType([Jk.number,Jk.string,Jk.func]),linkMaterial:Jk.oneOfType([Jk.object,Jk.string,Jk.func]),linkThreeObject:Jk.oneOfType([Jk.object,Jk.string,Jk.func]),linkThreeObjectExtend:Jk.oneOfType([Jk.bool,Jk.string,Jk.func]),linkPositionUpdate:Jk.func,linkDirectionalArrowResolution:Jk.number,linkDirectionalParticleResolution:Jk.number,linkDirectionalParticleThreeObject:Jk.oneOfType([Jk.object,Jk.string,Jk.func]),forceEngine:Jk.oneOf(["d3","ngraph"]),ngraphPhysics:Jk.object,numDimensions:Jk.oneOf([1,2,3])};Object.assign({},ez,tz,{linkLineDash:Jk.oneOfType([Jk.arrayOf(Jk.number),Jk.string,Jk.func]),nodeCanvasObjectMode:Jk.oneOfType([Jk.string,Jk.func]),nodeCanvasObject:Jk.func,nodePointerAreaPaint:Jk.func,linkCanvasObjectMode:Jk.oneOfType([Jk.string,Jk.func]),linkCanvasObject:Jk.func,linkPointerAreaPaint:Jk.func,linkDirectionalParticleCanvasObject:Jk.func,autoPauseRedraw:Jk.bool,minZoom:Jk.number,maxZoom:Jk.number,enableZoomInteraction:Jk.oneOfType([Jk.bool,Jk.func]),enablePanInteraction:Jk.oneOfType([Jk.bool,Jk.func]),onZoom:Jk.func,onZoomEnd:Jk.func,onRenderFramePre:Jk.func,onRenderFramePost:Jk.func});const rz=Object.assign({},ez,tz,nz,{enableNavigationControls:Jk.bool,controlType:Jk.oneOf(["trackball","orbit","fly"]),rendererConfig:Jk.object,extraRenderers:Jk.arrayOf(Jk.shape({render:Jk.func.isRequired}))});Object.assign({},ez,nz,{nodeDesc:Jk.oneOfType([Jk.string,Jk.func]),linkDesc:Jk.oneOfType([Jk.string,Jk.func])}),Object.assign({},ez,nz,{markerAttrs:Jk.object,yOffset:Jk.number,glScale:Jk.number});const iz=function(i){var s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=s.wrapperElementType,o=void 0===a?"div":a,u=s.nodeMapper,h=void 0===u?function(e){return e}:u,d=s.methodNames,p=void 0===d?[]:d,f=s.initPropNames,m=void 0===f?[]:f;return e.forwardRef(function(s,a){var u=e.useRef(),d=e.useMemo(function(){var e=Object.fromEntries(m.filter(function(e){return s.hasOwnProperty(e)}).map(function(e){return[e,s[e]]}));return i(e)},[]);c(function(){d(h(u.current))},e.useLayoutEffect),c(function(){return d._destructor instanceof Function?d._destructor:void 0});var f,g,_,v=e.useCallback(function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r