import{c as Cv,f as Nv,D as Pv}from"./data-bind-mapper-D9QKwI5o.js";import{o as Dv,s as Lv,i as Df,h as gt,e as Uv,g as Fv,b as Iv,c as Bv,f as Ov,k as kv,m as Gv,l as lx}from"./Paired-C4wB-ooD.js";import{p as Vv,c as zv}from"./polished.esm-BeKV07fA.js";import{i as Hv,G as Wv,T as um,E as hm}from"./float-tooltip-COGhpFke.js";import"./_commonjsHelpers-Cpj98o6Y.js";/** * @license * Copyright 2010-2026 Three.js Authors * SPDX-License-Identifier: MIT */const po="184",Ln={ROTATE:0,DOLLY:1,PAN:2},ks={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},cx=0,Qd=1,ux=2,$v=0,Yo=1,hx=2,fs=3,ni=0,Pt=1,wn=2,Cn=0,Jn=1,hr=2,dr=3,fr=4,Jr=5,dx=6,Wn=100,Lf=101,Uf=102,fx=103,px=104,Us=200,Ff=201,If=202,Bf=203,Ul=204,Fl=205,Of=206,kf=207,Gf=208,Vf=209,zf=210,Xv=211,qv=212,jv=213,Yv=214,Il=0,Bl=1,Ol=2,Ar=3,kl=4,Gl=5,Vl=6,zl=7,nc=0,mx=1,gx=2,Un=0,Hf=1,Wf=2,$f=3,Xf=4,_x=5,qf=6,jf=7,Yf=300,Xi=301,_s=302,Ko=303,Zo=304,so=306,ro=1e3,ai=1001,oo=1002,bt=1003,Kf=1004,Gs=1005,Ut=1006,Qo=1007,li=1008,$t=1009,_r=1010,xr=1011,Ci=1012,Sn=1013,wt=1014,Zt=1015,en=1016,ic=1017,sc=1018,ui=1020,rc=35902,oc=35899,Yu=1021,Ba=1022,an=1023,Nn=1026,$n=1027,Oa=1028,mo=1029,Fn=1030,go=1031,xx=1032,ka=1033,yr=33776,vr=33777,Sr=33778,br=33779,Hl=35840,Wl=35841,$l=35842,Xl=35843,oa=36196,aa=37492,la=37496,ca=37488,ua=37489,Rr=37490,ha=37491,da=37808,fa=37809,pa=37810,ma=37811,ga=37812,_a=37813,xa=37814,ya=37815,va=37816,Sa=37817,ba=37818,Ta=37819,Ma=37820,Ea=37821,Aa=36492,Jd=36494,ef=36495,Ra=36283,wa=36284,wr=36285,Ca=36286,Kv=3200,Wi=0,yx=1,ri="",Qn="srgb",ql="srgb-linear",Na="linear",Ee="srgb",vh="",vx="rg",Zv="ga",Qv=0,$r=7680,Jv=7681,eS=7682,tS=7683,nS=34055,iS=34056,sS=5386,rS=512,oS=513,aS=514,lS=515,cS=516,uS=517,hS=518,tf=519,Zf=512,Ku=513,Qf=514,Dr=515,jl=516,Jf=517,$s=518,ep=519,Pa=35044,Nu=35048,dm="300 es",ti=2e3,xs=2001,ps={COMPUTE:"compute",RENDER:"render"},_o={TEXTURE_COMPARE:"depthTextureCompare"};function dS(r){for(let e=r.length-1;e>=0;--e)if(r[e]>=65535)return!0;return!1}function Pu(r){return ArrayBuffer.isView(r)&&!(r instanceof DataView)}function Yl(r){return document.createElementNS("http://www.w3.org/1999/xhtml",r)}function Sx(){const r=Yl("canvas");return r.style.display="block",r}const fm={};function Kl(...r){const e="THREE."+r.shift();console.log(e,...r)}function bx(r){const e=r[0];if(typeof e=="string"&&e.startsWith("TSL:")){const t=r[1];t&&t.isStackTrace?r[0]+=" "+t.getLocation():r[1]='Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'}return r}function ee(...r){r=bx(r);const e="THREE."+r.shift();{const t=r[0];t&&t.isStackTrace?console.warn(t.getError(e)):console.warn(e,...r)}}function ne(...r){r=bx(r);const e="THREE."+r.shift();{const t=r[0];t&&t.isStackTrace?console.error(t.getError(e)):console.error(e,...r)}}function Yt(...r){const e=r.join(" ");e in fm||(fm[e]=!0,ee(...r))}function Tx(){return typeof self<"u"&&typeof self.scheduler<"u"&&typeof self.scheduler.yield<"u"?self.scheduler.yield():new Promise(r=>{requestAnimationFrame(r)})}function fS(r,e,t){return new Promise(function(n,i){function s(){switch(r.clientWaitSync(e,r.SYNC_FLUSH_COMMANDS_BIT,0)){case r.WAIT_FAILED:i();break;case r.TIMEOUT_EXPIRED:setTimeout(s,t);break;default:n()}}setTimeout(s,t)})}const tp={[Il]:Bl,[Ol]:Vl,[kl]:zl,[Ar]:Gl,[Bl]:Il,[Vl]:Ol,[zl]:kl,[Gl]:Ar};class Ii{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){const n=this._listeners;return n===void 0?!1:n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){const n=this._listeners;if(n===void 0)return;const i=n[e];if(i!==void 0){const s=i.indexOf(t);s!==-1&&i.splice(s,1)}}dispatchEvent(e){const t=this._listeners;if(t===void 0)return;const n=t[e.type];if(n!==void 0){e.target=this;const i=n.slice(0);for(let s=0,o=i.length;s>8&255]+Gn[r>>16&255]+Gn[r>>24&255]+"-"+Gn[e&255]+Gn[e>>8&255]+"-"+Gn[e>>16&15|64]+Gn[e>>24&255]+"-"+Gn[t&63|128]+Gn[t>>8&255]+"-"+Gn[t>>16&255]+Gn[t>>24&255]+Gn[n&255]+Gn[n>>8&255]+Gn[n>>16&255]+Gn[n>>24&255]).toLowerCase()}function ot(r,e,t){return Math.max(e,Math.min(t,r))}function np(r,e){return(r%e+e)%e}function pS(r,e,t,n,i){return n+(r-e)*(i-n)/(t-e)}function mS(r,e,t){return r!==e?(t-r)/(e-r):0}function bl(r,e,t){return(1-t)*r+t*e}function gS(r,e,t,n){return bl(r,e,1-Math.exp(-t*n))}function _S(r,e=1){return e-Math.abs(np(r,e*2)-e)}function xS(r,e,t){return r<=e?0:r>=t?1:(r=(r-e)/(t-e),r*r*(3-2*r))}function yS(r,e,t){return r<=e?0:r>=t?1:(r=(r-e)/(t-e),r*r*r*(r*(r*6-15)+10))}function vS(r,e){return r+Math.floor(Math.random()*(e-r+1))}function SS(r,e){return r+Math.random()*(e-r)}function bS(r){return r*(.5-Math.random())}function TS(r){r!==void 0&&(pm=r);let e=pm+=1831565813;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}function MS(r){return r*Sl}function ES(r){return r*ao}function AS(r){return(r&r-1)===0&&r!==0}function RS(r){return Math.pow(2,Math.ceil(Math.log(r)/Math.LN2))}function wS(r){return Math.pow(2,Math.floor(Math.log(r)/Math.LN2))}function CS(r,e,t,n,i){const s=Math.cos,o=Math.sin,a=s(t/2),l=o(t/2),c=s((e+n)/2),u=o((e+n)/2),h=s((e-n)/2),d=o((e-n)/2),f=s((n-e)/2),p=o((n-e)/2);switch(i){case"XYX":r.set(a*u,l*h,l*d,a*c);break;case"YZY":r.set(l*d,a*u,l*h,a*c);break;case"ZXZ":r.set(l*h,l*d,a*u,a*c);break;case"XZX":r.set(a*u,l*p,l*f,a*c);break;case"YXY":r.set(l*f,a*u,l*p,a*c);break;case"ZYZ":r.set(l*p,l*f,a*u,a*c);break;default:ee("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+i)}}function ei(r,e){switch(e.constructor){case Float32Array:return r;case Uint32Array:return r/4294967295;case Uint16Array:return r/65535;case Uint8Array:return r/255;case Int32Array:return Math.max(r/2147483647,-1);case Int16Array:return Math.max(r/32767,-1);case Int8Array:return Math.max(r/127,-1);default:throw new Error("Invalid component type.")}}function rt(r,e){switch(e.constructor){case Float32Array:return r;case Uint32Array:return Math.round(r*4294967295);case Uint16Array:return Math.round(r*65535);case Uint8Array:return Math.round(r*255);case Int32Array:return Math.round(r*2147483647);case Int16Array:return Math.round(r*32767);case Int8Array:return Math.round(r*127);default:throw new Error("Invalid component type.")}}const Du={DEG2RAD:Sl,RAD2DEG:ao,generateUUID:Vs,clamp:ot,euclideanModulo:np,mapLinear:pS,inverseLerp:mS,lerp:bl,damp:gS,pingpong:_S,smoothstep:xS,smootherstep:yS,randInt:vS,randFloat:SS,randFloatSpread:bS,seededRandom:TS,degToRad:MS,radToDeg:ES,isPowerOfTwo:AS,ceilPowerOfTwo:RS,floorPowerOfTwo:wS,setQuaternionFromProperEuler:CS,normalize:rt,denormalize:ei},Zp=class Zp{constructor(e=0,t=0){this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,n=this.y,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6],this.y=i[1]*t+i[4]*n+i[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=ot(this.x,e.x,t.x),this.y=ot(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=ot(this.x,e,t),this.y=ot(this.y,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(ot(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(t===0)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(ot(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),i=Math.sin(t),s=this.x-e.x,o=this.y-e.y;return this.x=s*n-o*i+e.x,this.y=s*i+o*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}};Zp.prototype.isVector2=!0;let de=Zp;class Li{constructor(e=0,t=0,n=0,i=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=i}static slerpFlat(e,t,n,i,s,o,a){let l=n[i+0],c=n[i+1],u=n[i+2],h=n[i+3],d=s[o+0],f=s[o+1],p=s[o+2],g=s[o+3];if(h!==g||l!==d||c!==f||u!==p){let m=l*d+c*f+u*p+h*g;m<0&&(d=-d,f=-f,p=-p,g=-g,m=-m);let _=1-a;if(m<.9995){const x=Math.acos(m),v=Math.sin(x);_=Math.sin(_*x)/v,a=Math.sin(a*x)/v,l=l*_+d*a,c=c*_+f*a,u=u*_+p*a,h=h*_+g*a}else{l=l*_+d*a,c=c*_+f*a,u=u*_+p*a,h=h*_+g*a;const x=1/Math.sqrt(l*l+c*c+u*u+h*h);l*=x,c*=x,u*=x,h*=x}}e[t]=l,e[t+1]=c,e[t+2]=u,e[t+3]=h}static multiplyQuaternionsFlat(e,t,n,i,s,o){const a=n[i],l=n[i+1],c=n[i+2],u=n[i+3],h=s[o],d=s[o+1],f=s[o+2],p=s[o+3];return e[t]=a*p+u*h+l*f-c*d,e[t+1]=l*p+u*d+c*h-a*f,e[t+2]=c*p+u*f+a*d-l*h,e[t+3]=u*p-a*h-l*d-c*f,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,i){return this._x=e,this._y=t,this._z=n,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const n=e._x,i=e._y,s=e._z,o=e._order,a=Math.cos,l=Math.sin,c=a(n/2),u=a(i/2),h=a(s/2),d=l(n/2),f=l(i/2),p=l(s/2);switch(o){case"XYZ":this._x=d*u*h+c*f*p,this._y=c*f*h-d*u*p,this._z=c*u*p+d*f*h,this._w=c*u*h-d*f*p;break;case"YXZ":this._x=d*u*h+c*f*p,this._y=c*f*h-d*u*p,this._z=c*u*p-d*f*h,this._w=c*u*h+d*f*p;break;case"ZXY":this._x=d*u*h-c*f*p,this._y=c*f*h+d*u*p,this._z=c*u*p+d*f*h,this._w=c*u*h-d*f*p;break;case"ZYX":this._x=d*u*h-c*f*p,this._y=c*f*h+d*u*p,this._z=c*u*p-d*f*h,this._w=c*u*h+d*f*p;break;case"YZX":this._x=d*u*h+c*f*p,this._y=c*f*h+d*u*p,this._z=c*u*p-d*f*h,this._w=c*u*h-d*f*p;break;case"XZY":this._x=d*u*h-c*f*p,this._y=c*f*h-d*u*p,this._z=c*u*p+d*f*h,this._w=c*u*h+d*f*p;break;default:ee("Quaternion: .setFromEuler() encountered an unknown order: "+o)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const n=t/2,i=Math.sin(n);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,n=t[0],i=t[4],s=t[8],o=t[1],a=t[5],l=t[9],c=t[2],u=t[6],h=t[10],d=n+a+h;if(d>0){const f=.5/Math.sqrt(d+1);this._w=.25/f,this._x=(u-l)*f,this._y=(s-c)*f,this._z=(o-i)*f}else if(n>a&&n>h){const f=2*Math.sqrt(1+n-a-h);this._w=(u-l)/f,this._x=.25*f,this._y=(i+o)/f,this._z=(s+c)/f}else if(a>h){const f=2*Math.sqrt(1+a-n-h);this._w=(s-c)/f,this._x=(i+o)/f,this._y=.25*f,this._z=(l+u)/f}else{const f=2*Math.sqrt(1+h-n-a);this._w=(o-i)/f,this._x=(s+c)/f,this._y=(l+u)/f,this._z=.25*f}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(ot(this.dot(e),-1,1)))}rotateTowards(e,t){const n=this.angleTo(e);if(n===0)return this;const i=Math.min(1,t/n);return this.slerp(e,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(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,i=e._y,s=e._z,o=e._w,a=t._x,l=t._y,c=t._z,u=t._w;return this._x=n*u+o*a+i*c-s*l,this._y=i*u+o*l+s*a-n*c,this._z=s*u+o*c+n*l-i*a,this._w=o*u-n*a-i*l-s*c,this._onChangeCallback(),this}slerp(e,t){let n=e._x,i=e._y,s=e._z,o=e._w,a=this.dot(e);a<0&&(n=-n,i=-i,s=-s,o=-o,a=-a);let l=1-t;if(a<.9995){const c=Math.acos(a),u=Math.sin(c);l=Math.sin(l*c)/u,t=Math.sin(t*c)/u,this._x=this._x*l+n*t,this._y=this._y*l+i*t,this._z=this._z*l+s*t,this._w=this._w*l+o*t,this._onChangeCallback()}else this._x=this._x*l+n*t,this._y=this._y*l+i*t,this._z=this._z*l+s*t,this._w=this._w*l+o*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(),i=Math.sqrt(1-n),s=Math.sqrt(n);return this.set(i*Math.sin(e),i*Math.cos(e),s*Math.sin(t),s*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}}const Qp=class Qp{constructor(e=0,t=0,n=0){this.x=e,this.y=t,this.z=n}set(e,t,n){return n===void 0&&(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(mm.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(mm.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,n=this.y,i=this.z,s=e.elements;return this.x=s[0]*t+s[3]*n+s[6]*i,this.y=s[1]*t+s[4]*n+s[7]*i,this.z=s[2]*t+s[5]*n+s[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,n=this.y,i=this.z,s=e.elements,o=1/(s[3]*t+s[7]*n+s[11]*i+s[15]);return this.x=(s[0]*t+s[4]*n+s[8]*i+s[12])*o,this.y=(s[1]*t+s[5]*n+s[9]*i+s[13])*o,this.z=(s[2]*t+s[6]*n+s[10]*i+s[14])*o,this}applyQuaternion(e){const t=this.x,n=this.y,i=this.z,s=e.x,o=e.y,a=e.z,l=e.w,c=2*(o*i-a*n),u=2*(a*t-s*i),h=2*(s*n-o*t);return this.x=t+l*c+o*h-a*u,this.y=n+l*u+a*c-s*h,this.z=i+l*h+s*u-o*c,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,i=this.z,s=e.elements;return this.x=s[0]*t+s[4]*n+s[8]*i,this.y=s[1]*t+s[5]*n+s[9]*i,this.z=s[2]*t+s[6]*n+s[10]*i,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=ot(this.x,e.x,t.x),this.y=ot(this.y,e.y,t.y),this.z=ot(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=ot(this.x,e,t),this.y=ot(this.y,e,t),this.z=ot(this.z,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(ot(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,i=e.y,s=e.z,o=t.x,a=t.y,l=t.z;return this.x=i*l-s*a,this.y=s*o-n*l,this.z=n*a-i*o,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return Sh.copy(this).projectOnVector(e),this.sub(Sh)}reflect(e){return this.sub(Sh.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(ot(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y,i=this.z-e.z;return t*t+n*n+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){const i=Math.sin(t)*e;return this.x=i*Math.sin(n),this.y=Math.cos(t)*e,this.z=i*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(),i=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=i,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}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=Math.random()*2-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}};Qp.prototype.isVector3=!0;let C=Qp;const Sh=new C,mm=new Li,Jp=class Jp{constructor(e,t,n,i,s,o,a,l,c){this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,n,i,s,o,a,l,c)}set(e,t,n,i,s,o,a,l,c){const u=this.elements;return u[0]=e,u[1]=i,u[2]=a,u[3]=t,u[4]=s,u[5]=l,u[6]=n,u[7]=o,u[8]=c,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,i=t.elements,s=this.elements,o=n[0],a=n[3],l=n[6],c=n[1],u=n[4],h=n[7],d=n[2],f=n[5],p=n[8],g=i[0],m=i[3],_=i[6],x=i[1],v=i[4],S=i[7],E=i[2],T=i[5],A=i[8];return s[0]=o*g+a*x+l*E,s[3]=o*m+a*v+l*T,s[6]=o*_+a*S+l*A,s[1]=c*g+u*x+h*E,s[4]=c*m+u*v+h*T,s[7]=c*_+u*S+h*A,s[2]=d*g+f*x+p*E,s[5]=d*m+f*v+p*T,s[8]=d*_+f*S+p*A,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],i=e[2],s=e[3],o=e[4],a=e[5],l=e[6],c=e[7],u=e[8];return t*o*u-t*a*c-n*s*u+n*a*l+i*s*c-i*o*l}invert(){const e=this.elements,t=e[0],n=e[1],i=e[2],s=e[3],o=e[4],a=e[5],l=e[6],c=e[7],u=e[8],h=u*o-a*c,d=a*l-u*s,f=c*s-o*l,p=t*h+n*d+i*f;if(p===0)return this.set(0,0,0,0,0,0,0,0,0);const g=1/p;return e[0]=h*g,e[1]=(i*c-u*n)*g,e[2]=(a*n-i*o)*g,e[3]=d*g,e[4]=(u*t-i*l)*g,e[5]=(i*s-a*t)*g,e[6]=f*g,e[7]=(n*l-c*t)*g,e[8]=(o*t-n*s)*g,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,i,s,o,a){const l=Math.cos(s),c=Math.sin(s);return this.set(n*l,n*c,-n*(l*o+c*a)+o+e,-i*c,i*l,-i*(-c*o+l*a)+a+t,0,0,1),this}scale(e,t){return this.premultiply(bh.makeScale(e,t)),this}rotate(e){return this.premultiply(bh.makeRotation(-e)),this}translate(e,t){return this.premultiply(bh.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 i=0;i<9;i++)if(t[i]!==n[i])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)}};Jp.prototype.isMatrix3=!0;let Ke=Jp;const bh=new Ke,gm=new Ke().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),_m=new Ke().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function NS(){const r={enabled:!0,workingColorSpace:ql,spaces:{},convert:function(i,s,o){return this.enabled===!1||s===o||!s||!o||(this.spaces[s].transfer===Ee&&(i.r=zs(i.r),i.g=zs(i.g),i.b=zs(i.b)),this.spaces[s].primaries!==this.spaces[o].primaries&&(i.applyMatrix3(this.spaces[s].toXYZ),i.applyMatrix3(this.spaces[o].fromXYZ)),this.spaces[o].transfer===Ee&&(i.r=Jo(i.r),i.g=Jo(i.g),i.b=Jo(i.b))),i},workingToColorSpace:function(i,s){return this.convert(i,this.workingColorSpace,s)},colorSpaceToWorking:function(i,s){return this.convert(i,s,this.workingColorSpace)},getPrimaries:function(i){return this.spaces[i].primaries},getTransfer:function(i){return i===ri?Na:this.spaces[i].transfer},getToneMappingMode:function(i){return this.spaces[i].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(i,s=this.workingColorSpace){return i.fromArray(this.spaces[s].luminanceCoefficients)},define:function(i){Object.assign(this.spaces,i)},_getMatrix:function(i,s,o){return i.copy(this.spaces[s].toXYZ).multiply(this.spaces[o].fromXYZ)},_getDrawingBufferColorSpace:function(i){return this.spaces[i].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(i=this.workingColorSpace){return this.spaces[i].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(i,s){return Yt("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),r.workingToColorSpace(i,s)},toWorkingColorSpace:function(i,s){return Yt("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),r.colorSpaceToWorking(i,s)}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],n=[.3127,.329];return r.define({[ql]:{primaries:e,whitePoint:n,transfer:Na,toXYZ:gm,fromXYZ:_m,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:Qn},outputColorSpaceConfig:{drawingBufferColorSpace:Qn}},[Qn]:{primaries:e,whitePoint:n,transfer:Ee,toXYZ:gm,fromXYZ:_m,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:Qn}}}),r}const Xe=NS();function zs(r){return r<.04045?r*.0773993808:Math.pow(r*.9478672986+.0521327014,2.4)}function Jo(r){return r<.0031308?r*12.92:1.055*Math.pow(r,.41666)-.055}let Ao;class PS{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{Ao===void 0&&(Ao=Yl("canvas")),Ao.width=e.width,Ao.height=e.height;const i=Ao.getContext("2d");e instanceof ImageData?i.putImageData(e,0,0):i.drawImage(e,0,0,e.width,e.height),n=Ao}return n.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=Yl("canvas");t.width=e.width,t.height=e.height;const n=t.getContext("2d");n.drawImage(e,0,0,e.width,e.height);const i=n.getImageData(0,0,e.width,e.height),s=i.data;for(let o=0;o1),this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(Mh).x}get height(){return this.source.getSize(Mh).y}get depth(){return this.source.getSize(Mh).z}get image(){return this.source.data}set image(e){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.normalized=e.normalized,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(const t in e){const n=e[t];if(n===void 0){ee(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const i=this[t];if(i===void 0){ee(`Texture.setValues(): property '${t}' does not exist.`);continue}i&&n&&i.isVector2&&n.isVector2||i&&n&&i.isVector3&&n.isVector3||i&&n&&i.isMatrix3&&n.isMatrix3?i.copy(n):this[t]=n}}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)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,normalized:this.normalized,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==Yf)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case ro:e.x=e.x-Math.floor(e.x);break;case ai:e.x=e.x<0?0:1;break;case oo:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case ro:e.y=e.y-Math.floor(e.y);break;case ai:e.y=e.y<0?0:1;break;case oo:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}}pn.DEFAULT_IMAGE=null;pn.DEFAULT_MAPPING=Yf;pn.DEFAULT_ANISOTROPY=1;const em=class em{constructor(e=0,t=0,n=0,i=1){this.x=e,this.y=t,this.z=n,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,i){return this.x=e,this.y=t,this.z=n,this.w=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?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,i=this.z,s=this.w,o=e.elements;return this.x=o[0]*t+o[4]*n+o[8]*i+o[12]*s,this.y=o[1]*t+o[5]*n+o[9]*i+o[13]*s,this.z=o[2]*t+o[6]*n+o[10]*i+o[14]*s,this.w=o[3]*t+o[7]*n+o[11]*i+o[15]*s,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,i,s;const l=e.elements,c=l[0],u=l[4],h=l[8],d=l[1],f=l[5],p=l[9],g=l[2],m=l[6],_=l[10];if(Math.abs(u-d)<.01&&Math.abs(h-g)<.01&&Math.abs(p-m)<.01){if(Math.abs(u+d)<.1&&Math.abs(h+g)<.1&&Math.abs(p+m)<.1&&Math.abs(c+f+_-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const v=(c+1)/2,S=(f+1)/2,E=(_+1)/2,T=(u+d)/4,A=(h+g)/4,y=(p+m)/4;return v>S&&v>E?v<.01?(n=0,i=.707106781,s=.707106781):(n=Math.sqrt(v),i=T/n,s=A/n):S>E?S<.01?(n=.707106781,i=0,s=.707106781):(i=Math.sqrt(S),n=T/i,s=y/i):E<.01?(n=.707106781,i=.707106781,s=0):(s=Math.sqrt(E),n=A/s,i=y/s),this.set(n,i,s,t),this}let x=Math.sqrt((m-p)*(m-p)+(h-g)*(h-g)+(d-u)*(d-u));return Math.abs(x)<.001&&(x=1),this.x=(m-p)/x,this.y=(h-g)/x,this.z=(d-u)/x,this.w=Math.acos((c+f+_-1)/2),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=ot(this.x,e.x,t.x),this.y=ot(this.y,e.y,t.y),this.z=ot(this.z,e.z,t.z),this.w=ot(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=ot(this.x,e,t),this.y=ot(this.y,e,t),this.z=ot(this.z,e,t),this.w=ot(this.w,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(ot(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this.w=e.w+(t.w-e.w)*n,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}};em.prototype.isVector4=!0;let tt=em;class Lr extends Ii{constructor(e=1,t=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Ut,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},n),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth,this.scissor=new tt(0,0,e,t),this.scissorTest=!1,this.viewport=new tt(0,0,e,t),this.textures=[];const i={width:e,height:t,depth:n.depth},s=new pn(i),o=n.count;for(let a=0;a1);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>>0}enable(e){this.mask|=1<1){for(let t=0;t1){for(let n=0;n0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),this.pivot!==null&&(i.pivot=this.pivot.toArray()),this.matrixAutoUpdate===!1&&(i.matrixAutoUpdate=!1),this.morphTargetDictionary!==void 0&&(i.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),this.morphTargetInfluences!==void 0&&(i.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.geometryInfo=this._geometryInfo.map(a=>({...a,boundingBox:a.boundingBox?a.boundingBox.toJSON():void 0,boundingSphere:a.boundingSphere?a.boundingSphere.toJSON():void 0})),i.instanceInfo=this._instanceInfo.map(a=>({...a})),i.availableInstanceIds=this._availableInstanceIds.slice(),i.availableGeometryIds=this._availableGeometryIds.slice(),i.nextIndexStart=this._nextIndexStart,i.nextVertexStart=this._nextVertexStart,i.geometryCount=this._geometryCount,i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.matricesTexture=this._matricesTexture.toJSON(e),i.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(i.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(i.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(i.boundingBox=this.boundingBox.toJSON()));function s(a,l){return a[l.uuid]===void 0&&(a[l.uuid]=l.toJSON(e)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=s(e.geometries,this.geometry);const a=this.geometry.parameters;if(a!==void 0&&a.shapes!==void 0){const l=a.shapes;if(Array.isArray(l))for(let c=0,u=l.length;c0){i.children=[];for(let a=0;a0){i.animations=[];for(let a=0;a0&&(n.geometries=a),l.length>0&&(n.materials=l),c.length>0&&(n.textures=c),u.length>0&&(n.images=u),h.length>0&&(n.shapes=h),d.length>0&&(n.skeletons=d),f.length>0&&(n.animations=f),p.length>0&&(n.nodes=p)}return n.object=i,n;function o(a){const l=[];for(const c in a){const u=a[c];delete u.metadata,l.push(u)}return l}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.pivot=e.pivot!==null?e.pivot.clone():null,this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.static=e.static,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let n=0;nf+p?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!c.inputState.pinching&&d<=f-p&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else l!==null&&e.gripSpace&&(s=t.getPose(e.gripSpace,n),s!==null&&(l.matrix.fromArray(s.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,s.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(s.linearVelocity)):l.hasLinearVelocity=!1,s.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(s.angularVelocity)):l.hasAngularVelocity=!1,l.eventsEnabled&&l.dispatchEvent({type:"gripUpdated",data:e,target:this})));a!==null&&(i=t.getPose(e.targetRaySpace,n),i===null&&s!==null&&(i=s),i!==null&&(a.matrix.fromArray(i.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,i.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(i.linearVelocity)):a.hasLinearVelocity=!1,i.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(i.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(VS)))}return a!==null&&(a.visible=i!==null),l!==null&&(l.visible=s!==null),c!==null&&(c.visible=o!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const n=new Xo;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}}const Mx={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},Js={h:0,s:0,l:0},bc={h:0,s:0,l:0};function Ah(r,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?r+(e-r)*6*t:t<1/2?e:t<2/3?r+(e-r)*6*(2/3-t):r}class Ve{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(t===void 0&&n===void 0){const i=e;i&&i.isColor?this.copy(i):typeof i=="number"?this.setHex(i):typeof i=="string"&&this.setStyle(i)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Qn){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,Xe.colorSpaceToWorking(this,t),this}setRGB(e,t,n,i=Xe.workingColorSpace){return this.r=e,this.g=t,this.b=n,Xe.colorSpaceToWorking(this,i),this}setHSL(e,t,n,i=Xe.workingColorSpace){if(e=np(e,1),t=ot(t,0,1),n=ot(n,0,1),t===0)this.r=this.g=this.b=n;else{const s=n<=.5?n*(1+t):n+t-n*t,o=2*n-s;this.r=Ah(o,s,e+1/3),this.g=Ah(o,s,e),this.b=Ah(o,s,e-1/3)}return Xe.colorSpaceToWorking(this,i),this}setStyle(e,t=Qn){function n(s){s!==void 0&&parseFloat(s)<1&&ee("Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let s;const o=i[1],a=i[2];switch(o){case"rgb":case"rgba":if(s=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(s[4]),this.setRGB(Math.min(255,parseInt(s[1],10))/255,Math.min(255,parseInt(s[2],10))/255,Math.min(255,parseInt(s[3],10))/255,t);if(s=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(s[4]),this.setRGB(Math.min(100,parseInt(s[1],10))/100,Math.min(100,parseInt(s[2],10))/100,Math.min(100,parseInt(s[3],10))/100,t);break;case"hsl":case"hsla":if(s=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(s[4]),this.setHSL(parseFloat(s[1])/360,parseFloat(s[2])/100,parseFloat(s[3])/100,t);break;default:ee("Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){const s=i[1],o=s.length;if(o===3)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,t);if(o===6)return this.setHex(parseInt(s,16),t);ee("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Qn){const n=Mx[e.toLowerCase()];return n!==void 0?this.setHex(n,t):ee("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=zs(e.r),this.g=zs(e.g),this.b=zs(e.b),this}copyLinearToSRGB(e){return this.r=Jo(e.r),this.g=Jo(e.g),this.b=Jo(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Qn){return Xe.workingToColorSpace(Vn.copy(this),e),Math.round(ot(Vn.r*255,0,255))*65536+Math.round(ot(Vn.g*255,0,255))*256+Math.round(ot(Vn.b*255,0,255))}getHexString(e=Qn){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Xe.workingColorSpace){Xe.workingToColorSpace(Vn.copy(this),t);const n=Vn.r,i=Vn.g,s=Vn.b,o=Math.max(n,i,s),a=Math.min(n,i,s);let l,c;const u=(a+o)/2;if(a===o)l=0,c=0;else{const h=o-a;switch(c=u<=.5?h/(o+a):h/(2-o-a),o){case n:l=(i-s)/h+(i0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}const Oi=new C,Rs=new C,Rh=new C,ws=new C,No=new C,Po=new C,Em=new C,wh=new C,Ch=new C,Nh=new C,Ph=new tt,Dh=new tt,Lh=new tt;class Hi{constructor(e=new C,t=new C,n=new C){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,i){i.subVectors(n,t),Oi.subVectors(e,t),i.cross(Oi);const s=i.lengthSq();return s>0?i.multiplyScalar(1/Math.sqrt(s)):i.set(0,0,0)}static getBarycoord(e,t,n,i,s){Oi.subVectors(i,t),Rs.subVectors(n,t),Rh.subVectors(e,t);const o=Oi.dot(Oi),a=Oi.dot(Rs),l=Oi.dot(Rh),c=Rs.dot(Rs),u=Rs.dot(Rh),h=o*c-a*a;if(h===0)return s.set(0,0,0),null;const d=1/h,f=(c*l-a*u)*d,p=(o*u-a*l)*d;return s.set(1-f-p,p,f)}static containsPoint(e,t,n,i){return this.getBarycoord(e,t,n,i,ws)===null?!1:ws.x>=0&&ws.y>=0&&ws.x+ws.y<=1}static getInterpolation(e,t,n,i,s,o,a,l){return this.getBarycoord(e,t,n,i,ws)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(s,ws.x),l.addScaledVector(o,ws.y),l.addScaledVector(a,ws.z),l)}static getInterpolatedAttribute(e,t,n,i,s,o){return Ph.setScalar(0),Dh.setScalar(0),Lh.setScalar(0),Ph.fromBufferAttribute(e,t),Dh.fromBufferAttribute(e,n),Lh.fromBufferAttribute(e,i),o.setScalar(0),o.addScaledVector(Ph,s.x),o.addScaledVector(Dh,s.y),o.addScaledVector(Lh,s.z),o}static isFrontFacing(e,t,n,i){return Oi.subVectors(n,t),Rs.subVectors(e,t),Oi.cross(Rs).dot(i)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,i){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,t,n,i){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,i),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Oi.subVectors(this.c,this.b),Rs.subVectors(this.a,this.b),Oi.cross(Rs).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Hi.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Hi.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,i,s){return Hi.getInterpolation(e,this.a,this.b,this.c,t,n,i,s)}containsPoint(e){return Hi.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Hi.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const n=this.a,i=this.b,s=this.c;let o,a;No.subVectors(i,n),Po.subVectors(s,n),wh.subVectors(e,n);const l=No.dot(wh),c=Po.dot(wh);if(l<=0&&c<=0)return t.copy(n);Ch.subVectors(e,i);const u=No.dot(Ch),h=Po.dot(Ch);if(u>=0&&h<=u)return t.copy(i);const d=l*h-u*c;if(d<=0&&l>=0&&u<=0)return o=l/(l-u),t.copy(n).addScaledVector(No,o);Nh.subVectors(e,s);const f=No.dot(Nh),p=Po.dot(Nh);if(p>=0&&f<=p)return t.copy(s);const g=f*c-l*p;if(g<=0&&c>=0&&p<=0)return a=c/(c-p),t.copy(n).addScaledVector(Po,a);const m=u*p-f*h;if(m<=0&&h-u>=0&&f-p>=0)return Em.subVectors(s,i),a=(h-u)/(h-u+(f-p)),t.copy(i).addScaledVector(Em,a);const _=1/(m+g+d);return o=g*_,a=d*_,t.copy(n).addScaledVector(No,o).addScaledVector(Po,a)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}class xo{constructor(e=new C(1/0,1/0,1/0),t=new C(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;t=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,ki),ki.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(Qa),Mc.subVectors(this.max,Qa),Do.subVectors(e.a,Qa),Lo.subVectors(e.b,Qa),Uo.subVectors(e.c,Qa),er.subVectors(Lo,Do),tr.subVectors(Uo,Lo),Br.subVectors(Do,Uo);let t=[0,-er.z,er.y,0,-tr.z,tr.y,0,-Br.z,Br.y,er.z,0,-er.x,tr.z,0,-tr.x,Br.z,0,-Br.x,-er.y,er.x,0,-tr.y,tr.x,0,-Br.y,Br.x,0];return!Uh(t,Do,Lo,Uo,Mc)||(t=[1,0,0,0,1,0,0,0,1],!Uh(t,Do,Lo,Uo,Mc))?!1:(Ec.crossVectors(er,tr),t=[Ec.x,Ec.y,Ec.z],Uh(t,Do,Lo,Uo,Mc))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,ki).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(ki).length()*.5),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()?this:(Cs[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Cs[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Cs[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Cs[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Cs[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Cs[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Cs[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Cs[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Cs),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 Cs=[new C,new C,new C,new C,new C,new C,new C,new C],ki=new C,Tc=new xo,Do=new C,Lo=new C,Uo=new C,er=new C,tr=new C,Br=new C,Qa=new C,Mc=new C,Ec=new C,Or=new C;function Uh(r,e,t,n,i){for(let s=0,o=r.length-3;s<=o;s+=3){Or.fromArray(r,s);const a=i.x*Math.abs(Or.x)+i.y*Math.abs(Or.y)+i.z*Math.abs(Or.z),l=e.dot(Or),c=t.dot(Or),u=n.dot(Or);if(Math.max(-Math.max(l,c,u),Math.min(l,c,u))>a)return!1}return!0}const Fs=zS();function zS(){const r=new ArrayBuffer(4),e=new Float32Array(r),t=new Uint32Array(r),n=new Uint32Array(512),i=new Uint32Array(512);for(let l=0;l<256;++l){const c=l-127;c<-27?(n[l]=0,n[l|256]=32768,i[l]=24,i[l|256]=24):c<-14?(n[l]=1024>>-c-14,n[l|256]=1024>>-c-14|32768,i[l]=-c-1,i[l|256]=-c-1):c<=15?(n[l]=c+15<<10,n[l|256]=c+15<<10|32768,i[l]=13,i[l|256]=13):c<128?(n[l]=31744,n[l|256]=64512,i[l]=24,i[l|256]=24):(n[l]=31744,n[l|256]=64512,i[l]=13,i[l|256]=13)}const s=new Uint32Array(2048),o=new Uint32Array(64),a=new Uint32Array(64);for(let l=1;l<1024;++l){let c=l<<13,u=0;for(;!(c&8388608);)c<<=1,u-=8388608;c&=-8388609,u+=947912704,s[l]=c|u}for(let l=1024;l<2048;++l)s[l]=939524096+(l-1024<<13);for(let l=1;l<31;++l)o[l]=l<<23;o[31]=1199570944,o[32]=2147483648;for(let l=33;l<63;++l)o[l]=2147483648+(l-32<<23);o[63]=3347054592;for(let l=1;l<64;++l)l!==32&&(a[l]=1024);return{floatView:e,uint32View:t,baseTable:n,shiftTable:i,mantissaTable:s,exponentTable:o,offsetTable:a}}function mi(r){Math.abs(r)>65504&&ee("DataUtils.toHalfFloat(): Value out of range."),r=ot(r,-65504,65504),Fs.floatView[0]=r;const e=Fs.uint32View[0],t=e>>23&511;return Fs.baseTable[t]+((e&8388607)>>Fs.shiftTable[t])}function Ac(r){const e=r>>10;return Fs.uint32View[0]=Fs.mantissaTable[Fs.offsetTable[e]+(r&1023)]+Fs.exponentTable[e],Fs.floatView[0]}const fn=new C,Rc=new de;let HS=0;class In extends Ii{constructor(e,t,n=!1){if(super(),Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:HS++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=n,this.usage=Pa,this.updateRanges=[],this.gpuType=Zt,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&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 i=0,s=this.itemSize;ithis.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;Ja.subVectors(e,this.center);const t=Ja.lengthSq();if(t>this.radius*this.radius){const n=Math.sqrt(t),i=(n-this.radius)*.5;this.center.addScaledVector(Ja,i/n),this.radius+=i}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(Fh.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Ja.copy(e.center).add(Fh)),this.expandByPoint(Ja.copy(e.center).sub(Fh))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}}let $S=0;const Ti=new dt,Ih=new mn,Fo=new C,gi=new xo,el=new xo,En=new C;class Pn extends Ii{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:$S++}),this.uuid=Vs(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(dS(e)?lp:ap)(e,1):this.index=e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,n=0){this.groups.push({start:e,count:t,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){const t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);const n=this.attributes.normal;if(n!==void 0){const s=new Ke().getNormalMatrix(e);n.applyNormalMatrix(s),n.needsUpdate=!0}const i=this.attributes.tangent;return i!==void 0&&(i.transformDirection(e),i.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return Ti.makeRotationFromQuaternion(e),this.applyMatrix4(Ti),this}rotateX(e){return Ti.makeRotationX(e),this.applyMatrix4(Ti),this}rotateY(e){return Ti.makeRotationY(e),this.applyMatrix4(Ti),this}rotateZ(e){return Ti.makeRotationZ(e),this.applyMatrix4(Ti),this}translate(e,t,n){return Ti.makeTranslation(e,t,n),this.applyMatrix4(Ti),this}scale(e,t,n){return Ti.makeScale(e,t,n),this.applyMatrix4(Ti),this}lookAt(e){return Ih.lookAt(e),Ih.updateMatrix(),this.applyMatrix4(Ih.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Fo).negate(),this.translate(Fo.x,Fo.y,Fo.z),this}setFromPoints(e){const t=this.getAttribute("position");if(t===void 0){const n=[];for(let i=0,s=e.length;it.count&&ee("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new xo);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){ne("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new C(-1/0,-1/0,-1/0),new C(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let n=0,i=t.length;n0&&(e.userData=this.userData),this.parameters!==void 0){const l=this.parameters;for(const c in l)l[c]!==void 0&&(e[c]=l[c]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const n=this.attributes;for(const l in n){const c=n[l];e.data.attributes[l]=c.toJSON(e.data)}const i={};let s=!1;for(const l in this.morphAttributes){const c=this.morphAttributes[l],u=[];for(let h=0,d=c.length;h0&&(i[l]=u,s=!0)}s&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);const o=this.groups;o.length>0&&(e.data.groups=JSON.parse(JSON.stringify(o)));const a=this.boundingSphere;return a!==null&&(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;n!==null&&this.setIndex(n.clone());const i=e.attributes;for(const c in i){const u=i[c];this.setAttribute(c,u.clone(t))}const s=e.morphAttributes;for(const c in s){const u=[],h=s[c];for(let d=0,f=h.length;d0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const t in e){const n=e[t];if(n===void 0){ee(`Material: parameter '${t}' has value of undefined.`);continue}const i=this[t];if(i===void 0){ee(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}i&&i.isColor?i.set(n):i&&i.isVector3&&n&&n.isVector3?i.copy(n):this[t]=n}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const n={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};n.uuid=this.uuid,n.type=this.type,this.name!==""&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(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),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(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),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(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,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.shadowSide!==null&&(n.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),this.blending!==Jn&&(n.blending=this.blending),this.side!==ni&&(n.side=this.side),this.vertexColors===!0&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),this.transparent===!0&&(n.transparent=!0),this.blendSrc!==Ul&&(n.blendSrc=this.blendSrc),this.blendDst!==Fl&&(n.blendDst=this.blendDst),this.blendEquation!==Wn&&(n.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(n.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(n.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(n.blendAlpha=this.blendAlpha),this.depthFunc!==Ar&&(n.depthFunc=this.depthFunc),this.depthTest===!1&&(n.depthTest=this.depthTest),this.depthWrite===!1&&(n.depthWrite=this.depthWrite),this.colorWrite===!1&&(n.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(n.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==tf&&(n.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(n.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==$r&&(n.stencilFail=this.stencilFail),this.stencilZFail!==$r&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==$r&&(n.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(n.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(n.rotation=this.rotation),this.polygonOffset===!0&&(n.polygonOffset=!0),this.polygonOffsetFactor!==0&&(n.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(n.linewidth=this.linewidth),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.dithering===!0&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),this.alphaHash===!0&&(n.alphaHash=!0),this.alphaToCoverage===!0&&(n.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=!0),this.forceSinglePass===!0&&(n.forceSinglePass=!0),this.allowOverride===!1&&(n.allowOverride=!1),this.wireframe===!0&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(n.flatShading=!0),this.visible===!1&&(n.visible=!1),this.toneMapped===!1&&(n.toneMapped=!1),this.fog===!1&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData);function i(s){const o=[];for(const a in s){const l=s[a];delete l.metadata,o.push(l)}return o}if(t){const s=i(e.textures),o=i(e.images);s.length>0&&(n.textures=s),o.length>0&&(n.images=o)}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(t!==null){const i=t.length;n=new Array(i);for(let s=0;s!==i;++s)n[s]=t[s].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){e===!0&&this.version++}}class qS extends qn{constructor(e){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new Ve(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.rotation=e.rotation,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}const Ns=new C,Bh=new C,wc=new C,nr=new C,Oh=new C,Cc=new C,kh=new C;class Zu{constructor(e=new C,t=new C(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,Ns)),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=Ns.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Ns.copy(this.origin).addScaledVector(this.direction,t),Ns.distanceToSquared(e))}distanceSqToSegment(e,t,n,i){Bh.copy(e).add(t).multiplyScalar(.5),wc.copy(t).sub(e).normalize(),nr.copy(this.origin).sub(Bh);const s=e.distanceTo(t)*.5,o=-this.direction.dot(wc),a=nr.dot(this.direction),l=-nr.dot(wc),c=nr.lengthSq(),u=Math.abs(1-o*o);let h,d,f,p;if(u>0)if(h=o*l-a,d=o*a-l,p=s*u,h>=0)if(d>=-p)if(d<=p){const g=1/u;h*=g,d*=g,f=h*(h+o*d+2*a)+d*(o*h+d+2*l)+c}else d=s,h=Math.max(0,-(o*d+a)),f=-h*h+d*(d+2*l)+c;else d=-s,h=Math.max(0,-(o*d+a)),f=-h*h+d*(d+2*l)+c;else d<=-p?(h=Math.max(0,-(-o*s+a)),d=h>0?-s:Math.min(Math.max(-s,-l),s),f=-h*h+d*(d+2*l)+c):d<=p?(h=0,d=Math.min(Math.max(-s,-l),s),f=d*(d+2*l)+c):(h=Math.max(0,-(o*s+a)),d=h>0?s:Math.min(Math.max(-s,-l),s),f=-h*h+d*(d+2*l)+c);else d=o>0?-s:s,h=Math.max(0,-(o*d+a)),f=-h*h+d*(d+2*l)+c;return n&&n.copy(this.origin).addScaledVector(this.direction,h),i&&i.copy(Bh).addScaledVector(wc,d),f}intersectSphere(e,t){Ns.subVectors(e.center,this.origin);const n=Ns.dot(this.direction),i=Ns.dot(Ns)-n*n,s=e.radius*e.radius;if(i>s)return null;const o=Math.sqrt(s-i),a=n-o,l=n+o;return l<0?null:a<0?this.at(l,t):this.at(a,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?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 n===null?null:this.at(n,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,i,s,o,a,l;const c=1/this.direction.x,u=1/this.direction.y,h=1/this.direction.z,d=this.origin;return c>=0?(n=(e.min.x-d.x)*c,i=(e.max.x-d.x)*c):(n=(e.max.x-d.x)*c,i=(e.min.x-d.x)*c),u>=0?(s=(e.min.y-d.y)*u,o=(e.max.y-d.y)*u):(s=(e.max.y-d.y)*u,o=(e.min.y-d.y)*u),n>o||s>i||((s>n||isNaN(n))&&(n=s),(o=0?(a=(e.min.z-d.z)*h,l=(e.max.z-d.z)*h):(a=(e.max.z-d.z)*h,l=(e.min.z-d.z)*h),n>l||a>i)||((a>n||n!==n)&&(n=a),(l=0?n:i,t)}intersectsBox(e){return this.intersectBox(e,Ns)!==null}intersectTriangle(e,t,n,i,s){Oh.subVectors(t,e),Cc.subVectors(n,e),kh.crossVectors(Oh,Cc);let o=this.direction.dot(kh),a;if(o>0){if(i)return null;a=1}else if(o<0)a=-1,o=-o;else return null;nr.subVectors(this.origin,e);const l=a*this.direction.dot(Cc.crossVectors(nr,Cc));if(l<0)return null;const c=a*this.direction.dot(Oh.cross(nr));if(c<0||l+c>o)return null;const u=-a*nr.dot(kh);return u<0?null:this.at(u/o,s)}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 us extends qn{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Ve(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 ys,this.combine=nc,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 Am=new dt,kr=new Zu,Nc=new ac,Rm=new C,Pc=new C,Dc=new C,Lc=new C,Gh=new C,Uc=new C,wm=new C,Fc=new C;class gn extends mn{constructor(e=new Pn,t=new us){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){const t=this.geometry.morphAttributes,n=Object.keys(t);if(n.length>0){const i=t[n[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=i.length;s(e.far-e.near)**2))&&(Am.copy(s).invert(),kr.copy(e.ray).applyMatrix4(Am),!(n.boundingBox!==null&&kr.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(e,t,kr)))}_computeIntersections(e,t,n){let i;const s=this.geometry,o=this.material,a=s.index,l=s.attributes.position,c=s.attributes.uv,u=s.attributes.uv1,h=s.attributes.normal,d=s.groups,f=s.drawRange;if(a!==null)if(Array.isArray(o))for(let p=0,g=d.length;pt.far?null:{distance:c,point:Fc.clone(),object:r}}function Ic(r,e,t,n,i,s,o,a,l,c){r.getVertexPosition(a,Pc),r.getVertexPosition(l,Dc),r.getVertexPosition(c,Lc);const u=jS(r,e,t,n,Pc,Dc,Lc,wm);if(u){const h=new C;Hi.getBarycoord(wm,Pc,Dc,Lc,h),i&&(u.uv=Hi.getInterpolatedAttribute(i,a,l,c,h,new de)),s&&(u.uv1=Hi.getInterpolatedAttribute(s,a,l,c,h,new de)),o&&(u.normal=Hi.getInterpolatedAttribute(o,a,l,c,h,new C),u.normal.dot(n.direction)>0&&u.normal.multiplyScalar(-1));const d={a,b:l,c,normal:new C,materialIndex:0};Hi.getNormal(Pc,Dc,Lc,d.normal),u.face=d,u.barycoord=h}return u}class up extends pn{constructor(e=null,t=1,n=1,i,s,o,a,l,c=bt,u=bt,h,d){super(null,o,a,l,c,u,i,s,h,d),this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class YS extends In{constructor(e,t,n,i=1){super(e,t,n),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=i}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}toJSON(){const e=super.toJSON();return e.meshPerAttribute=this.meshPerAttribute,e.isInstancedBufferAttribute=!0,e}}const Vh=new C,KS=new C,ZS=new Ke;class os{constructor(e=new C(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,i){return this.normal.set(e,t,n),this.constant=i,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){const i=Vh.subVectors(n,t).cross(KS.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(i,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t,n=!0){const i=e.delta(Vh),s=this.normal.dot(i);if(s===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;const o=-(e.start.dot(this.normal)+this.constant)/s;return n===!0&&(o<0||o>1)?null:t.copy(e.start).addScaledVector(i,o)}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||ZS.getNormalMatrix(e),i=this.coplanarPoint(Vh).applyMatrix4(e),s=this.normal.applyMatrix3(n).normalize();return this.constant=-i.dot(s),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 Gr=new ac,QS=new de(.5,.5),Bc=new C;class lc{constructor(e=new os,t=new os,n=new os,i=new os,s=new os,o=new os){this.planes=[e,t,n,i,s,o]}set(e,t,n,i,s,o){const a=this.planes;return a[0].copy(e),a[1].copy(t),a[2].copy(n),a[3].copy(i),a[4].copy(s),a[5].copy(o),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=ti,n=!1){const i=this.planes,s=e.elements,o=s[0],a=s[1],l=s[2],c=s[3],u=s[4],h=s[5],d=s[6],f=s[7],p=s[8],g=s[9],m=s[10],_=s[11],x=s[12],v=s[13],S=s[14],E=s[15];if(i[0].setComponents(c-o,f-u,_-p,E-x).normalize(),i[1].setComponents(c+o,f+u,_+p,E+x).normalize(),i[2].setComponents(c+a,f+h,_+g,E+v).normalize(),i[3].setComponents(c-a,f-h,_-g,E-v).normalize(),n)i[4].setComponents(l,d,m,S).normalize(),i[5].setComponents(c-l,f-d,_-m,E-S).normalize();else if(i[4].setComponents(c-l,f-d,_-m,E-S).normalize(),t===ti)i[5].setComponents(c+l,f+d,_+m,E+S).normalize();else if(t===xs)i[5].setComponents(l,d,m,S).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),Gr.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),Gr.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Gr)}intersectsSprite(e){Gr.center.set(0,0,0);const t=QS.distanceTo(e.center);return Gr.radius=.7071067811865476+t,Gr.applyMatrix4(e.matrixWorld),this.intersectsSphere(Gr)}intersectsSphere(e){const t=this.planes,n=e.center,i=-e.radius;for(let s=0;s<6;s++)if(t[s].distanceToPoint(n)0?e.max.x:e.min.x,Bc.y=i.normal.y>0?e.max.y:e.min.y,Bc.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(Bc)<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 Yi=new dt,Ki=new lc;class hp{constructor(){this.coordinateSystem=ti}intersectsObject(e,t){if(!t.isArrayCamera||t.cameras.length===0)return!1;for(let n=0;n0){const i=t[n[0]];if(i!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=i.length;sn)return;zh.applyMatrix4(r.matrixWorld);const c=e.ray.origin.distanceTo(zh);if(!(ce.far))return{distance:c,point:Nm.clone().applyMatrix4(r.matrixWorld),index:o,face:null,faceIndex:null,barycoord:null,object:r}}class eb extends qn{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new Ve(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 Rx extends pn{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=bt,this.minFilter=bt,this.generateMipmaps=!1,this.needsUpdate=!0}}class Ga extends pn{constructor(e=[],t=Xi,n,i,s,o,a,l,c,u){super(e,t,n,i,s,o,a,l,c,u),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class Xn extends pn{constructor(e,t,n=wt,i,s,o,a=bt,l=bt,c,u=Nn,h=1){if(u!==Nn&&u!==$n)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const d={width:e,height:t,depth:h};super(d,i,s,o,a,l,u,n,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new ip(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}}class wx extends Xn{constructor(e,t=wt,n=Xi,i,s,o=bt,a=bt,l,c=Nn){const u={width:e,height:e,depth:1},h=[u,u,u,u,u,u];super(e,e,t,n,i,s,o,a,l,c),this.image=h,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}}class Cx extends pn{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}class yo extends Pn{constructor(e=1,t=1,n=1,i=1,s=1,o=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:n,widthSegments:i,heightSegments:s,depthSegments:o};const a=this;i=Math.floor(i),s=Math.floor(s),o=Math.floor(o);const l=[],c=[],u=[],h=[];let d=0,f=0;p("z","y","x",-1,-1,n,t,e,o,s,0),p("z","y","x",1,-1,n,t,-e,o,s,1),p("x","z","y",1,1,e,n,t,i,o,2),p("x","z","y",1,-1,e,n,-t,i,o,3),p("x","y","z",1,-1,e,t,n,i,s,4),p("x","y","z",-1,-1,e,t,-n,i,s,5),this.setIndex(l),this.setAttribute("position",new sn(c,3)),this.setAttribute("normal",new sn(u,3)),this.setAttribute("uv",new sn(h,2));function p(g,m,_,x,v,S,E,T,A,y,R){const P=S/A,N=E/y,U=S/2,G=E/2,V=T/2,L=A+1,B=y+1;let H=0,ie=0;const ce=new C;for(let ve=0;ve0?1:-1,u.push(ce.x,ce.y,ce.z),h.push(ke/A),h.push(1-ve/y),H+=1}}for(let ve=0;ve0&&v(!0),t>0&&v(!1)),this.setIndex(u),this.setAttribute("position",new sn(h,3)),this.setAttribute("normal",new sn(d,3)),this.setAttribute("uv",new sn(f,2));function x(){const S=new C,E=new C;let T=0;const A=(t-e)/n;for(let y=0;y<=s;y++){const R=[],P=y/s,N=P*(t-e)+e;for(let U=0;U<=i;U++){const G=U/i,V=G*l+a,L=Math.sin(V),B=Math.cos(V);E.x=N*L,E.y=-P*n+m,E.z=N*B,h.push(E.x,E.y,E.z),S.set(L,A,B).normalize(),d.push(S.x,S.y,S.z),f.push(G,1-P),R.push(p++)}g.push(R)}for(let y=0;y0||R!==0)&&(u.push(P,N,G),T+=3),(t>0||R!==s-1)&&(u.push(N,U,G),T+=3)}c.addGroup(_,T,0),_+=T}function v(S){const E=p,T=new de,A=new C;let y=0;const R=S===!0?e:t,P=S===!0?1:-1;for(let U=1;U<=i;U++)h.push(0,m*P,0),d.push(0,P,0),f.push(.5,.5),p++;const N=p;for(let U=0;U<=i;U++){const V=U/i*l+a,L=Math.cos(V),B=Math.sin(V);A.x=R*B,A.y=m*P,A.z=R*L,h.push(A.x,A.y,A.z),d.push(0,P,0),T.x=L*.5+.5,T.y=B*.5*P+.5,f.push(T.x,T.y),p++}for(let U=0;U0)l=i-1;else{l=i;break}if(i=l,n[i]===o)return i/(s-1);const u=n[i],d=n[i+1]-u,f=(o-u)/d;return(i+f)/(s-1)}getTangent(e,t){let i=e-1e-4,s=e+1e-4;i<0&&(i=0),s>1&&(s=1);const o=this.getPoint(i),a=this.getPoint(s),l=t||(o.isVector2?new de:new C);return l.copy(a).sub(o).normalize(),l}getTangentAt(e,t){const n=this.getUtoTmapping(e);return this.getTangent(n,t)}computeFrenetFrames(e,t=!1){const n=new C,i=[],s=[],o=[],a=new C,l=new dt;for(let f=0;f<=e;f++){const p=f/e;i[f]=this.getTangentAt(p,new C)}s[0]=new C,o[0]=new C;let c=Number.MAX_VALUE;const u=Math.abs(i[0].x),h=Math.abs(i[0].y),d=Math.abs(i[0].z);u<=c&&(c=u,n.set(1,0,0)),h<=c&&(c=h,n.set(0,1,0)),d<=c&&n.set(0,0,1),a.crossVectors(i[0],n).normalize(),s[0].crossVectors(i[0],a),o[0].crossVectors(i[0],s[0]);for(let f=1;f<=e;f++){if(s[f]=s[f-1].clone(),o[f]=o[f-1].clone(),a.crossVectors(i[f-1],i[f]),a.length()>Number.EPSILON){a.normalize();const p=Math.acos(ot(i[f-1].dot(i[f]),-1,1));s[f].applyMatrix4(l.makeRotationAxis(a,p))}o[f].crossVectors(i[f],s[f])}if(t===!0){let f=Math.acos(ot(s[0].dot(s[e]),-1,1));f/=e,i[0].dot(a.crossVectors(s[0],s[e]))>0&&(f=-f);for(let p=1;p<=e;p++)s[p].applyMatrix4(l.makeRotationAxis(i[p],f*p)),o[p].crossVectors(i[p],s[p])}return{tangents:i,normals:s,binormals:o}}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 Nx extends qs{constructor(e=0,t=0,n=1,i=1,s=0,o=Math.PI*2,a=!1,l=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=e,this.aY=t,this.xRadius=n,this.yRadius=i,this.aStartAngle=s,this.aEndAngle=o,this.aClockwise=a,this.aRotation=l}getPoint(e,t=new de){const n=t,i=Math.PI*2;let s=this.aEndAngle-this.aStartAngle;const o=Math.abs(s)i;)s-=i;s0?0:(Math.floor(Math.abs(a)/s)+1)*s:l===0&&a===s-1&&(a=s-2,l=1);let c,u;this.closed||a>0?c=i[(a-1)%s]:(Dm.subVectors(i[0],i[1]).add(i[0]),c=Dm);const h=i[a%s],d=i[(a+1)%s];if(this.closed||a+2i.length-2?i.length-1:o+1],h=i[o>i.length-3?i.length-1:o+2];return n.set(Lm(a,l.x,c.x,u.x,h.x),Lm(a,l.y,c.y,u.y,h.y)),n}copy(e){super.copy(e),this.points=[];for(let t=0,n=e.points.length;t0)&&f.push(v,S,T),(_!==n-1||l0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const n={};for(const i in this.extensions)this.extensions[i]===!0&&(n[i]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}}class vb extends Ui{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}}class Ux extends qn{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new Ve(16777215),this.roughness=1,this.metalness=0,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Ve(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Wi,this.normalScale=new de(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new ys,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={STANDARD:""},this.color.copy(e.color),this.roughness=e.roughness,this.metalness=e.metalness,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.roughnessMap=e.roughnessMap,this.metalnessMap=e.metalnessMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.envMapIntensity=e.envMapIntensity,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Sb extends Ux{constructor(e){super(),this.isMeshPhysicalMaterial=!0,this.defines={STANDARD:"",PHYSICAL:""},this.type="MeshPhysicalMaterial",this.anisotropyRotation=0,this.anisotropyMap=null,this.clearcoatMap=null,this.clearcoatRoughness=0,this.clearcoatRoughnessMap=null,this.clearcoatNormalScale=new de(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return ot(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(t){this.ior=(1+.4*t)/(1-.4*t)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new Ve(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=1/0,this.attenuationColor=new Ve(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new Ve(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(e)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}}class bb extends qn{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new Ve(16777215),this.specular=new Ve(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Ve(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Wi,this.normalScale=new de(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new ys,this.combine=nc,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.envMapIntensity=e.envMapIntensity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Tb extends qn{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new Ve(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Ve(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Wi,this.normalScale=new de(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 Mb extends qn{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Wi,this.normalScale=new de(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 Fx extends qn{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new Ve(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Ve(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Wi,this.normalScale=new de(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new ys,this.combine=nc,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.envMapIntensity=e.envMapIntensity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Eb extends qn{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=Kv,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 Ab extends qn{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 Rb extends qn{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new Ve(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Wi,this.normalScale=new de(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 wb extends Qu{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 Xh={enabled:!1,files:{},add:function(r,e){this.enabled!==!1&&(Fm(r)||(this.files[r]=e))},get:function(r){if(this.enabled!==!1&&!Fm(r))return this.files[r]},remove:function(r){delete this.files[r]},clear:function(){this.files={}}};function Fm(r){try{const e=r.slice(r.indexOf(":")+1);return new URL(e).protocol==="blob:"}catch{return!1}}class Cb{constructor(e,t,n){const i=this;let s=!1,o=0,a=0,l;const c=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=n,this._abortController=null,this.itemStart=function(u){a++,s===!1&&i.onStart!==void 0&&i.onStart(u,o,a),s=!0},this.itemEnd=function(u){o++,i.onProgress!==void 0&&i.onProgress(u,o,a),o===a&&(s=!1,i.onLoad!==void 0&&i.onLoad())},this.itemError=function(u){i.onError!==void 0&&i.onError(u)},this.resolveURL=function(u){return l?l(u):u},this.setURLModifier=function(u){return l=u,this},this.addHandler=function(u,h){return c.push(u,h),this},this.removeHandler=function(u){const h=c.indexOf(u);return h!==-1&&c.splice(h,2),this},this.getHandler=function(u){for(let h=0,d=c.length;hf.start-p.start);let d=0;for(let f=1;f 0 vec4 plane; #ifdef ALPHA_TO_COVERAGE float distanceToPlane, distanceGradient; float clipOpacity = 1.0; #pragma unroll_loop_start for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { plane = clippingPlanes[ i ]; distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; distanceGradient = fwidth( distanceToPlane ) / 2.0; clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); if ( clipOpacity == 0.0 ) discard; } #pragma unroll_loop_end #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES float unionClipOpacity = 1.0; #pragma unroll_loop_start for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { plane = clippingPlanes[ i ]; distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; distanceGradient = fwidth( distanceToPlane ) / 2.0; unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); } #pragma unroll_loop_end clipOpacity *= 1.0 - unionClipOpacity; #endif diffuseColor.a *= clipOpacity; if ( diffuseColor.a == 0.0 ) discard; #else #pragma unroll_loop_start for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { plane = clippingPlanes[ i ]; if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard; } #pragma unroll_loop_end #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES bool clipped = true; #pragma unroll_loop_start for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { plane = clippingPlanes[ i ]; clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped; } #pragma unroll_loop_end if ( clipped ) discard; #endif #endif #endif`,aT=`#if NUM_CLIPPING_PLANES > 0 varying vec3 vClipPosition; uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; #endif`,lT=`#if NUM_CLIPPING_PLANES > 0 varying vec3 vClipPosition; #endif`,cT=`#if NUM_CLIPPING_PLANES > 0 vClipPosition = - mvPosition.xyz; #endif`,uT=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) diffuseColor *= vColor; #endif`,hT=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) varying vec4 vColor; #endif`,dT=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) varying vec4 vColor; #endif`,fT=`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) vColor = vec4( 1.0 ); #endif #ifdef USE_COLOR_ALPHA vColor *= color; #elif defined( USE_COLOR ) vColor.rgb *= color; #endif #ifdef USE_INSTANCING_COLOR vColor.rgb *= instanceColor.rgb; #endif #ifdef USE_BATCHING_COLOR vColor *= getBatchingColor( getIndirectIndex( gl_DrawID ) ); #endif`,pT=`#define PI 3.141592653589793 #define PI2 6.283185307179586 #define PI_HALF 1.5707963267948966 #define RECIPROCAL_PI 0.3183098861837907 #define RECIPROCAL_PI2 0.15915494309189535 #define EPSILON 1e-6 #ifndef saturate #define saturate( a ) clamp( a, 0.0, 1.0 ) #endif #define whiteComplement( a ) ( 1.0 - saturate( a ) ) float pow2( const in float x ) { return x*x; } vec3 pow2( const in vec3 x ) { return x*x; } float pow3( const in float x ) { return x*x*x; } float pow4( const in float x ) { float x2 = x*x; return x2*x2; } float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); } highp float rand( const in vec2 uv ) { const highp float a = 12.9898, b = 78.233, c = 43758.5453; highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); return fract( sin( sn ) * c ); } #ifdef HIGH_PRECISION float precisionSafeLength( vec3 v ) { return length( v ); } #else float precisionSafeLength( vec3 v ) { float maxComponent = max3( abs( v ) ); return length( v / maxComponent ) * maxComponent; } #endif struct IncidentLight { vec3 color; vec3 direction; bool visible; }; struct ReflectedLight { vec3 directDiffuse; vec3 directSpecular; vec3 indirectDiffuse; vec3 indirectSpecular; }; #ifdef USE_ALPHAHASH varying vec3 vPosition; #endif vec3 transformDirection( in vec3 dir, in mat4 matrix ) { return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); } vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); } bool isPerspectiveMatrix( mat4 m ) { return m[ 2 ][ 3 ] == - 1.0; } vec2 equirectUv( in vec3 dir ) { float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; return vec2( u, v ); } vec3 BRDF_Lambert( const in vec3 diffuseColor ) { return RECIPROCAL_PI * diffuseColor; } vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); } float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); } // validated`,mT=`#ifdef ENVMAP_TYPE_CUBE_UV #define cubeUV_minMipLevel 4.0 #define cubeUV_minTileSize 16.0 float getFace( vec3 direction ) { vec3 absDirection = abs( direction ); float face = - 1.0; if ( absDirection.x > absDirection.z ) { if ( absDirection.x > absDirection.y ) face = direction.x > 0.0 ? 0.0 : 3.0; else face = direction.y > 0.0 ? 1.0 : 4.0; } else { if ( absDirection.z > absDirection.y ) face = direction.z > 0.0 ? 2.0 : 5.0; else face = direction.y > 0.0 ? 1.0 : 4.0; } return face; } vec2 getUV( vec3 direction, float face ) { vec2 uv; if ( face == 0.0 ) { uv = vec2( direction.z, direction.y ) / abs( direction.x ); } else if ( face == 1.0 ) { uv = vec2( - direction.x, - direction.z ) / abs( direction.y ); } else if ( face == 2.0 ) { uv = vec2( - direction.x, direction.y ) / abs( direction.z ); } else if ( face == 3.0 ) { uv = vec2( - direction.z, direction.y ) / abs( direction.x ); } else if ( face == 4.0 ) { uv = vec2( - direction.x, direction.z ) / abs( direction.y ); } else { uv = vec2( direction.x, direction.y ) / abs( direction.z ); } return 0.5 * ( uv + 1.0 ); } vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) { float face = getFace( direction ); float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 ); mipInt = max( mipInt, cubeUV_minMipLevel ); float faceSize = exp2( mipInt ); highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0; if ( face > 2.0 ) { uv.y += faceSize; face -= 3.0; } uv.x += face * faceSize; uv.x += filterInt * 3.0 * cubeUV_minTileSize; uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize ); uv.x *= CUBEUV_TEXEL_WIDTH; uv.y *= CUBEUV_TEXEL_HEIGHT; #ifdef texture2DGradEXT return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb; #else return texture2D( envMap, uv ).rgb; #endif } #define cubeUV_r0 1.0 #define cubeUV_m0 - 2.0 #define cubeUV_r1 0.8 #define cubeUV_m1 - 1.0 #define cubeUV_r4 0.4 #define cubeUV_m4 2.0 #define cubeUV_r5 0.305 #define cubeUV_m5 3.0 #define cubeUV_r6 0.21 #define cubeUV_m6 4.0 float roughnessToMip( float roughness ) { float mip = 0.0; if ( roughness >= cubeUV_r1 ) { mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0; } else if ( roughness >= cubeUV_r4 ) { mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1; } else if ( roughness >= cubeUV_r5 ) { mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4; } else if ( roughness >= cubeUV_r6 ) { mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5; } else { mip = - 2.0 * log2( 1.16 * roughness ); } return mip; } vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) { float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP ); float mipF = fract( mip ); float mipInt = floor( mip ); vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt ); if ( mipF == 0.0 ) { return vec4( color0, 1.0 ); } else { vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 ); return vec4( mix( color0, color1, mipF ), 1.0 ); } } #endif`,gT=`vec3 transformedNormal = objectNormal; #ifdef USE_TANGENT vec3 transformedTangent = objectTangent; #endif #ifdef USE_BATCHING mat3 bm = mat3( batchingMatrix ); transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) ); transformedNormal = bm * transformedNormal; #ifdef USE_TANGENT transformedTangent = bm * transformedTangent; #endif #endif #ifdef USE_INSTANCING mat3 im = mat3( instanceMatrix ); transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) ); transformedNormal = im * transformedNormal; #ifdef USE_TANGENT transformedTangent = im * transformedTangent; #endif #endif transformedNormal = normalMatrix * transformedNormal; #ifdef FLIP_SIDED transformedNormal = - transformedNormal; #endif #ifdef USE_TANGENT transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz; #ifdef FLIP_SIDED transformedTangent = - transformedTangent; #endif #endif`,_T=`#ifdef USE_DISPLACEMENTMAP uniform sampler2D displacementMap; uniform float displacementScale; uniform float displacementBias; #endif`,xT=`#ifdef USE_DISPLACEMENTMAP transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); #endif`,yT=`#ifdef USE_EMISSIVEMAP vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE emissiveColor = sRGBTransferEOTF( emissiveColor ); #endif totalEmissiveRadiance *= emissiveColor.rgb; #endif`,vT=`#ifdef USE_EMISSIVEMAP uniform sampler2D emissiveMap; #endif`,ST="gl_FragColor = linearToOutputTexel( gl_FragColor );",bT=`vec4 LinearTransferOETF( in vec4 value ) { return value; } vec4 sRGBTransferEOTF( in vec4 value ) { return 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 ); } vec4 sRGBTransferOETF( in vec4 value ) { return 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 ); }`,TT=`#ifdef USE_ENVMAP #ifdef ENV_WORLDPOS vec3 cameraToFrag; if ( isOrthographic ) { cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); } else { cameraToFrag = normalize( vWorldPosition - cameraPosition ); } vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); #ifdef ENVMAP_MODE_REFLECTION vec3 reflectVec = reflect( cameraToFrag, worldNormal ); #else vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); #endif #else vec3 reflectVec = vReflect; #endif #ifdef ENVMAP_TYPE_CUBE vec4 envColor = textureCube( envMap, envMapRotation * reflectVec ); #ifdef ENVMAP_BLENDING_MULTIPLY outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); #elif defined( ENVMAP_BLENDING_MIX ) outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); #elif defined( ENVMAP_BLENDING_ADD ) outgoingLight += envColor.xyz * specularStrength * reflectivity; #endif #endif #endif`,MT=`#ifdef USE_ENVMAP uniform float envMapIntensity; uniform mat3 envMapRotation; #ifdef ENVMAP_TYPE_CUBE uniform samplerCube envMap; #else uniform sampler2D envMap; #endif #endif`,ET=`#ifdef USE_ENVMAP uniform float reflectivity; #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) #define ENV_WORLDPOS #endif #ifdef ENV_WORLDPOS varying vec3 vWorldPosition; uniform float refractionRatio; #else varying vec3 vReflect; #endif #endif`,AT=`#ifdef USE_ENVMAP #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) #define ENV_WORLDPOS #endif #ifdef ENV_WORLDPOS varying vec3 vWorldPosition; #else varying vec3 vReflect; uniform float refractionRatio; #endif #endif`,RT=`#ifdef USE_ENVMAP #ifdef ENV_WORLDPOS vWorldPosition = worldPosition.xyz; #else vec3 cameraToVertex; if ( isOrthographic ) { cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); } else { cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); } vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); #ifdef ENVMAP_MODE_REFLECTION vReflect = reflect( cameraToVertex, worldNormal ); #else vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); #endif #endif #endif`,wT=`#ifdef USE_FOG vFogDepth = - mvPosition.z; #endif`,CT=`#ifdef USE_FOG varying float vFogDepth; #endif`,NT=`#ifdef USE_FOG #ifdef FOG_EXP2 float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); #else float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); #endif gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); #endif`,PT=`#ifdef USE_FOG uniform vec3 fogColor; varying float vFogDepth; #ifdef FOG_EXP2 uniform float fogDensity; #else uniform float fogNear; uniform float fogFar; #endif #endif`,DT=`#ifdef USE_GRADIENTMAP uniform sampler2D gradientMap; #endif vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { float dotNL = dot( normal, lightDirection ); vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); #ifdef USE_GRADIENTMAP return vec3( texture2D( gradientMap, coord ).r ); #else vec2 fw = fwidth( coord ) * 0.5; return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); #endif }`,LT=`#ifdef USE_LIGHTMAP uniform sampler2D lightMap; uniform float lightMapIntensity; #endif`,UT=`LambertMaterial material; material.diffuseColor = diffuseColor.rgb; material.specularStrength = specularStrength;`,FT=`varying vec3 vViewPosition; struct LambertMaterial { vec3 diffuseColor; float specularStrength; }; void 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 ) { float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); vec3 irradiance = dotNL * directLight.color; reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } void 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 ) { reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_Lambert #define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,IT=`uniform bool receiveShadow; uniform vec3 ambientLightColor; #if defined( USE_LIGHT_PROBES ) uniform vec3 lightProbe[ 9 ]; #endif vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { float x = normal.x, y = normal.y, z = normal.z; vec3 result = shCoefficients[ 0 ] * 0.886227; result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); return result; } vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); return irradiance; } vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { vec3 irradiance = ambientLightColor; return irradiance; } float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); if ( cutoffDistance > 0.0 ) { distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); } return distanceFalloff; } float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { return smoothstep( coneCosine, penumbraCosine, angleCosine ); } #if NUM_DIR_LIGHTS > 0 struct DirectionalLight { vec3 direction; vec3 color; }; uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) { light.color = directionalLight.color; light.direction = directionalLight.direction; light.visible = true; } #endif #if NUM_POINT_LIGHTS > 0 struct PointLight { vec3 position; vec3 color; float distance; float decay; }; uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) { vec3 lVector = pointLight.position - geometryPosition; light.direction = normalize( lVector ); float lightDistance = length( lVector ); light.color = pointLight.color; light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); light.visible = ( light.color != vec3( 0.0 ) ); } #endif #if NUM_SPOT_LIGHTS > 0 struct SpotLight { vec3 position; vec3 direction; vec3 color; float distance; float decay; float coneCos; float penumbraCos; }; uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) { vec3 lVector = spotLight.position - geometryPosition; light.direction = normalize( lVector ); float angleCos = dot( light.direction, spotLight.direction ); float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); if ( spotAttenuation > 0.0 ) { float lightDistance = length( lVector ); light.color = spotLight.color * spotAttenuation; light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); light.visible = ( light.color != vec3( 0.0 ) ); } else { light.color = vec3( 0.0 ); light.visible = false; } } #endif #if NUM_RECT_AREA_LIGHTS > 0 struct RectAreaLight { vec3 color; vec3 position; vec3 halfWidth; vec3 halfHeight; }; uniform sampler2D ltc_1; uniform sampler2D ltc_2; uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; #endif #if NUM_HEMI_LIGHTS > 0 struct HemisphereLight { vec3 direction; vec3 skyColor; vec3 groundColor; }; uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { float dotNL = dot( normal, hemiLight.direction ); float hemiDiffuseWeight = 0.5 * dotNL + 0.5; vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); return irradiance; } #endif #include `,BT=`#ifdef USE_ENVMAP vec3 getIBLIrradiance( const in vec3 normal ) { #ifdef ENVMAP_TYPE_CUBE_UV vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 ); return PI * envMapColor.rgb * envMapIntensity; #else return vec3( 0.0 ); #endif } vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { #ifdef ENVMAP_TYPE_CUBE_UV vec3 reflectVec = reflect( - viewDir, normal ); reflectVec = normalize( mix( reflectVec, normal, pow4( roughness ) ) ); reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness ); return envMapColor.rgb * envMapIntensity; #else return vec3( 0.0 ); #endif } #ifdef USE_ANISOTROPY vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { #ifdef ENVMAP_TYPE_CUBE_UV vec3 bentNormal = cross( bitangent, viewDir ); bentNormal = normalize( cross( bentNormal, bitangent ) ); bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); return getIBLRadiance( viewDir, bentNormal, roughness ); #else return vec3( 0.0 ); #endif } #endif #endif`,OT=`ToonMaterial material; material.diffuseColor = diffuseColor.rgb;`,kT=`varying vec3 vViewPosition; struct ToonMaterial { vec3 diffuseColor; }; void 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 ) { vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color; reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } void 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 ) { reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_Toon #define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,GT=`BlinnPhongMaterial material; material.diffuseColor = diffuseColor.rgb; material.specularColor = specular; material.specularShininess = shininess; material.specularStrength = specularStrength;`,VT=`varying vec3 vViewPosition; struct BlinnPhongMaterial { vec3 diffuseColor; vec3 specularColor; float specularShininess; float specularStrength; }; void 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 ) { float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); vec3 irradiance = dotNL * directLight.color; reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength; } void 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 ) { reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); } #define RE_Direct RE_Direct_BlinnPhong #define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,zT=`PhysicalMaterial material; material.diffuseColor = diffuseColor.rgb; material.diffuseContribution = diffuseColor.rgb * ( 1.0 - metalnessFactor ); material.metalness = metalnessFactor; vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; material.roughness = min( material.roughness, 1.0 ); #ifdef IOR material.ior = ior; #ifdef USE_SPECULAR float specularIntensityFactor = specularIntensity; vec3 specularColorFactor = specularColor; #ifdef USE_SPECULAR_COLORMAP specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb; #endif #ifdef USE_SPECULAR_INTENSITYMAP specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a; #endif material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); #else float specularIntensityFactor = 1.0; vec3 specularColorFactor = vec3( 1.0 ); material.specularF90 = 1.0; #endif material.specularColor = min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor; material.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor ); #else material.specularColor = vec3( 0.04 ); material.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor ); material.specularF90 = 1.0; #endif #ifdef USE_CLEARCOAT material.clearcoat = clearcoat; material.clearcoatRoughness = clearcoatRoughness; material.clearcoatF0 = vec3( 0.04 ); material.clearcoatF90 = 1.0; #ifdef USE_CLEARCOATMAP material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y; #endif material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); material.clearcoatRoughness += geometryRoughness; material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); #endif #ifdef USE_DISPERSION material.dispersion = dispersion; #endif #ifdef USE_IRIDESCENCE material.iridescence = iridescence; material.iridescenceIOR = iridescenceIOR; #ifdef USE_IRIDESCENCEMAP material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum; #else material.iridescenceThickness = iridescenceThicknessMaximum; #endif #endif #ifdef USE_SHEEN material.sheenColor = sheenColor; #ifdef USE_SHEEN_COLORMAP material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb; #endif material.sheenRoughness = clamp( sheenRoughness, 0.0001, 1.0 ); #ifdef USE_SHEEN_ROUGHNESSMAP material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a; #endif #endif #ifdef USE_ANISOTROPY #ifdef USE_ANISOTROPYMAP mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x ); vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb; vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b; #else vec2 anisotropyV = anisotropyVector; #endif material.anisotropy = length( anisotropyV ); if( material.anisotropy == 0.0 ) { anisotropyV = vec2( 1.0, 0.0 ); } else { anisotropyV /= material.anisotropy; material.anisotropy = saturate( material.anisotropy ); } material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; #endif`,HT=`uniform sampler2D dfgLUT; struct PhysicalMaterial { vec3 diffuseColor; vec3 diffuseContribution; vec3 specularColor; vec3 specularColorBlended; float roughness; float metalness; float specularF90; float dispersion; #ifdef USE_CLEARCOAT float clearcoat; float clearcoatRoughness; vec3 clearcoatF0; float clearcoatF90; #endif #ifdef USE_IRIDESCENCE float iridescence; float iridescenceIOR; float iridescenceThickness; vec3 iridescenceFresnel; vec3 iridescenceF0; vec3 iridescenceFresnelDielectric; vec3 iridescenceFresnelMetallic; #endif #ifdef USE_SHEEN vec3 sheenColor; float sheenRoughness; #endif #ifdef IOR float ior; #endif #ifdef USE_TRANSMISSION float transmission; float transmissionAlpha; float thickness; float attenuationDistance; vec3 attenuationColor; #endif #ifdef USE_ANISOTROPY float anisotropy; float alphaT; vec3 anisotropyT; vec3 anisotropyB; #endif }; vec3 clearcoatSpecularDirect = vec3( 0.0 ); vec3 clearcoatSpecularIndirect = vec3( 0.0 ); vec3 sheenSpecularDirect = vec3( 0.0 ); vec3 sheenSpecularIndirect = vec3(0.0 ); vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) { float x = clamp( 1.0 - dotVH, 0.0, 1.0 ); float x2 = x * x; float x5 = clamp( x * x2 * x2, 0.0, 0.9999 ); return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 ); } float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { float a2 = pow2( alpha ); float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); return 0.5 / max( gv + gl, EPSILON ); } float D_GGX( const in float alpha, const in float dotNH ) { float a2 = pow2( alpha ); float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; return RECIPROCAL_PI * a2 / pow2( denom ); } #ifdef USE_ANISOTROPY float 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 ) { float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) ); float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) ); return 0.5 / max( gv + gl, EPSILON ); } float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) { float a2 = alphaT * alphaB; highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH ); highp float v2 = dot( v, v ); float w2 = a2 / v2; return RECIPROCAL_PI * a2 * pow2 ( w2 ); } #endif #ifdef USE_CLEARCOAT vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) { vec3 f0 = material.clearcoatF0; float f90 = material.clearcoatF90; float roughness = material.clearcoatRoughness; float alpha = pow2( roughness ); vec3 halfDir = normalize( lightDir + viewDir ); float dotNL = saturate( dot( normal, lightDir ) ); float dotNV = saturate( dot( normal, viewDir ) ); float dotNH = saturate( dot( normal, halfDir ) ); float dotVH = saturate( dot( viewDir, halfDir ) ); vec3 F = F_Schlick( f0, f90, dotVH ); float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); float D = D_GGX( alpha, dotNH ); return F * ( V * D ); } #endif vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { vec3 f0 = material.specularColorBlended; float f90 = material.specularF90; float roughness = material.roughness; float alpha = pow2( roughness ); vec3 halfDir = normalize( lightDir + viewDir ); float dotNL = saturate( dot( normal, lightDir ) ); float dotNV = saturate( dot( normal, viewDir ) ); float dotNH = saturate( dot( normal, halfDir ) ); float dotVH = saturate( dot( viewDir, halfDir ) ); vec3 F = F_Schlick( f0, f90, dotVH ); #ifdef USE_IRIDESCENCE F = mix( F, material.iridescenceFresnel, material.iridescence ); #endif #ifdef USE_ANISOTROPY float dotTL = dot( material.anisotropyT, lightDir ); float dotTV = dot( material.anisotropyT, viewDir ); float dotTH = dot( material.anisotropyT, halfDir ); float dotBL = dot( material.anisotropyB, lightDir ); float dotBV = dot( material.anisotropyB, viewDir ); float dotBH = dot( material.anisotropyB, halfDir ); float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL ); float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH ); #else float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); float D = D_GGX( alpha, dotNH ); #endif return F * ( V * D ); } vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { const float LUT_SIZE = 64.0; const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; const float LUT_BIAS = 0.5 / LUT_SIZE; float dotNV = saturate( dot( N, V ) ); vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); uv = uv * LUT_SCALE + LUT_BIAS; return uv; } float LTC_ClippedSphereFormFactor( const in vec3 f ) { float l = length( f ); return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); } vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { float x = dot( v1, v2 ); float y = abs( x ); float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; float b = 3.4175940 + ( 4.1616724 + y ) * y; float v = a / b; float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; return cross( v1, v2 ) * theta_sintheta; } vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; vec3 lightNormal = cross( v1, v2 ); if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); vec3 T1, T2; T1 = normalize( V - N * dot( V, N ) ); T2 = - cross( N, T1 ); mat3 mat = mInv * transpose( mat3( T1, T2, N ) ); vec3 coords[ 4 ]; coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); coords[ 0 ] = normalize( coords[ 0 ] ); coords[ 1 ] = normalize( coords[ 1 ] ); coords[ 2 ] = normalize( coords[ 2 ] ); coords[ 3 ] = normalize( coords[ 3 ] ); vec3 vectorFormFactor = vec3( 0.0 ); vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); return vec3( result ); } #if defined( USE_SHEEN ) float D_Charlie( float roughness, float dotNH ) { float alpha = pow2( roughness ); float invAlpha = 1.0 / alpha; float cos2h = dotNH * dotNH; float sin2h = max( 1.0 - cos2h, 0.0078125 ); return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); } float V_Neubelt( float dotNV, float dotNL ) { return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); } vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { vec3 halfDir = normalize( lightDir + viewDir ); float dotNL = saturate( dot( normal, lightDir ) ); float dotNV = saturate( dot( normal, viewDir ) ); float dotNH = saturate( dot( normal, halfDir ) ); float D = D_Charlie( sheenRoughness, dotNH ); float V = V_Neubelt( dotNV, dotNL ); return sheenColor * ( D * V ); } #endif float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { float dotNV = saturate( dot( normal, viewDir ) ); float r2 = roughness * roughness; float rInv = 1.0 / ( roughness + 0.1 ); float a = -1.9362 + 1.0678 * roughness + 0.4573 * r2 - 0.8469 * rInv; float b = -0.6014 + 0.5538 * roughness - 0.4670 * r2 - 0.1255 * rInv; float DG = exp( a * dotNV + b ); return saturate( DG ); } vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { float dotNV = saturate( dot( normal, viewDir ) ); vec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg; return specularColor * fab.x + specularF90 * fab.y; } #ifdef USE_IRIDESCENCE void 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 ) { #else void 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 ) { #endif float dotNV = saturate( dot( normal, viewDir ) ); vec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg; #ifdef USE_IRIDESCENCE vec3 Fr = mix( specularColor, iridescenceF0, iridescence ); #else vec3 Fr = specularColor; #endif vec3 FssEss = Fr * fab.x + specularF90 * fab.y; float Ess = fab.x + fab.y; float Ems = 1.0 - Ess; vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); singleScatter += FssEss; multiScatter += Fms * Ems; } vec3 BRDF_GGX_Multiscatter( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { vec3 singleScatter = BRDF_GGX( lightDir, viewDir, normal, material ); float dotNL = saturate( dot( normal, lightDir ) ); float dotNV = saturate( dot( normal, viewDir ) ); vec2 dfgV = texture2D( dfgLUT, vec2( material.roughness, dotNV ) ).rg; vec2 dfgL = texture2D( dfgLUT, vec2( material.roughness, dotNL ) ).rg; vec3 FssEss_V = material.specularColorBlended * dfgV.x + material.specularF90 * dfgV.y; vec3 FssEss_L = material.specularColorBlended * dfgL.x + material.specularF90 * dfgL.y; float Ess_V = dfgV.x + dfgV.y; float Ess_L = dfgL.x + dfgL.y; float Ems_V = 1.0 - Ess_V; float Ems_L = 1.0 - Ess_L; vec3 Favg = material.specularColorBlended + ( 1.0 - material.specularColorBlended ) * 0.047619; vec3 Fms = FssEss_V * FssEss_L * Favg / ( 1.0 - Ems_V * Ems_L * Favg + EPSILON ); float compensationFactor = Ems_V * Ems_L; vec3 multiScatter = Fms * compensationFactor; return singleScatter + multiScatter; } #if NUM_RECT_AREA_LIGHTS > 0 void 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 ) { vec3 normal = geometryNormal; vec3 viewDir = geometryViewDir; vec3 position = geometryPosition; vec3 lightPos = rectAreaLight.position; vec3 halfWidth = rectAreaLight.halfWidth; vec3 halfHeight = rectAreaLight.halfHeight; vec3 lightColor = rectAreaLight.color; float roughness = material.roughness; vec3 rectCoords[ 4 ]; rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; vec2 uv = LTC_Uv( normal, viewDir, roughness ); vec4 t1 = texture2D( ltc_1, uv ); vec4 t2 = texture2D( ltc_2, uv ); mat3 mInv = mat3( vec3( t1.x, 0, t1.y ), vec3( 0, 1, 0 ), vec3( t1.z, 0, t1.w ) ); vec3 fresnel = ( material.specularColorBlended * t2.x + ( material.specularF90 - material.specularColorBlended ) * t2.y ); reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); reflectedLight.directDiffuse += lightColor * material.diffuseContribution * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); #ifdef USE_CLEARCOAT vec3 Ncc = geometryClearcoatNormal; vec2 uvClearcoat = LTC_Uv( Ncc, viewDir, material.clearcoatRoughness ); vec4 t1Clearcoat = texture2D( ltc_1, uvClearcoat ); vec4 t2Clearcoat = texture2D( ltc_2, uvClearcoat ); mat3 mInvClearcoat = mat3( vec3( t1Clearcoat.x, 0, t1Clearcoat.y ), vec3( 0, 1, 0 ), vec3( t1Clearcoat.z, 0, t1Clearcoat.w ) ); vec3 fresnelClearcoat = material.clearcoatF0 * t2Clearcoat.x + ( material.clearcoatF90 - material.clearcoatF0 ) * t2Clearcoat.y; clearcoatSpecularDirect += lightColor * fresnelClearcoat * LTC_Evaluate( Ncc, viewDir, position, mInvClearcoat, rectCoords ); #endif } #endif void 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 ) { float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); vec3 irradiance = dotNL * directLight.color; #ifdef USE_CLEARCOAT float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) ); vec3 ccIrradiance = dotNLcc * directLight.color; clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material ); #endif #ifdef USE_SHEEN sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness ); float sheenAlbedoV = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); float sheenAlbedoL = IBLSheenBRDF( geometryNormal, directLight.direction, material.sheenRoughness ); float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * max( sheenAlbedoV, sheenAlbedoL ); irradiance *= sheenEnergyComp; #endif reflectedLight.directSpecular += irradiance * BRDF_GGX_Multiscatter( directLight.direction, geometryViewDir, geometryNormal, material ); reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseContribution ); } void 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 ) { vec3 diffuse = irradiance * BRDF_Lambert( material.diffuseContribution ); #ifdef USE_SHEEN float sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo; diffuse *= sheenEnergyComp; #endif reflectedLight.indirectDiffuse += diffuse; } void 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) { #ifdef USE_CLEARCOAT clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); #endif #ifdef USE_SHEEN sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ) * RECIPROCAL_PI; #endif vec3 singleScatteringDielectric = vec3( 0.0 ); vec3 multiScatteringDielectric = vec3( 0.0 ); vec3 singleScatteringMetallic = vec3( 0.0 ); vec3 multiScatteringMetallic = vec3( 0.0 ); #ifdef USE_IRIDESCENCE computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnelDielectric, material.roughness, singleScatteringDielectric, multiScatteringDielectric ); computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.iridescence, material.iridescenceFresnelMetallic, material.roughness, singleScatteringMetallic, multiScatteringMetallic ); #else computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScatteringDielectric, multiScatteringDielectric ); computeMultiscattering( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.roughness, singleScatteringMetallic, multiScatteringMetallic ); #endif vec3 singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, material.metalness ); vec3 multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, material.metalness ); vec3 totalScatteringDielectric = singleScatteringDielectric + multiScatteringDielectric; vec3 diffuse = material.diffuseContribution * ( 1.0 - totalScatteringDielectric ); vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; vec3 indirectSpecular = radiance * singleScattering; indirectSpecular += multiScattering * cosineWeightedIrradiance; vec3 indirectDiffuse = diffuse * cosineWeightedIrradiance; #ifdef USE_SHEEN float sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo; indirectSpecular *= sheenEnergyComp; indirectDiffuse *= sheenEnergyComp; #endif reflectedLight.indirectSpecular += indirectSpecular; reflectedLight.indirectDiffuse += indirectDiffuse; } #define RE_Direct RE_Direct_Physical #define RE_Direct_RectArea RE_Direct_RectArea_Physical #define RE_IndirectDiffuse RE_IndirectDiffuse_Physical #define RE_IndirectSpecular RE_IndirectSpecular_Physical float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); }`,WT=` vec3 geometryPosition = - vViewPosition; vec3 geometryNormal = normal; vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); vec3 geometryClearcoatNormal = vec3( 0.0 ); #ifdef USE_CLEARCOAT geometryClearcoatNormal = clearcoatNormal; #endif #ifdef USE_IRIDESCENCE float dotNVi = saturate( dot( normal, geometryViewDir ) ); if ( material.iridescenceThickness == 0.0 ) { material.iridescence = 0.0; } else { material.iridescence = saturate( material.iridescence ); } if ( material.iridescence > 0.0 ) { material.iridescenceFresnelDielectric = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); material.iridescenceFresnelMetallic = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.diffuseColor ); material.iridescenceFresnel = mix( material.iridescenceFresnelDielectric, material.iridescenceFresnelMetallic, material.metalness ); material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); } #endif IncidentLight directLight; #if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) PointLight pointLight; #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 PointLightShadow pointLightShadow; #endif #pragma unroll_loop_start for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { pointLight = pointLights[ i ]; getPointLightInfo( pointLight, geometryPosition, directLight ); #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) ) pointLightShadow = pointLightShadows[ i ]; directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; #endif RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); } #pragma unroll_loop_end #endif #if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) SpotLight spotLight; vec4 spotColor; vec3 spotLightCoord; bool inSpotLightMap; #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 SpotLightShadow spotLightShadow; #endif #pragma unroll_loop_start for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { spotLight = spotLights[ i ]; getSpotLightInfo( spotLight, geometryPosition, directLight ); #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS #else #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) #endif #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; #endif #undef SPOT_LIGHT_MAP_INDEX #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) spotLightShadow = spotLightShadows[ i ]; directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; #endif RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); } #pragma unroll_loop_end #endif #if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) DirectionalLight directionalLight; #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 DirectionalLightShadow directionalLightShadow; #endif #pragma unroll_loop_start for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { directionalLight = directionalLights[ i ]; getDirectionalLightInfo( directionalLight, directLight ); #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) directionalLightShadow = directionalLightShadows[ i ]; directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; #endif RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); } #pragma unroll_loop_end #endif #if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) RectAreaLight rectAreaLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { rectAreaLight = rectAreaLights[ i ]; RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); } #pragma unroll_loop_end #endif #if defined( RE_IndirectDiffuse ) vec3 iblIrradiance = vec3( 0.0 ); vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); #if defined( USE_LIGHT_PROBES ) irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); #endif #if ( NUM_HEMI_LIGHTS > 0 ) #pragma unroll_loop_start for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); } #pragma unroll_loop_end #endif #ifdef USE_LIGHT_PROBES_GRID vec3 probeWorldPos = ( ( vec4( geometryPosition, 1.0 ) - viewMatrix[ 3 ] ) * viewMatrix ).xyz; vec3 probeWorldNormal = inverseTransformDirection( geometryNormal, viewMatrix ); irradiance += getLightProbeGridIrradiance( probeWorldPos, probeWorldNormal ); #endif #endif #if defined( RE_IndirectSpecular ) vec3 radiance = vec3( 0.0 ); vec3 clearcoatRadiance = vec3( 0.0 ); #endif`,$T=`#if defined( RE_IndirectDiffuse ) #ifdef USE_LIGHTMAP vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; irradiance += lightMapIrradiance; #endif #if defined( USE_ENVMAP ) && defined( ENVMAP_TYPE_CUBE_UV ) #if defined( STANDARD ) || defined( LAMBERT ) || defined( PHONG ) iblIrradiance += getIBLIrradiance( geometryNormal ); #endif #endif #endif #if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) #ifdef USE_ANISOTROPY radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy ); #else radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness ); #endif #ifdef USE_CLEARCOAT clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); #endif #endif`,XT=`#if defined( RE_IndirectDiffuse ) #if defined( LAMBERT ) || defined( PHONG ) irradiance += iblIrradiance; #endif RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); #endif #if defined( RE_IndirectSpecular ) RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); #endif`,qT=`#ifdef USE_LIGHT_PROBES_GRID uniform highp sampler3D probesSH; uniform vec3 probesMin; uniform vec3 probesMax; uniform vec3 probesResolution; vec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) { vec3 res = probesResolution; vec3 gridRange = probesMax - probesMin; vec3 resMinusOne = res - 1.0; vec3 probeSpacing = gridRange / resMinusOne; vec3 samplePos = worldPos + worldNormal * probeSpacing * 0.5; vec3 uvw = clamp( ( samplePos - probesMin ) / gridRange, 0.0, 1.0 ); uvw = uvw * resMinusOne / res + 0.5 / res; float nz = res.z; float paddedSlices = nz + 2.0; float atlasDepth = 7.0 * paddedSlices; float uvZBase = uvw.z * nz + 1.0; vec4 s0 = texture( probesSH, vec3( uvw.xy, ( uvZBase ) / atlasDepth ) ); vec4 s1 = texture( probesSH, vec3( uvw.xy, ( uvZBase + paddedSlices ) / atlasDepth ) ); vec4 s2 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 2.0 * paddedSlices ) / atlasDepth ) ); vec4 s3 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 3.0 * paddedSlices ) / atlasDepth ) ); vec4 s4 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 4.0 * paddedSlices ) / atlasDepth ) ); vec4 s5 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 5.0 * paddedSlices ) / atlasDepth ) ); vec4 s6 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 6.0 * paddedSlices ) / atlasDepth ) ); vec3 c0 = s0.xyz; vec3 c1 = vec3( s0.w, s1.xy ); vec3 c2 = vec3( s1.zw, s2.x ); vec3 c3 = s2.yzw; vec3 c4 = s3.xyz; vec3 c5 = vec3( s3.w, s4.xy ); vec3 c6 = vec3( s4.zw, s5.x ); vec3 c7 = s5.yzw; vec3 c8 = s6.xyz; float x = worldNormal.x, y = worldNormal.y, z = worldNormal.z; vec3 result = c0 * 0.886227; result += c1 * 2.0 * 0.511664 * y; result += c2 * 2.0 * 0.511664 * z; result += c3 * 2.0 * 0.511664 * x; result += c4 * 2.0 * 0.429043 * x * y; result += c5 * 2.0 * 0.429043 * y * z; result += c6 * ( 0.743125 * z * z - 0.247708 ); result += c7 * 2.0 * 0.429043 * x * z; result += c8 * 0.429043 * ( x * x - y * y ); return max( result, vec3( 0.0 ) ); } #endif`,jT=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; #endif`,YT=`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) uniform float logDepthBufFC; varying float vFragDepth; varying float vIsPerspective; #endif`,KT=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER varying float vFragDepth; varying float vIsPerspective; #endif`,ZT=`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER vFragDepth = 1.0 + gl_Position.w; vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); #endif`,QT=`#ifdef USE_MAP vec4 sampledDiffuseColor = texture2D( map, vMapUv ); #ifdef DECODE_VIDEO_TEXTURE sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); #endif diffuseColor *= sampledDiffuseColor; #endif`,JT=`#ifdef USE_MAP uniform sampler2D map; #endif`,eM=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) #if defined( USE_POINTS_UV ) vec2 uv = vUv; #else vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy; #endif #endif #ifdef USE_MAP diffuseColor *= texture2D( map, uv ); #endif #ifdef USE_ALPHAMAP diffuseColor.a *= texture2D( alphaMap, uv ).g; #endif`,tM=`#if defined( USE_POINTS_UV ) varying vec2 vUv; #else #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) uniform mat3 uvTransform; #endif #endif #ifdef USE_MAP uniform sampler2D map; #endif #ifdef USE_ALPHAMAP uniform sampler2D alphaMap; #endif`,nM=`float metalnessFactor = metalness; #ifdef USE_METALNESSMAP vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); metalnessFactor *= texelMetalness.b; #endif`,iM=`#ifdef USE_METALNESSMAP uniform sampler2D metalnessMap; #endif`,sM=`#ifdef USE_INSTANCING_MORPH float morphTargetInfluences[ MORPHTARGETS_COUNT ]; float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r; } #endif`,rM=`#if defined( USE_MORPHCOLORS ) vColor *= morphTargetBaseInfluence; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { #if defined( USE_COLOR_ALPHA ) if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ]; #elif defined( USE_COLOR ) if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; #endif } #endif`,oM=`#ifdef USE_MORPHNORMALS objectNormal *= morphTargetBaseInfluence; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; } #endif`,aM=`#ifdef USE_MORPHTARGETS #ifndef USE_INSTANCING_MORPH uniform float morphTargetBaseInfluence; uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; #endif uniform sampler2DArray morphTargetsTexture; uniform ivec2 morphTargetsTextureSize; vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) { int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset; int y = texelIndex / morphTargetsTextureSize.x; int x = texelIndex - y * morphTargetsTextureSize.x; ivec3 morphUV = ivec3( x, y, morphTargetIndex ); return texelFetch( morphTargetsTexture, morphUV, 0 ); } #endif`,lM=`#ifdef USE_MORPHTARGETS transformed *= morphTargetBaseInfluence; for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; } #endif`,cM=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; #ifdef FLAT_SHADED vec3 fdx = dFdx( vViewPosition ); vec3 fdy = dFdy( vViewPosition ); vec3 normal = normalize( cross( fdx, fdy ) ); #else vec3 normal = normalize( vNormal ); #ifdef DOUBLE_SIDED normal *= faceDirection; #endif #endif #if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) #ifdef USE_TANGENT mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); #else mat3 tbn = getTangentFrame( - vViewPosition, normal, #if defined( USE_NORMALMAP ) vNormalMapUv #elif defined( USE_CLEARCOAT_NORMALMAP ) vClearcoatNormalMapUv #else vUv #endif ); #endif #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) tbn[0] *= faceDirection; tbn[1] *= faceDirection; #endif #endif #ifdef USE_CLEARCOAT_NORMALMAP #ifdef USE_TANGENT mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); #else mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); #endif #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) tbn2[0] *= faceDirection; tbn2[1] *= faceDirection; #endif #endif vec3 nonPerturbedNormal = normal;`,uM=`#ifdef USE_NORMALMAP_OBJECTSPACE normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; #ifdef FLIP_SIDED normal = - normal; #endif #ifdef DOUBLE_SIDED normal = normal * faceDirection; #endif normal = normalize( normalMatrix * normal ); #elif defined( USE_NORMALMAP_TANGENTSPACE ) vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; #if defined( USE_PACKED_NORMALMAP ) mapN = vec3( mapN.xy, sqrt( saturate( 1.0 - dot( mapN.xy, mapN.xy ) ) ) ); #endif mapN.xy *= normalScale; normal = normalize( tbn * mapN ); #elif defined( USE_BUMPMAP ) normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); #endif`,hM=`#ifndef FLAT_SHADED varying vec3 vNormal; #ifdef USE_TANGENT varying vec3 vTangent; varying vec3 vBitangent; #endif #endif`,dM=`#ifndef FLAT_SHADED varying vec3 vNormal; #ifdef USE_TANGENT varying vec3 vTangent; varying vec3 vBitangent; #endif #endif`,fM=`#ifndef FLAT_SHADED vNormal = normalize( transformedNormal ); #ifdef USE_TANGENT vTangent = normalize( transformedTangent ); vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); #endif #endif`,pM=`#ifdef USE_NORMALMAP uniform sampler2D normalMap; uniform vec2 normalScale; #endif #ifdef USE_NORMALMAP_OBJECTSPACE uniform mat3 normalMatrix; #endif #if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) ) mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) { vec3 q0 = dFdx( eye_pos.xyz ); vec3 q1 = dFdy( eye_pos.xyz ); vec2 st0 = dFdx( uv.st ); vec2 st1 = dFdy( uv.st ); vec3 N = surf_norm; vec3 q1perp = cross( q1, N ); vec3 q0perp = cross( N, q0 ); vec3 T = q1perp * st0.x + q0perp * st1.x; vec3 B = q1perp * st0.y + q0perp * st1.y; float det = max( dot( T, T ), dot( B, B ) ); float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); return mat3( T * scale, B * scale, N ); } #endif`,mM=`#ifdef USE_CLEARCOAT vec3 clearcoatNormal = nonPerturbedNormal; #endif`,gM=`#ifdef USE_CLEARCOAT_NORMALMAP vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; clearcoatMapN.xy *= clearcoatNormalScale; clearcoatNormal = normalize( tbn2 * clearcoatMapN ); #endif`,_M=`#ifdef USE_CLEARCOATMAP uniform sampler2D clearcoatMap; #endif #ifdef USE_CLEARCOAT_NORMALMAP uniform sampler2D clearcoatNormalMap; uniform vec2 clearcoatNormalScale; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP uniform sampler2D clearcoatRoughnessMap; #endif`,xM=`#ifdef USE_IRIDESCENCEMAP uniform sampler2D iridescenceMap; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP uniform sampler2D iridescenceThicknessMap; #endif`,yM=`#ifdef OPAQUE diffuseColor.a = 1.0; #endif #ifdef USE_TRANSMISSION diffuseColor.a *= material.transmissionAlpha; #endif gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,vM=`vec3 packNormalToRGB( const in vec3 normal ) { return normalize( normal ) * 0.5 + 0.5; } vec3 unpackRGBToNormal( const in vec3 rgb ) { return 2.0 * rgb.xyz - 1.0; } const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.; const float Inv255 = 1. / 255.; const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 ); const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g ); const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b ); const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a ); vec4 packDepthToRGBA( const in float v ) { if( v <= 0.0 ) return vec4( 0., 0., 0., 0. ); if( v >= 1.0 ) return vec4( 1., 1., 1., 1. ); float vuf; float af = modf( v * PackFactors.a, vuf ); float bf = modf( vuf * ShiftRight8, vuf ); float gf = modf( vuf * ShiftRight8, vuf ); return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af ); } vec3 packDepthToRGB( const in float v ) { if( v <= 0.0 ) return vec3( 0., 0., 0. ); if( v >= 1.0 ) return vec3( 1., 1., 1. ); float vuf; float bf = modf( v * PackFactors.b, vuf ); float gf = modf( vuf * ShiftRight8, vuf ); return vec3( vuf * Inv255, gf * PackUpscale, bf ); } vec2 packDepthToRG( const in float v ) { if( v <= 0.0 ) return vec2( 0., 0. ); if( v >= 1.0 ) return vec2( 1., 1. ); float vuf; float gf = modf( v * 256., vuf ); return vec2( vuf * Inv255, gf ); } float unpackRGBAToDepth( const in vec4 v ) { return dot( v, UnpackFactors4 ); } float unpackRGBToDepth( const in vec3 v ) { return dot( v, UnpackFactors3 ); } float unpackRGToDepth( const in vec2 v ) { return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g; } vec4 pack2HalfToRGBA( const in vec2 v ) { vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); } vec2 unpackRGBATo2Half( const in vec4 v ) { return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); } float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { return ( viewZ + near ) / ( near - far ); } float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) { #ifdef USE_REVERSED_DEPTH_BUFFER return depth * ( far - near ) - far; #else return depth * ( near - far ) - near; #endif } float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); } float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { #ifdef USE_REVERSED_DEPTH_BUFFER return ( near * far ) / ( ( near - far ) * depth - near ); #else return ( near * far ) / ( ( far - near ) * depth - far ); #endif }`,SM=`#ifdef PREMULTIPLIED_ALPHA gl_FragColor.rgb *= gl_FragColor.a; #endif`,bM=`vec4 mvPosition = vec4( transformed, 1.0 ); #ifdef USE_BATCHING mvPosition = batchingMatrix * mvPosition; #endif #ifdef USE_INSTANCING mvPosition = instanceMatrix * mvPosition; #endif mvPosition = modelViewMatrix * mvPosition; gl_Position = projectionMatrix * mvPosition;`,TM=`#ifdef DITHERING gl_FragColor.rgb = dithering( gl_FragColor.rgb ); #endif`,MM=`#ifdef DITHERING vec3 dithering( vec3 color ) { float grid_position = rand( gl_FragCoord.xy ); vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); return color + dither_shift_RGB; } #endif`,EM=`float roughnessFactor = roughness; #ifdef USE_ROUGHNESSMAP vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); roughnessFactor *= texelRoughness.g; #endif`,AM=`#ifdef USE_ROUGHNESSMAP uniform sampler2D roughnessMap; #endif`,RM=`#if NUM_SPOT_LIGHT_COORDS > 0 varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; #endif #if NUM_SPOT_LIGHT_MAPS > 0 uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ]; #endif #ifdef USE_SHADOWMAP #if NUM_DIR_LIGHT_SHADOWS > 0 #if defined( SHADOWMAP_TYPE_PCF ) uniform sampler2DShadow directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; #else uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; #endif varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; struct DirectionalLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; #endif #if NUM_SPOT_LIGHT_SHADOWS > 0 #if defined( SHADOWMAP_TYPE_PCF ) uniform sampler2DShadow spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; #else uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; #endif struct SpotLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; #endif #if NUM_POINT_LIGHT_SHADOWS > 0 #if defined( SHADOWMAP_TYPE_PCF ) uniform samplerCubeShadow pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; #elif defined( SHADOWMAP_TYPE_BASIC ) uniform samplerCube pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; #endif varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; struct PointLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; float shadowCameraNear; float shadowCameraFar; }; uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; #endif #if defined( SHADOWMAP_TYPE_PCF ) float interleavedGradientNoise( vec2 position ) { return fract( 52.9829189 * fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) ); } vec2 vogelDiskSample( int sampleIndex, int samplesCount, float phi ) { const float goldenAngle = 2.399963229728653; float r = sqrt( ( float( sampleIndex ) + 0.5 ) / float( samplesCount ) ); float theta = float( sampleIndex ) * goldenAngle + phi; return vec2( cos( theta ), sin( theta ) ) * r; } #endif #if defined( SHADOWMAP_TYPE_PCF ) float getShadow( sampler2DShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { float shadow = 1.0; shadowCoord.xyz /= shadowCoord.w; shadowCoord.z += shadowBias; bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; bool frustumTest = inFrustum && shadowCoord.z <= 1.0; if ( frustumTest ) { vec2 texelSize = vec2( 1.0 ) / shadowMapSize; float radius = shadowRadius * texelSize.x; float phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2; shadow = ( texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 0, 5, phi ) * radius, shadowCoord.z ) ) + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 1, 5, phi ) * radius, shadowCoord.z ) ) + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 2, 5, phi ) * radius, shadowCoord.z ) ) + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 3, 5, phi ) * radius, shadowCoord.z ) ) + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 4, 5, phi ) * radius, shadowCoord.z ) ) ) * 0.2; } return mix( 1.0, shadow, shadowIntensity ); } #elif defined( SHADOWMAP_TYPE_VSM ) float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { float shadow = 1.0; shadowCoord.xyz /= shadowCoord.w; #ifdef USE_REVERSED_DEPTH_BUFFER shadowCoord.z -= shadowBias; #else shadowCoord.z += shadowBias; #endif bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; bool frustumTest = inFrustum && shadowCoord.z <= 1.0; if ( frustumTest ) { vec2 distribution = texture2D( shadowMap, shadowCoord.xy ).rg; float mean = distribution.x; float variance = distribution.y * distribution.y; #ifdef USE_REVERSED_DEPTH_BUFFER float hard_shadow = step( mean, shadowCoord.z ); #else float hard_shadow = step( shadowCoord.z, mean ); #endif if ( hard_shadow == 1.0 ) { shadow = 1.0; } else { variance = max( variance, 0.0000001 ); float d = shadowCoord.z - mean; float p_max = variance / ( variance + d * d ); p_max = clamp( ( p_max - 0.3 ) / 0.65, 0.0, 1.0 ); shadow = max( hard_shadow, p_max ); } } return mix( 1.0, shadow, shadowIntensity ); } #else float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { float shadow = 1.0; shadowCoord.xyz /= shadowCoord.w; #ifdef USE_REVERSED_DEPTH_BUFFER shadowCoord.z -= shadowBias; #else shadowCoord.z += shadowBias; #endif bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; bool frustumTest = inFrustum && shadowCoord.z <= 1.0; if ( frustumTest ) { float depth = texture2D( shadowMap, shadowCoord.xy ).r; #ifdef USE_REVERSED_DEPTH_BUFFER shadow = step( depth, shadowCoord.z ); #else shadow = step( shadowCoord.z, depth ); #endif } return mix( 1.0, shadow, shadowIntensity ); } #endif #if NUM_POINT_LIGHT_SHADOWS > 0 #if defined( SHADOWMAP_TYPE_PCF ) float getPointShadow( samplerCubeShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { float shadow = 1.0; vec3 lightToPosition = shadowCoord.xyz; vec3 bd3D = normalize( lightToPosition ); vec3 absVec = abs( lightToPosition ); float viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z ); if ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) { #ifdef USE_REVERSED_DEPTH_BUFFER float dp = ( shadowCameraNear * ( shadowCameraFar - viewSpaceZ ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) ); dp -= shadowBias; #else float dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) ); dp += shadowBias; #endif float texelSize = shadowRadius / shadowMapSize.x; vec3 absDir = abs( bd3D ); vec3 tangent = absDir.x > absDir.z ? vec3( 0.0, 1.0, 0.0 ) : vec3( 1.0, 0.0, 0.0 ); tangent = normalize( cross( bd3D, tangent ) ); vec3 bitangent = cross( bd3D, tangent ); float phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2; vec2 sample0 = vogelDiskSample( 0, 5, phi ); vec2 sample1 = vogelDiskSample( 1, 5, phi ); vec2 sample2 = vogelDiskSample( 2, 5, phi ); vec2 sample3 = vogelDiskSample( 3, 5, phi ); vec2 sample4 = vogelDiskSample( 4, 5, phi ); shadow = ( texture( shadowMap, vec4( bd3D + ( tangent * sample0.x + bitangent * sample0.y ) * texelSize, dp ) ) + texture( shadowMap, vec4( bd3D + ( tangent * sample1.x + bitangent * sample1.y ) * texelSize, dp ) ) + texture( shadowMap, vec4( bd3D + ( tangent * sample2.x + bitangent * sample2.y ) * texelSize, dp ) ) + texture( shadowMap, vec4( bd3D + ( tangent * sample3.x + bitangent * sample3.y ) * texelSize, dp ) ) + texture( shadowMap, vec4( bd3D + ( tangent * sample4.x + bitangent * sample4.y ) * texelSize, dp ) ) ) * 0.2; } return mix( 1.0, shadow, shadowIntensity ); } #elif defined( SHADOWMAP_TYPE_BASIC ) float getPointShadow( samplerCube shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { float shadow = 1.0; vec3 lightToPosition = shadowCoord.xyz; vec3 absVec = abs( lightToPosition ); float viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z ); if ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) { float dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) ); dp += shadowBias; vec3 bd3D = normalize( lightToPosition ); float depth = textureCube( shadowMap, bd3D ).r; #ifdef USE_REVERSED_DEPTH_BUFFER depth = 1.0 - depth; #endif shadow = step( dp, depth ); } return mix( 1.0, shadow, shadowIntensity ); } #endif #endif #endif`,wM=`#if NUM_SPOT_LIGHT_COORDS > 0 uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; #endif #ifdef USE_SHADOWMAP #if NUM_DIR_LIGHT_SHADOWS > 0 uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ]; varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; struct DirectionalLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; #endif #if NUM_SPOT_LIGHT_SHADOWS > 0 struct SpotLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; }; uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; #endif #if NUM_POINT_LIGHT_SHADOWS > 0 uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ]; varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; struct PointLightShadow { float shadowIntensity; float shadowBias; float shadowNormalBias; float shadowRadius; vec2 shadowMapSize; float shadowCameraNear; float shadowCameraFar; }; uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; #endif #endif`,CM=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) #ifdef HAS_NORMAL vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); #else vec3 shadowWorldNormal = vec3( 0.0 ); #endif vec4 shadowWorldPosition; #endif #if defined( USE_SHADOWMAP ) #if NUM_DIR_LIGHT_SHADOWS > 0 #pragma unroll_loop_start for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; } #pragma unroll_loop_end #endif #if NUM_POINT_LIGHT_SHADOWS > 0 #pragma unroll_loop_start for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; } #pragma unroll_loop_end #endif #endif #if NUM_SPOT_LIGHT_COORDS > 0 #pragma unroll_loop_start for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) { shadowWorldPosition = worldPosition; #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias; #endif vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; } #pragma unroll_loop_end #endif`,NM=`float getShadowMask() { float shadow = 1.0; #ifdef USE_SHADOWMAP #if NUM_DIR_LIGHT_SHADOWS > 0 DirectionalLightShadow directionalLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { directionalLight = directionalLightShadows[ i ]; shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; } #pragma unroll_loop_end #endif #if NUM_SPOT_LIGHT_SHADOWS > 0 SpotLightShadow spotLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { spotLight = spotLightShadows[ i ]; shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; } #pragma unroll_loop_end #endif #if NUM_POINT_LIGHT_SHADOWS > 0 && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) ) PointLightShadow pointLight; #pragma unroll_loop_start for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { pointLight = pointLightShadows[ i ]; shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; } #pragma unroll_loop_end #endif #endif return shadow; }`,PM=`#ifdef USE_SKINNING mat4 boneMatX = getBoneMatrix( skinIndex.x ); mat4 boneMatY = getBoneMatrix( skinIndex.y ); mat4 boneMatZ = getBoneMatrix( skinIndex.z ); mat4 boneMatW = getBoneMatrix( skinIndex.w ); #endif`,DM=`#ifdef USE_SKINNING uniform mat4 bindMatrix; uniform mat4 bindMatrixInverse; uniform highp sampler2D boneTexture; mat4 getBoneMatrix( const in float i ) { int size = textureSize( boneTexture, 0 ).x; int j = int( i ) * 4; int x = j % size; int y = j / size; vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); return mat4( v1, v2, v3, v4 ); } #endif`,LM=`#ifdef USE_SKINNING vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); vec4 skinned = vec4( 0.0 ); skinned += boneMatX * skinVertex * skinWeight.x; skinned += boneMatY * skinVertex * skinWeight.y; skinned += boneMatZ * skinVertex * skinWeight.z; skinned += boneMatW * skinVertex * skinWeight.w; transformed = ( bindMatrixInverse * skinned ).xyz; #endif`,UM=`#ifdef USE_SKINNING mat4 skinMatrix = mat4( 0.0 ); skinMatrix += skinWeight.x * boneMatX; skinMatrix += skinWeight.y * boneMatY; skinMatrix += skinWeight.z * boneMatZ; skinMatrix += skinWeight.w * boneMatW; skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; #ifdef USE_TANGENT objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; #endif #endif`,FM=`float specularStrength; #ifdef USE_SPECULARMAP vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); specularStrength = texelSpecular.r; #else specularStrength = 1.0; #endif`,IM=`#ifdef USE_SPECULARMAP uniform sampler2D specularMap; #endif`,BM=`#if defined( TONE_MAPPING ) gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); #endif`,OM=`#ifndef saturate #define saturate( a ) clamp( a, 0.0, 1.0 ) #endif uniform float toneMappingExposure; vec3 LinearToneMapping( vec3 color ) { return saturate( toneMappingExposure * color ); } vec3 ReinhardToneMapping( vec3 color ) { color *= toneMappingExposure; return saturate( color / ( vec3( 1.0 ) + color ) ); } vec3 CineonToneMapping( vec3 color ) { color *= toneMappingExposure; color = max( vec3( 0.0 ), color - 0.004 ); return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); } vec3 RRTAndODTFit( vec3 v ) { vec3 a = v * ( v + 0.0245786 ) - 0.000090537; vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; return a / b; } vec3 ACESFilmicToneMapping( vec3 color ) { const mat3 ACESInputMat = mat3( vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ), vec3( 0.04823, 0.01566, 0.83777 ) ); const mat3 ACESOutputMat = mat3( vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ), vec3( -0.07367, -0.00605, 1.07602 ) ); color *= toneMappingExposure / 0.6; color = ACESInputMat * color; color = RRTAndODTFit( color ); color = ACESOutputMat * color; return saturate( color ); } const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3( vec3( 1.6605, - 0.1246, - 0.0182 ), vec3( - 0.5876, 1.1329, - 0.1006 ), vec3( - 0.0728, - 0.0083, 1.1187 ) ); const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( vec3( 0.6274, 0.0691, 0.0164 ), vec3( 0.3293, 0.9195, 0.0880 ), vec3( 0.0433, 0.0113, 0.8956 ) ); vec3 agxDefaultContrastApprox( vec3 x ) { vec3 x2 = x * x; vec3 x4 = x2 * x2; return + 15.5 * x4 * x2 - 40.14 * x4 * x + 31.96 * x4 - 6.868 * x2 * x + 0.4298 * x2 + 0.1191 * x - 0.00232; } vec3 AgXToneMapping( vec3 color ) { const mat3 AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) ); const mat3 AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) ); const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069; color *= toneMappingExposure; color = LINEAR_SRGB_TO_LINEAR_REC2020 * color; color = AgXInsetMatrix * color; color = max( color, 1e-10 ); color = log2( color ); color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv ); color = clamp( color, 0.0, 1.0 ); color = agxDefaultContrastApprox( color ); color = AgXOutsetMatrix * color; color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) ); color = LINEAR_REC2020_TO_LINEAR_SRGB * color; color = clamp( color, 0.0, 1.0 ); return color; } vec3 NeutralToneMapping( vec3 color ) { const float StartCompression = 0.8 - 0.04; const float Desaturation = 0.15; color *= toneMappingExposure; float x = min( color.r, min( color.g, color.b ) ); float offset = x < 0.08 ? x - 6.25 * x * x : 0.04; color -= offset; float peak = max( color.r, max( color.g, color.b ) ); if ( peak < StartCompression ) return color; float d = 1. - StartCompression; float newPeak = 1. - d * d / ( peak + d - StartCompression ); color *= newPeak / peak; float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. ); return mix( color, vec3( newPeak ), g ); } vec3 CustomToneMapping( vec3 color ) { return color; }`,kM=`#ifdef USE_TRANSMISSION material.transmission = transmission; material.transmissionAlpha = 1.0; material.thickness = thickness; material.attenuationDistance = attenuationDistance; material.attenuationColor = attenuationColor; #ifdef USE_TRANSMISSIONMAP material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r; #endif #ifdef USE_THICKNESSMAP material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g; #endif vec3 pos = vWorldPosition; vec3 v = normalize( cameraPosition - pos ); vec3 n = inverseTransformDirection( normal, viewMatrix ); vec4 transmitted = getIBLVolumeRefraction( n, v, material.roughness, material.diffuseContribution, material.specularColorBlended, material.specularF90, pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness, material.attenuationColor, material.attenuationDistance ); material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); #endif`,GM=`#ifdef USE_TRANSMISSION uniform float transmission; uniform float thickness; uniform float attenuationDistance; uniform vec3 attenuationColor; #ifdef USE_TRANSMISSIONMAP uniform sampler2D transmissionMap; #endif #ifdef USE_THICKNESSMAP uniform sampler2D thicknessMap; #endif uniform vec2 transmissionSamplerSize; uniform sampler2D transmissionSamplerMap; uniform mat4 modelMatrix; uniform mat4 projectionMatrix; varying vec3 vWorldPosition; float w0( float a ) { return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 ); } float w1( float a ) { return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 ); } float w2( float a ){ return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 ); } float w3( float a ) { return ( 1.0 / 6.0 ) * ( a * a * a ); } float g0( float a ) { return w0( a ) + w1( a ); } float g1( float a ) { return w2( a ) + w3( a ); } float h0( float a ) { return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) ); } float h1( float a ) { return 1.0 + w3( a ) / ( w2( a ) + w3( a ) ); } vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) { uv = uv * texelSize.zw + 0.5; vec2 iuv = floor( uv ); vec2 fuv = fract( uv ); float g0x = g0( fuv.x ); float g1x = g1( fuv.x ); float h0x = h0( fuv.x ); float h1x = h1( fuv.x ); float h0y = h0( fuv.y ); float h1y = h1( fuv.y ); vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) + g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) ); } vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) { vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) ); vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) ); vec2 fLodSizeInv = 1.0 / fLodSize; vec2 cLodSizeInv = 1.0 / cLodSize; vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) ); vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) ); return mix( fSample, cSample, fract( lod ) ); } vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); vec3 modelScale; modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); return normalize( refractionVector ) * thickness * modelScale; } float applyIorToRoughness( const in float roughness, const in float ior ) { return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); } vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ); } vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { if ( isinf( attenuationDistance ) ) { return vec3( 1.0 ); } else { vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance; } } vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness, const in vec3 attenuationColor, const in float attenuationDistance ) { vec4 transmittedLight; vec3 transmittance; #ifdef USE_DISPERSION float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion; vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread ); for ( int i = 0; i < 3; i ++ ) { vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix ); vec3 refractedRayExit = position + transmissionRay; vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); vec2 refractionCoords = ndcPos.xy / ndcPos.w; refractionCoords += 1.0; refractionCoords /= 2.0; vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] ); transmittedLight[ i ] = transmissionSample[ i ]; transmittedLight.a += transmissionSample.a; transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ]; } transmittedLight.a /= 3.0; #else vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); vec3 refractedRayExit = position + transmissionRay; vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); vec2 refractionCoords = ndcPos.xy / ndcPos.w; refractionCoords += 1.0; refractionCoords /= 2.0; transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ); #endif vec3 attenuatedColor = transmittance * transmittedLight.rgb; vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); } #endif`,VM=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) varying vec2 vUv; #endif #ifdef USE_MAP varying vec2 vMapUv; #endif #ifdef USE_ALPHAMAP varying vec2 vAlphaMapUv; #endif #ifdef USE_LIGHTMAP varying vec2 vLightMapUv; #endif #ifdef USE_AOMAP varying vec2 vAoMapUv; #endif #ifdef USE_BUMPMAP varying vec2 vBumpMapUv; #endif #ifdef USE_NORMALMAP varying vec2 vNormalMapUv; #endif #ifdef USE_EMISSIVEMAP varying vec2 vEmissiveMapUv; #endif #ifdef USE_METALNESSMAP varying vec2 vMetalnessMapUv; #endif #ifdef USE_ROUGHNESSMAP varying vec2 vRoughnessMapUv; #endif #ifdef USE_ANISOTROPYMAP varying vec2 vAnisotropyMapUv; #endif #ifdef USE_CLEARCOATMAP varying vec2 vClearcoatMapUv; #endif #ifdef USE_CLEARCOAT_NORMALMAP varying vec2 vClearcoatNormalMapUv; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP varying vec2 vClearcoatRoughnessMapUv; #endif #ifdef USE_IRIDESCENCEMAP varying vec2 vIridescenceMapUv; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP varying vec2 vIridescenceThicknessMapUv; #endif #ifdef USE_SHEEN_COLORMAP varying vec2 vSheenColorMapUv; #endif #ifdef USE_SHEEN_ROUGHNESSMAP varying vec2 vSheenRoughnessMapUv; #endif #ifdef USE_SPECULARMAP varying vec2 vSpecularMapUv; #endif #ifdef USE_SPECULAR_COLORMAP varying vec2 vSpecularColorMapUv; #endif #ifdef USE_SPECULAR_INTENSITYMAP varying vec2 vSpecularIntensityMapUv; #endif #ifdef USE_TRANSMISSIONMAP uniform mat3 transmissionMapTransform; varying vec2 vTransmissionMapUv; #endif #ifdef USE_THICKNESSMAP uniform mat3 thicknessMapTransform; varying vec2 vThicknessMapUv; #endif`,zM=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) varying vec2 vUv; #endif #ifdef USE_MAP uniform mat3 mapTransform; varying vec2 vMapUv; #endif #ifdef USE_ALPHAMAP uniform mat3 alphaMapTransform; varying vec2 vAlphaMapUv; #endif #ifdef USE_LIGHTMAP uniform mat3 lightMapTransform; varying vec2 vLightMapUv; #endif #ifdef USE_AOMAP uniform mat3 aoMapTransform; varying vec2 vAoMapUv; #endif #ifdef USE_BUMPMAP uniform mat3 bumpMapTransform; varying vec2 vBumpMapUv; #endif #ifdef USE_NORMALMAP uniform mat3 normalMapTransform; varying vec2 vNormalMapUv; #endif #ifdef USE_DISPLACEMENTMAP uniform mat3 displacementMapTransform; varying vec2 vDisplacementMapUv; #endif #ifdef USE_EMISSIVEMAP uniform mat3 emissiveMapTransform; varying vec2 vEmissiveMapUv; #endif #ifdef USE_METALNESSMAP uniform mat3 metalnessMapTransform; varying vec2 vMetalnessMapUv; #endif #ifdef USE_ROUGHNESSMAP uniform mat3 roughnessMapTransform; varying vec2 vRoughnessMapUv; #endif #ifdef USE_ANISOTROPYMAP uniform mat3 anisotropyMapTransform; varying vec2 vAnisotropyMapUv; #endif #ifdef USE_CLEARCOATMAP uniform mat3 clearcoatMapTransform; varying vec2 vClearcoatMapUv; #endif #ifdef USE_CLEARCOAT_NORMALMAP uniform mat3 clearcoatNormalMapTransform; varying vec2 vClearcoatNormalMapUv; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP uniform mat3 clearcoatRoughnessMapTransform; varying vec2 vClearcoatRoughnessMapUv; #endif #ifdef USE_SHEEN_COLORMAP uniform mat3 sheenColorMapTransform; varying vec2 vSheenColorMapUv; #endif #ifdef USE_SHEEN_ROUGHNESSMAP uniform mat3 sheenRoughnessMapTransform; varying vec2 vSheenRoughnessMapUv; #endif #ifdef USE_IRIDESCENCEMAP uniform mat3 iridescenceMapTransform; varying vec2 vIridescenceMapUv; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP uniform mat3 iridescenceThicknessMapTransform; varying vec2 vIridescenceThicknessMapUv; #endif #ifdef USE_SPECULARMAP uniform mat3 specularMapTransform; varying vec2 vSpecularMapUv; #endif #ifdef USE_SPECULAR_COLORMAP uniform mat3 specularColorMapTransform; varying vec2 vSpecularColorMapUv; #endif #ifdef USE_SPECULAR_INTENSITYMAP uniform mat3 specularIntensityMapTransform; varying vec2 vSpecularIntensityMapUv; #endif #ifdef USE_TRANSMISSIONMAP uniform mat3 transmissionMapTransform; varying vec2 vTransmissionMapUv; #endif #ifdef USE_THICKNESSMAP uniform mat3 thicknessMapTransform; varying vec2 vThicknessMapUv; #endif`,HM=`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) vUv = vec3( uv, 1 ).xy; #endif #ifdef USE_MAP vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy; #endif #ifdef USE_ALPHAMAP vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy; #endif #ifdef USE_LIGHTMAP vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy; #endif #ifdef USE_AOMAP vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy; #endif #ifdef USE_BUMPMAP vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy; #endif #ifdef USE_NORMALMAP vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy; #endif #ifdef USE_DISPLACEMENTMAP vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy; #endif #ifdef USE_EMISSIVEMAP vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy; #endif #ifdef USE_METALNESSMAP vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_ROUGHNESSMAP vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_ANISOTROPYMAP vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy; #endif #ifdef USE_CLEARCOATMAP vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy; #endif #ifdef USE_CLEARCOAT_NORMALMAP vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy; #endif #ifdef USE_CLEARCOAT_ROUGHNESSMAP vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_IRIDESCENCEMAP vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy; #endif #ifdef USE_IRIDESCENCE_THICKNESSMAP vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_SHEEN_COLORMAP vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy; #endif #ifdef USE_SHEEN_ROUGHNESSMAP vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy; #endif #ifdef USE_SPECULARMAP vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy; #endif #ifdef USE_SPECULAR_COLORMAP vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy; #endif #ifdef USE_SPECULAR_INTENSITYMAP vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy; #endif #ifdef USE_TRANSMISSIONMAP vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy; #endif #ifdef USE_THICKNESSMAP vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; #endif`,WM=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 vec4 worldPosition = vec4( transformed, 1.0 ); #ifdef USE_BATCHING worldPosition = batchingMatrix * worldPosition; #endif #ifdef USE_INSTANCING worldPosition = instanceMatrix * worldPosition; #endif worldPosition = modelMatrix * worldPosition; #endif`;const $M=`varying vec2 vUv; uniform mat3 uvTransform; void main() { vUv = ( uvTransform * vec3( uv, 1 ) ).xy; gl_Position = vec4( position.xy, 1.0, 1.0 ); }`,XM=`uniform sampler2D t2D; uniform float backgroundIntensity; varying vec2 vUv; void main() { vec4 texColor = texture2D( t2D, vUv ); #ifdef DECODE_VIDEO_TEXTURE texColor = 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 ); #endif texColor.rgb *= backgroundIntensity; gl_FragColor = texColor; #include #include }`,qM=`varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include gl_Position.z = gl_Position.w; }`,jM=`#ifdef ENVMAP_TYPE_CUBE uniform samplerCube envMap; #elif defined( ENVMAP_TYPE_CUBE_UV ) uniform sampler2D envMap; #endif uniform float backgroundBlurriness; uniform float backgroundIntensity; uniform mat3 backgroundRotation; varying vec3 vWorldDirection; #include void main() { #ifdef ENVMAP_TYPE_CUBE vec4 texColor = textureCube( envMap, backgroundRotation * vWorldDirection ); #elif defined( ENVMAP_TYPE_CUBE_UV ) vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness ); #else vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 ); #endif texColor.rgb *= backgroundIntensity; gl_FragColor = texColor; #include #include }`,YM=`varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include gl_Position.z = gl_Position.w; }`,KM=`uniform samplerCube tCube; uniform float tFlip; uniform float opacity; varying vec3 vWorldDirection; void main() { vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) ); gl_FragColor = texColor; gl_FragColor.a *= opacity; #include #include }`,ZM=`#include #include #include #include #include #include #include #include varying vec2 vHighPrecisionZW; void main() { #include #include #include #include #ifdef USE_DISPLACEMENTMAP #include #include #include #endif #include #include #include #include #include #include #include vHighPrecisionZW = gl_Position.zw; }`,QM=`#if DEPTH_PACKING == 3200 uniform float opacity; #endif #include #include #include #include #include #include #include #include #include varying vec2 vHighPrecisionZW; void main() { vec4 diffuseColor = vec4( 1.0 ); #include #if DEPTH_PACKING == 3200 diffuseColor.a = opacity; #endif #include #include #include #include #include #ifdef USE_REVERSED_DEPTH_BUFFER float fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ]; #else float fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5; #endif #if DEPTH_PACKING == 3200 gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); #elif DEPTH_PACKING == 3201 gl_FragColor = packDepthToRGBA( fragCoordZ ); #elif DEPTH_PACKING == 3202 gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 ); #elif DEPTH_PACKING == 3203 gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 ); #endif }`,JM=`#define DISTANCE varying vec3 vWorldPosition; #include #include #include #include #include #include #include void main() { #include #include #include #include #ifdef USE_DISPLACEMENTMAP #include #include #include #endif #include #include #include #include #include #include #include vWorldPosition = worldPosition.xyz; }`,eE=`#define DISTANCE uniform vec3 referencePosition; uniform float nearDistance; uniform float farDistance; varying vec3 vWorldPosition; #include #include #include #include #include #include #include void main () { vec4 diffuseColor = vec4( 1.0 ); #include #include #include #include #include float dist = length( vWorldPosition - referencePosition ); dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); dist = saturate( dist ); gl_FragColor = vec4( dist, 0.0, 0.0, 1.0 ); }`,tE=`varying vec3 vWorldDirection; #include void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include }`,nE=`uniform sampler2D tEquirect; varying vec3 vWorldDirection; #include void main() { vec3 direction = normalize( vWorldDirection ); vec2 sampleUV = equirectUv( direction ); gl_FragColor = texture2D( tEquirect, sampleUV ); #include #include }`,iE=`uniform float scale; attribute float lineDistance; varying float vLineDistance; #include #include #include #include #include #include #include void main() { vLineDistance = scale * lineDistance; #include #include #include #include #include #include #include #include #include #include }`,sE=`uniform vec3 diffuse; uniform float opacity; uniform float dashSize; uniform float totalSize; varying float vLineDistance; #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include if ( mod( vLineDistance, totalSize ) > dashSize ) { discard; } vec3 outgoingLight = vec3( 0.0 ); #include #include #include outgoingLight = diffuseColor.rgb; #include #include #include #include #include }`,rE=`#include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) #include #include #include #include #include #endif #include #include #include #include #include #include #include #include #include }`,oE=`uniform vec3 diffuse; uniform float opacity; #ifndef FLAT_SHADED varying vec3 vNormal; #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include #include #include #include #include #include #include #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); #ifdef USE_LIGHTMAP vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI; #else reflectedLight.indirectDiffuse += vec3( 1.0 ); #endif #include reflectedLight.indirectDiffuse *= diffuseColor.rgb; vec3 outgoingLight = reflectedLight.indirectDiffuse; #include #include #include #include #include #include #include }`,aE=`#define LAMBERT varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; #include #include #include #include }`,lE=`#define LAMBERT uniform vec3 diffuse; uniform vec3 emissive; uniform float opacity; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); vec3 totalEmissiveRadiance = emissive; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; #include #include #include #include #include #include #include }`,cE=`#define MATCAP varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; }`,uE=`#define MATCAP uniform vec3 diffuse; uniform float opacity; uniform sampler2D matcap; varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include #include #include #include #include #include #include #include #include vec3 viewDir = normalize( vViewPosition ); vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); vec3 y = cross( viewDir, x ); vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; #ifdef USE_MATCAP vec4 matcapColor = texture2D( matcap, uv ); #else vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 ); #endif vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb; #include #include #include #include #include #include }`,hE=`#define NORMAL #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) varying vec3 vViewPosition; #endif #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) vViewPosition = - mvPosition.xyz; #endif }`,dE=`#define NORMAL uniform float opacity; #if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) varying vec3 vViewPosition; #endif #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity ); #include #include #include #include gl_FragColor = vec4( normalize( normal ) * 0.5 + 0.5, diffuseColor.a ); #ifdef OPAQUE gl_FragColor.a = 1.0; #endif }`,fE=`#define PHONG varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; #include #include #include #include }`,pE=`#define PHONG uniform vec3 diffuse; uniform vec3 emissive; uniform vec3 specular; uniform float shininess; uniform float opacity; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); vec3 totalEmissiveRadiance = emissive; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; #include #include #include #include #include #include #include }`,mE=`#define STANDARD varying vec3 vViewPosition; #ifdef USE_TRANSMISSION varying vec3 vWorldPosition; #endif #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; #include #include #include #ifdef USE_TRANSMISSION vWorldPosition = worldPosition.xyz; #endif }`,gE=`#define STANDARD #ifdef PHYSICAL #define IOR #define USE_SPECULAR #endif uniform vec3 diffuse; uniform vec3 emissive; uniform float roughness; uniform float metalness; uniform float opacity; #ifdef IOR uniform float ior; #endif #ifdef USE_SPECULAR uniform float specularIntensity; uniform vec3 specularColor; #ifdef USE_SPECULAR_COLORMAP uniform sampler2D specularColorMap; #endif #ifdef USE_SPECULAR_INTENSITYMAP uniform sampler2D specularIntensityMap; #endif #endif #ifdef USE_CLEARCOAT uniform float clearcoat; uniform float clearcoatRoughness; #endif #ifdef USE_DISPERSION uniform float dispersion; #endif #ifdef USE_IRIDESCENCE uniform float iridescence; uniform float iridescenceIOR; uniform float iridescenceThicknessMinimum; uniform float iridescenceThicknessMaximum; #endif #ifdef USE_SHEEN uniform vec3 sheenColor; uniform float sheenRoughness; #ifdef USE_SHEEN_COLORMAP uniform sampler2D sheenColorMap; #endif #ifdef USE_SHEEN_ROUGHNESSMAP uniform sampler2D sheenRoughnessMap; #endif #endif #ifdef USE_ANISOTROPY uniform vec2 anisotropyVector; #ifdef USE_ANISOTROPYMAP uniform sampler2D anisotropyMap; #endif #endif varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); vec3 totalEmissiveRadiance = emissive; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; #include vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; #ifdef USE_SHEEN outgoingLight = outgoingLight + sheenSpecularDirect + sheenSpecularIndirect; #endif #ifdef USE_CLEARCOAT float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) ); vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat; #endif #include #include #include #include #include #include }`,_E=`#define TOON varying vec3 vViewPosition; #include #include #include #include #include #include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include vViewPosition = - mvPosition.xyz; #include #include #include }`,xE=`#define TOON uniform vec3 diffuse; uniform vec3 emissive; uniform float opacity; #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); vec3 totalEmissiveRadiance = emissive; #include #include #include #include #include #include #include #include #include #include #include #include #include #include vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; #include #include #include #include #include #include }`,yE=`uniform float size; uniform float scale; #include #include #include #include #include #include #ifdef USE_POINTS_UV varying vec2 vUv; uniform mat3 uvTransform; #endif void main() { #ifdef USE_POINTS_UV vUv = ( uvTransform * vec3( uv, 1 ) ).xy; #endif #include #include #include #include #include #include gl_PointSize = size; #ifdef USE_SIZEATTENUATION bool isPerspective = isPerspectiveMatrix( projectionMatrix ); if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); #endif #include #include #include #include }`,vE=`uniform vec3 diffuse; uniform float opacity; #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include vec3 outgoingLight = vec3( 0.0 ); #include #include #include #include #include outgoingLight = diffuseColor.rgb; #include #include #include #include #include }`,SE=`#include #include #include #include #include #include #include void main() { #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include }`,bE=`uniform vec3 color; uniform float opacity; #include #include #include #include #include #include #include void main() { #include gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); #include #include #include #include }`,TE=`uniform float rotation; uniform vec2 center; #include #include #include #include #include void main() { #include vec4 mvPosition = modelViewMatrix[ 3 ]; vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) ); #ifndef USE_SIZEATTENUATION bool isPerspective = isPerspectiveMatrix( projectionMatrix ); if ( isPerspective ) scale *= - mvPosition.z; #endif vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; vec2 rotatedPosition; rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; mvPosition.xy += rotatedPosition; gl_Position = projectionMatrix * mvPosition; #include #include #include }`,ME=`uniform vec3 diffuse; uniform float opacity; #include #include #include #include #include #include #include #include #include void main() { vec4 diffuseColor = vec4( diffuse, opacity ); #include vec3 outgoingLight = vec3( 0.0 ); #include #include #include #include #include outgoingLight = diffuseColor.rgb; #include #include #include #include }`,lt={alphahash_fragment:$b,alphahash_pars_fragment:Xb,alphamap_fragment:qb,alphamap_pars_fragment:jb,alphatest_fragment:Yb,alphatest_pars_fragment:Kb,aomap_fragment:Zb,aomap_pars_fragment:Qb,batching_pars_vertex:Jb,batching_vertex:eT,begin_vertex:tT,beginnormal_vertex:nT,bsdfs:iT,iridescence_fragment:sT,bumpmap_pars_fragment:rT,clipping_planes_fragment:oT,clipping_planes_pars_fragment:aT,clipping_planes_pars_vertex:lT,clipping_planes_vertex:cT,color_fragment:uT,color_pars_fragment:hT,color_pars_vertex:dT,color_vertex:fT,common:pT,cube_uv_reflection_fragment:mT,defaultnormal_vertex:gT,displacementmap_pars_vertex:_T,displacementmap_vertex:xT,emissivemap_fragment:yT,emissivemap_pars_fragment:vT,colorspace_fragment:ST,colorspace_pars_fragment:bT,envmap_fragment:TT,envmap_common_pars_fragment:MT,envmap_pars_fragment:ET,envmap_pars_vertex:AT,envmap_physical_pars_fragment:BT,envmap_vertex:RT,fog_vertex:wT,fog_pars_vertex:CT,fog_fragment:NT,fog_pars_fragment:PT,gradientmap_pars_fragment:DT,lightmap_pars_fragment:LT,lights_lambert_fragment:UT,lights_lambert_pars_fragment:FT,lights_pars_begin:IT,lights_toon_fragment:OT,lights_toon_pars_fragment:kT,lights_phong_fragment:GT,lights_phong_pars_fragment:VT,lights_physical_fragment:zT,lights_physical_pars_fragment:HT,lights_fragment_begin:WT,lights_fragment_maps:$T,lights_fragment_end:XT,lightprobes_pars_fragment:qT,logdepthbuf_fragment:jT,logdepthbuf_pars_fragment:YT,logdepthbuf_pars_vertex:KT,logdepthbuf_vertex:ZT,map_fragment:QT,map_pars_fragment:JT,map_particle_fragment:eM,map_particle_pars_fragment:tM,metalnessmap_fragment:nM,metalnessmap_pars_fragment:iM,morphinstance_vertex:sM,morphcolor_vertex:rM,morphnormal_vertex:oM,morphtarget_pars_vertex:aM,morphtarget_vertex:lM,normal_fragment_begin:cM,normal_fragment_maps:uM,normal_pars_fragment:hM,normal_pars_vertex:dM,normal_vertex:fM,normalmap_pars_fragment:pM,clearcoat_normal_fragment_begin:mM,clearcoat_normal_fragment_maps:gM,clearcoat_pars_fragment:_M,iridescence_pars_fragment:xM,opaque_fragment:yM,packing:vM,premultiplied_alpha_fragment:SM,project_vertex:bM,dithering_fragment:TM,dithering_pars_fragment:MM,roughnessmap_fragment:EM,roughnessmap_pars_fragment:AM,shadowmap_pars_fragment:RM,shadowmap_pars_vertex:wM,shadowmap_vertex:CM,shadowmask_pars_fragment:NM,skinbase_vertex:PM,skinning_pars_vertex:DM,skinning_vertex:LM,skinnormal_vertex:UM,specularmap_fragment:FM,specularmap_pars_fragment:IM,tonemapping_fragment:BM,tonemapping_pars_fragment:OM,transmission_fragment:kM,transmission_pars_fragment:GM,uv_pars_fragment:VM,uv_pars_vertex:zM,uv_vertex:HM,worldpos_vertex:WM,background_vert:$M,background_frag:XM,backgroundCube_vert:qM,backgroundCube_frag:jM,cube_vert:YM,cube_frag:KM,depth_vert:ZM,depth_frag:QM,distance_vert:JM,distance_frag:eE,equirect_vert:tE,equirect_frag:nE,linedashed_vert:iE,linedashed_frag:sE,meshbasic_vert:rE,meshbasic_frag:oE,meshlambert_vert:aE,meshlambert_frag:lE,meshmatcap_vert:cE,meshmatcap_frag:uE,meshnormal_vert:hE,meshnormal_frag:dE,meshphong_vert:fE,meshphong_frag:pE,meshphysical_vert:mE,meshphysical_frag:gE,meshtoon_vert:_E,meshtoon_frag:xE,points_vert:yE,points_frag:vE,shadow_vert:SE,shadow_frag:bE,sprite_vert:TE,sprite_frag:ME},Te={common:{diffuse:{value:new Ve(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new Ke},alphaMap:{value:null},alphaMapTransform:{value:new Ke},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new Ke}},envmap:{envMap:{value:null},envMapRotation:{value:new Ke},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new Ke}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new Ke}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new Ke},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new Ke},normalScale:{value:new de(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new Ke},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new Ke}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new Ke}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new Ke}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Ve(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null},probesSH:{value:null},probesMin:{value:new C},probesMax:{value:new C},probesResolution:{value:new C}},points:{diffuse:{value:new Ve(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new Ke},alphaTest:{value:0},uvTransform:{value:new Ke}},sprite:{diffuse:{value:new Ve(16777215)},opacity:{value:1},center:{value:new de(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new Ke},alphaMap:{value:null},alphaMapTransform:{value:new Ke},alphaTest:{value:0}}},as={basic:{uniforms:Kn([Te.common,Te.specularmap,Te.envmap,Te.aomap,Te.lightmap,Te.fog]),vertexShader:lt.meshbasic_vert,fragmentShader:lt.meshbasic_frag},lambert:{uniforms:Kn([Te.common,Te.specularmap,Te.envmap,Te.aomap,Te.lightmap,Te.emissivemap,Te.bumpmap,Te.normalmap,Te.displacementmap,Te.fog,Te.lights,{emissive:{value:new Ve(0)},envMapIntensity:{value:1}}]),vertexShader:lt.meshlambert_vert,fragmentShader:lt.meshlambert_frag},phong:{uniforms:Kn([Te.common,Te.specularmap,Te.envmap,Te.aomap,Te.lightmap,Te.emissivemap,Te.bumpmap,Te.normalmap,Te.displacementmap,Te.fog,Te.lights,{emissive:{value:new Ve(0)},specular:{value:new Ve(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:lt.meshphong_vert,fragmentShader:lt.meshphong_frag},standard:{uniforms:Kn([Te.common,Te.envmap,Te.aomap,Te.lightmap,Te.emissivemap,Te.bumpmap,Te.normalmap,Te.displacementmap,Te.roughnessmap,Te.metalnessmap,Te.fog,Te.lights,{emissive:{value:new Ve(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:lt.meshphysical_vert,fragmentShader:lt.meshphysical_frag},toon:{uniforms:Kn([Te.common,Te.aomap,Te.lightmap,Te.emissivemap,Te.bumpmap,Te.normalmap,Te.displacementmap,Te.gradientmap,Te.fog,Te.lights,{emissive:{value:new Ve(0)}}]),vertexShader:lt.meshtoon_vert,fragmentShader:lt.meshtoon_frag},matcap:{uniforms:Kn([Te.common,Te.bumpmap,Te.normalmap,Te.displacementmap,Te.fog,{matcap:{value:null}}]),vertexShader:lt.meshmatcap_vert,fragmentShader:lt.meshmatcap_frag},points:{uniforms:Kn([Te.points,Te.fog]),vertexShader:lt.points_vert,fragmentShader:lt.points_frag},dashed:{uniforms:Kn([Te.common,Te.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:lt.linedashed_vert,fragmentShader:lt.linedashed_frag},depth:{uniforms:Kn([Te.common,Te.displacementmap]),vertexShader:lt.depth_vert,fragmentShader:lt.depth_frag},normal:{uniforms:Kn([Te.common,Te.bumpmap,Te.normalmap,Te.displacementmap,{opacity:{value:1}}]),vertexShader:lt.meshnormal_vert,fragmentShader:lt.meshnormal_frag},sprite:{uniforms:Kn([Te.sprite,Te.fog]),vertexShader:lt.sprite_vert,fragmentShader:lt.sprite_frag},background:{uniforms:{uvTransform:{value:new Ke},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:lt.background_vert,fragmentShader:lt.background_frag},backgroundCube:{uniforms:{envMap:{value:null},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new Ke}},vertexShader:lt.backgroundCube_vert,fragmentShader:lt.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:lt.cube_vert,fragmentShader:lt.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:lt.equirect_vert,fragmentShader:lt.equirect_frag},distance:{uniforms:Kn([Te.common,Te.displacementmap,{referencePosition:{value:new C},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:lt.distance_vert,fragmentShader:lt.distance_frag},shadow:{uniforms:Kn([Te.lights,Te.fog,{color:{value:new Ve(0)},opacity:{value:1}}]),vertexShader:lt.shadow_vert,fragmentShader:lt.shadow_frag}};as.physical={uniforms:Kn([as.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new Ke},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new Ke},clearcoatNormalScale:{value:new de(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new Ke},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new Ke},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new Ke},sheen:{value:0},sheenColor:{value:new Ve(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new Ke},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new Ke},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new Ke},transmissionSamplerSize:{value:new de},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new Ke},attenuationDistance:{value:0},attenuationColor:{value:new Ve(0)},specularColor:{value:new Ve(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new Ke},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new Ke},anisotropyVector:{value:new de},anisotropyMap:{value:null},anisotropyMapTransform:{value:new Ke}}]),vertexShader:lt.meshphysical_vert,fragmentShader:lt.meshphysical_frag};const zc={r:0,b:0,g:0},EE=new dt,Wx=new Ke;Wx.set(-1,0,0,0,1,0,0,0,1);function AE(r,e,t,n,i,s){const o=new Ve(0);let a=i===!0?0:1,l,c,u=null,h=0,d=null;function f(x){let v=x.isScene===!0?x.background:null;if(v&&v.isTexture){const S=x.backgroundBlurriness>0;v=e.get(v,S)}return v}function p(x){let v=!1;const S=f(x);S===null?m(o,a):S&&S.isColor&&(m(S,1),v=!0);const E=r.xr.getEnvironmentBlendMode();E==="additive"?t.buffers.color.setClear(0,0,0,1,s):E==="alpha-blend"&&t.buffers.color.setClear(0,0,0,0,s),(r.autoClear||v)&&(t.buffers.depth.setTest(!0),t.buffers.depth.setMask(!0),t.buffers.color.setMask(!0),r.clear(r.autoClearColor,r.autoClearDepth,r.autoClearStencil))}function g(x,v){const S=f(v);S&&(S.isCubeTexture||S.mapping===so)?(c===void 0&&(c=new gn(new yo(1,1,1),new Ui({name:"BackgroundCubeMaterial",uniforms:Da(as.backgroundCube.uniforms),vertexShader:as.backgroundCube.vertexShader,fragmentShader:as.backgroundCube.fragmentShader,side:Pt,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute("normal"),c.geometry.deleteAttribute("uv"),c.onBeforeRender=function(E,T,A){this.matrixWorld.copyPosition(A.matrixWorld)},Object.defineProperty(c.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),n.update(c)),c.material.uniforms.envMap.value=S,c.material.uniforms.backgroundBlurriness.value=v.backgroundBlurriness,c.material.uniforms.backgroundIntensity.value=v.backgroundIntensity,c.material.uniforms.backgroundRotation.value.setFromMatrix4(EE.makeRotationFromEuler(v.backgroundRotation)).transpose(),S.isCubeTexture&&S.isRenderTargetTexture===!1&&c.material.uniforms.backgroundRotation.value.premultiply(Wx),c.material.toneMapped=Xe.getTransfer(S.colorSpace)!==Ee,(u!==S||h!==S.version||d!==r.toneMapping)&&(c.material.needsUpdate=!0,u=S,h=S.version,d=r.toneMapping),c.layers.enableAll(),x.unshift(c,c.geometry,c.material,0,0,null)):S&&S.isTexture&&(l===void 0&&(l=new gn(new uc(2,2),new Ui({name:"BackgroundMaterial",uniforms:Da(as.background.uniforms),vertexShader:as.background.vertexShader,fragmentShader:as.background.fragmentShader,side:ni,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),n.update(l)),l.material.uniforms.t2D.value=S,l.material.uniforms.backgroundIntensity.value=v.backgroundIntensity,l.material.toneMapped=Xe.getTransfer(S.colorSpace)!==Ee,S.matrixAutoUpdate===!0&&S.updateMatrix(),l.material.uniforms.uvTransform.value.copy(S.matrix),(u!==S||h!==S.version||d!==r.toneMapping)&&(l.material.needsUpdate=!0,u=S,h=S.version,d=r.toneMapping),l.layers.enableAll(),x.unshift(l,l.geometry,l.material,0,0,null))}function m(x,v){x.getRGB(zc,Dx(r)),t.buffers.color.setClear(zc.r,zc.g,zc.b,v,s)}function _(){c!==void 0&&(c.geometry.dispose(),c.material.dispose(),c=void 0),l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0)}return{getClearColor:function(){return o},setClearColor:function(x,v=1){o.set(x),a=v,m(o,a)},getClearAlpha:function(){return a},setClearAlpha:function(x){a=x,m(o,a)},render:p,addToRenderList:g,dispose:_}}function RE(r,e){const t=r.getParameter(r.MAX_VERTEX_ATTRIBS),n={},i=d(null);let s=i,o=!1;function a(N,U,G,V,L){let B=!1;const H=h(N,V,G,U);s!==H&&(s=H,c(s.object)),B=f(N,V,G,L),B&&p(N,V,G,L),L!==null&&e.update(L,r.ELEMENT_ARRAY_BUFFER),(B||o)&&(o=!1,S(N,U,G,V),L!==null&&r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,e.get(L).buffer))}function l(){return r.createVertexArray()}function c(N){return r.bindVertexArray(N)}function u(N){return r.deleteVertexArray(N)}function h(N,U,G,V){const L=V.wireframe===!0;let B=n[U.id];B===void 0&&(B={},n[U.id]=B);const H=N.isInstancedMesh===!0?N.id:0;let ie=B[H];ie===void 0&&(ie={},B[H]=ie);let ce=ie[G.id];ce===void 0&&(ce={},ie[G.id]=ce);let ve=ce[L];return ve===void 0&&(ve=d(l()),ce[L]=ve),ve}function d(N){const U=[],G=[],V=[];for(let L=0;L=0){const Ce=L[ce];let ke=B[ce];if(ke===void 0&&(ce==="instanceMatrix"&&N.instanceMatrix&&(ke=N.instanceMatrix),ce==="instanceColor"&&N.instanceColor&&(ke=N.instanceColor)),Ce===void 0||Ce.attribute!==ke||ke&&Ce.data!==ke.data)return!0;H++}return s.attributesNum!==H||s.index!==V}function p(N,U,G,V){const L={},B=U.attributes;let H=0;const ie=G.getAttributes();for(const ce in ie)if(ie[ce].location>=0){let Ce=B[ce];Ce===void 0&&(ce==="instanceMatrix"&&N.instanceMatrix&&(Ce=N.instanceMatrix),ce==="instanceColor"&&N.instanceColor&&(Ce=N.instanceColor));const ke={};ke.attribute=Ce,Ce&&Ce.data&&(ke.data=Ce.data),L[ce]=ke,H++}s.attributes=L,s.attributesNum=H,s.index=V}function g(){const N=s.newAttributes;for(let U=0,G=N.length;U=0){let ve=L[ie];if(ve===void 0&&(ie==="instanceMatrix"&&N.instanceMatrix&&(ve=N.instanceMatrix),ie==="instanceColor"&&N.instanceColor&&(ve=N.instanceColor)),ve!==void 0){const Ce=ve.normalized,ke=ve.itemSize,ut=e.get(ve);if(ut===void 0)continue;const Mt=ut.buffer,oe=ut.type,W=ut.bytesPerElement,se=oe===r.INT||oe===r.UNSIGNED_INT||ve.gpuType===Sn;if(ve.isInterleavedBufferAttribute){const le=ve.data,Ne=le.stride,Le=ve.offset;if(le.isInstancedInterleavedBuffer){for(let we=0;we0&&r.getShaderPrecisionFormat(r.FRAGMENT_SHADER,r.HIGH_FLOAT).precision>0)return"highp";A="mediump"}return A==="mediump"&&r.getShaderPrecisionFormat(r.VERTEX_SHADER,r.MEDIUM_FLOAT).precision>0&&r.getShaderPrecisionFormat(r.FRAGMENT_SHADER,r.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let c=t.precision!==void 0?t.precision:"highp";const u=l(c);u!==c&&(ee("WebGLRenderer:",c,"not supported, using",u,"instead."),c=u);const h=t.logarithmicDepthBuffer===!0,d=t.reversedDepthBuffer===!0&&e.has("EXT_clip_control");t.reversedDepthBuffer===!0&&d===!1&&ee("WebGLRenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer.");const f=r.getParameter(r.MAX_TEXTURE_IMAGE_UNITS),p=r.getParameter(r.MAX_VERTEX_TEXTURE_IMAGE_UNITS),g=r.getParameter(r.MAX_TEXTURE_SIZE),m=r.getParameter(r.MAX_CUBE_MAP_TEXTURE_SIZE),_=r.getParameter(r.MAX_VERTEX_ATTRIBS),x=r.getParameter(r.MAX_VERTEX_UNIFORM_VECTORS),v=r.getParameter(r.MAX_VARYING_VECTORS),S=r.getParameter(r.MAX_FRAGMENT_UNIFORM_VECTORS),E=r.getParameter(r.MAX_SAMPLES),T=r.getParameter(r.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:s,getMaxPrecision:l,textureFormatReadable:o,textureTypeReadable:a,precision:c,logarithmicDepthBuffer:h,reversedDepthBuffer:d,maxTextures:f,maxVertexTextures:p,maxTextureSize:g,maxCubemapSize:m,maxAttributes:_,maxVertexUniforms:x,maxVaryings:v,maxFragmentUniforms:S,maxSamples:E,samples:T}}function NE(r){const e=this;let t=null,n=0,i=!1,s=!1;const o=new os,a=new Ke,l={value:null,needsUpdate:!1};this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(h,d){const f=h.length!==0||d||n!==0||i;return i=d,n=h.length,f},this.beginShadows=function(){s=!0,u(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(h,d){t=u(h,d,0)},this.setState=function(h,d,f){const p=h.clippingPlanes,g=h.clipIntersection,m=h.clipShadows,_=r.get(h);if(!i||p===null||p.length===0||s&&!m)s?u(null):c();else{const x=s?0:n,v=x*4;let S=_.clippingState||null;l.value=S,S=u(p,d,v,f);for(let E=0;E!==v;++E)S[E]=t[E];_.clippingState=S,this.numIntersection=g?this.numPlanes:0,this.numPlanes+=x}};function c(){l.value!==t&&(l.value=t,l.needsUpdate=n>0),e.numPlanes=n,e.numIntersection=0}function u(h,d,f,p){const g=h!==null?h.length:0;let m=null;if(g!==0){if(m=l.value,p!==!0||m===null){const _=f+g*4,x=d.matrixWorldInverse;a.getNormalMatrix(x),(m===null||m.length<_)&&(m=new Float32Array(_));for(let v=0,S=f;v!==g;++v,S+=4)o.copy(h[v]).applyMatrix4(x,a),o.normal.toArray(m,S),m[S+3]=o.constant}l.value=m,l.needsUpdate=!0}return e.numPlanes=g,e.numIntersection=0,m}}const pr=4,Hm=[.125,.215,.35,.446,.526,.582],qr=20,PE=256,nl=new Va,Wm=new Ve;let jh=null,Yh=0,Kh=0,Zh=!1;const DE=new C;let $m=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,i=100,s={}){const{size:o=256,position:a=DE}=s;jh=this._renderer.getRenderTarget(),Yh=this._renderer.getActiveCubeFace(),Kh=this._renderer.getActiveMipmapLevel(),Zh=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(o);const l=this._allocateTargets();return l.depthBuffer=!0,this._sceneToCubeUV(e,n,i,l,a),t>0&&this._blur(l,0,0,t),this._applyPMREM(l),this._cleanup(l),l}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=jm(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=qm(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._backgroundBox!==null&&(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(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e2?E:0,E,E),h.setRenderTarget(i),_&&h.render(g,l),h.render(e,l)}h.toneMapping=f,h.autoClear=d,e.background=x}_textureToCubeUV(e,t){const n=this._renderer,i=e.mapping===Xi||e.mapping===_s;i?(this._cubemapMaterial===null&&(this._cubemapMaterial=jm()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=qm());const s=i?this._cubemapMaterial:this._equirectMaterial,o=this._lodMeshes[0];o.material=s;const a=s.uniforms;a.envMap.value=e;const l=this._cubeSize;ko(t,0,0,3*l,2*l),n.setRenderTarget(t),n.render(o,nl)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;const i=this._lodMeshes.length;for(let s=1;sp-pr?n-p+pr:0),_=4*(this._cubeSize-g);l.envMap.value=e.texture,l.roughness.value=f,l.mipInt.value=p-t,ko(s,m,_,3*g,2*g),i.setRenderTarget(s),i.render(a,nl),l.envMap.value=s.texture,l.roughness.value=0,l.mipInt.value=p-n,ko(e,m,_,3*g,2*g),i.setRenderTarget(e),i.render(a,nl)}_blur(e,t,n,i,s){const o=this._pingPongRenderTarget;this._halfBlur(e,o,t,n,i,"latitudinal",s),this._halfBlur(o,e,n,n,i,"longitudinal",s)}_halfBlur(e,t,n,i,s,o,a){const l=this._renderer,c=this._blurMaterial;o!=="latitudinal"&&o!=="longitudinal"&&ne("blur direction must be either latitudinal or longitudinal!");const u=3,h=this._lodMeshes[i];h.material=c;const d=c.uniforms,f=this._sizeLods[n]-1,p=isFinite(s)?Math.PI/(2*f):2*Math.PI/(2*qr-1),g=s/p,m=isFinite(s)?1+Math.floor(u*g):qr;m>qr&&ee(`sigmaRadians, ${s}, is too large and will clip, as it requested ${m} samples when the maximum is set to ${qr}`);const _=[];let x=0;for(let A=0;Av-pr?i-v+pr:0),T=4*(this._cubeSize-S);ko(t,E,T,3*S,2*S),l.setRenderTarget(t),l.render(h,nl)}};function LE(r){const e=[],t=[],n=[];let i=r;const s=r-pr+1+Hm.length;for(let o=0;or-pr?l=Hm[o-r+pr-1]:o===0&&(l=0),t.push(l);const c=1/(a-2),u=-c,h=1+c,d=[u,u,h,u,h,h,u,u,h,h,u,h],f=6,p=6,g=3,m=2,_=1,x=new Float32Array(g*p*f),v=new Float32Array(m*p*f),S=new Float32Array(_*p*f);for(let T=0;T2?0:-1,R=[A,y,0,A+2/3,y,0,A+2/3,y+1,0,A,y,0,A+2/3,y+1,0,A,y+1,0];x.set(R,g*p*T),v.set(d,m*p*T);const P=[T,T,T,T,T,T];S.set(P,_*p*T)}const E=new Pn;E.setAttribute("position",new In(x,g)),E.setAttribute("uv",new In(v,m)),E.setAttribute("faceIndex",new In(S,_)),n.push(new gn(E,null)),i>pr&&i--}return{lodMeshes:n,sizeLods:e,sigmas:t}}function Xm(r,e,t){const n=new $i(r,e,t);return n.texture.mapping=so,n.texture.name="PMREM.cubeUv",n.scissorTest=!0,n}function ko(r,e,t,n,i){r.viewport.set(e,t,n,i),r.scissor.set(e,t,n,i)}function UE(r,e,t){return new Ui({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:PE,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${r}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:eh(),fragmentShader:` precision highp float; precision highp int; varying vec3 vOutputDirection; uniform sampler2D envMap; uniform float roughness; uniform float mipInt; #define ENVMAP_TYPE_CUBE_UV #include #define PI 3.14159265359 // Van der Corput radical inverse float radicalInverse_VdC(uint bits) { bits = (bits << 16u) | (bits >> 16u); bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); return float(bits) * 2.3283064365386963e-10; // / 0x100000000 } // Hammersley sequence vec2 hammersley(uint i, uint N) { return vec2(float(i) / float(N), radicalInverse_VdC(i)); } // GGX VNDF importance sampling (Eric Heitz 2018) // "Sampling the GGX Distribution of Visible Normals" // https://jcgt.org/published/0007/04/01/ vec3 importanceSampleGGX_VNDF(vec2 Xi, vec3 V, float roughness) { float alpha = roughness * roughness; // Section 4.1: Orthonormal basis vec3 T1 = vec3(1.0, 0.0, 0.0); vec3 T2 = cross(V, T1); // Section 4.2: Parameterization of projected area float r = sqrt(Xi.x); float phi = 2.0 * PI * Xi.y; float t1 = r * cos(phi); float t2 = r * sin(phi); float s = 0.5 * (1.0 + V.z); t2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2; // Section 4.3: Reprojection onto hemisphere vec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * V; // Section 3.4: Transform back to ellipsoid configuration return normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z))); } void main() { vec3 N = normalize(vOutputDirection); vec3 V = N; // Assume view direction equals normal for pre-filtering vec3 prefilteredColor = vec3(0.0); float totalWeight = 0.0; // For very low roughness, just sample the environment directly if (roughness < 0.001) { gl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0); return; } // Tangent space basis for VNDF sampling vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); vec3 tangent = normalize(cross(up, N)); vec3 bitangent = cross(N, tangent); for(uint i = 0u; i < uint(GGX_SAMPLES); i++) { vec2 Xi = hammersley(i, uint(GGX_SAMPLES)); // For PMREM, V = N, so in tangent space V is always (0, 0, 1) vec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness); // Transform H back to world space vec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z); vec3 L = normalize(2.0 * dot(V, H) * H - V); float NdotL = max(dot(N, L), 0.0); if(NdotL > 0.0) { // Sample environment at fixed mip level // VNDF importance sampling handles the distribution filtering vec3 sampleColor = bilinearCubeUV(envMap, L, mipInt); // Weight by NdotL for the split-sum approximation // VNDF PDF naturally accounts for the visible microfacet distribution prefilteredColor += sampleColor * NdotL; totalWeight += NdotL; } } if (totalWeight > 0.0) { prefilteredColor = prefilteredColor / totalWeight; } gl_FragColor = vec4(prefilteredColor, 1.0); } `,blending:Cn,depthTest:!1,depthWrite:!1})}function FE(r,e,t){const n=new Float32Array(qr),i=new C(0,1,0);return new Ui({name:"SphericalGaussianBlur",defines:{n:qr,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${r}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:n},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:i}},vertexShader:eh(),fragmentShader:` precision mediump float; precision mediump int; varying vec3 vOutputDirection; uniform sampler2D envMap; uniform int samples; uniform float weights[ n ]; uniform bool latitudinal; uniform float dTheta; uniform float mipInt; uniform vec3 poleAxis; #define ENVMAP_TYPE_CUBE_UV #include vec3 getSample( float theta, vec3 axis ) { float cosTheta = cos( theta ); // Rodrigues' axis-angle rotation vec3 sampleDirection = vOutputDirection * cosTheta + cross( axis, vOutputDirection ) * sin( theta ) + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); return bilinearCubeUV( envMap, sampleDirection, mipInt ); } void main() { vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); if ( all( equal( axis, vec3( 0.0 ) ) ) ) { axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); } axis = normalize( axis ); gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); for ( int i = 1; i < n; i++ ) { if ( i >= samples ) { break; } float theta = dTheta * float( i ); gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); } } `,blending:Cn,depthTest:!1,depthWrite:!1})}function qm(){return new Ui({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:eh(),fragmentShader:` precision mediump float; precision mediump int; varying vec3 vOutputDirection; uniform sampler2D envMap; #include void main() { vec3 outputDirection = normalize( vOutputDirection ); vec2 uv = equirectUv( outputDirection ); gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); } `,blending:Cn,depthTest:!1,depthWrite:!1})}function jm(){return new Ui({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:eh(),fragmentShader:` precision mediump float; precision mediump int; uniform float flipEnvMap; varying vec3 vOutputDirection; uniform samplerCube envMap; void main() { gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); } `,blending:Cn,depthTest:!1,depthWrite:!1})}function eh(){return` precision mediump float; precision mediump int; attribute float faceIndex; varying vec3 vOutputDirection; // RH coordinate system; PMREM face-indexing convention vec3 getDirection( vec2 uv, float face ) { uv = 2.0 * uv - 1.0; vec3 direction = vec3( uv, 1.0 ); if ( face == 0.0 ) { direction = direction.zyx; // ( 1, v, u ) pos x } else if ( face == 1.0 ) { direction = direction.xzy; direction.xz *= -1.0; // ( -u, 1, -v ) pos y } else if ( face == 2.0 ) { direction.x *= -1.0; // ( -u, v, 1 ) pos z } else if ( face == 3.0 ) { direction = direction.zyx; direction.xz *= -1.0; // ( -1, v, -u ) neg x } else if ( face == 4.0 ) { direction = direction.xzy; direction.xy *= -1.0; // ( -u, -1, v ) neg y } else if ( face == 5.0 ) { direction.z *= -1.0; // ( u, v, -1 ) neg z } return direction; } void main() { vOutputDirection = getDirection( uv, faceIndex ); gl_Position = vec4( position, 1.0 ); } `}class $x extends $i{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const n={width:e,height:e,depth:1},i=[n,n,n,n,n,n];this.texture=new Ga(i),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const n={uniforms:{tEquirect:{value:null}},vertexShader:` varying vec3 vWorldDirection; vec3 transformDirection( in vec3 dir, in mat4 matrix ) { return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); } void main() { vWorldDirection = transformDirection( position, modelMatrix ); #include #include } `,fragmentShader:` uniform sampler2D tEquirect; varying vec3 vWorldDirection; #include void main() { vec3 direction = normalize( vWorldDirection ); vec2 sampleUV = equirectUv( direction ); gl_FragColor = texture2D( tEquirect, sampleUV ); } `},i=new yo(5,5,5),s=new Ui({name:"CubemapFromEquirect",uniforms:Da(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:Pt,blending:Cn});s.uniforms.tEquirect.value=t;const o=new gn(i,s),a=t.minFilter;return t.minFilter===li&&(t.minFilter=Ut),new kx(1,10,this).update(e,o),t.minFilter=a,o.geometry.dispose(),o.material.dispose(),this}clear(e,t=!0,n=!0,i=!0){const s=e.getRenderTarget();for(let o=0;o<6;o++)e.setRenderTarget(this,o),e.clear(t,n,i);e.setRenderTarget(s)}}function IE(r){let e=new WeakMap,t=new WeakMap,n=null;function i(d,f=!1){return d==null?null:f?o(d):s(d)}function s(d){if(d&&d.isTexture){const f=d.mapping;if(f===Ko||f===Zo)if(e.has(d)){const p=e.get(d).texture;return a(p,d.mapping)}else{const p=d.image;if(p&&p.height>0){const g=new $x(p.height);return g.fromEquirectangularTexture(r,d),e.set(d,g),d.addEventListener("dispose",c),a(g.texture,d.mapping)}else return null}}return d}function o(d){if(d&&d.isTexture){const f=d.mapping,p=f===Ko||f===Zo,g=f===Xi||f===_s;if(p||g){let m=t.get(d);const _=m!==void 0?m.texture.pmremVersion:0;if(d.isRenderTargetTexture&&d.pmremVersion!==_)return n===null&&(n=new $m(r)),m=p?n.fromEquirectangular(d,m):n.fromCubemap(d,m),m.texture.pmremVersion=d.pmremVersion,t.set(d,m),m.texture;if(m!==void 0)return m.texture;{const x=d.image;return p&&x&&x.height>0||g&&x&&l(x)?(n===null&&(n=new $m(r)),m=p?n.fromEquirectangular(d):n.fromCubemap(d),m.texture.pmremVersion=d.pmremVersion,t.set(d,m),d.addEventListener("dispose",u),m.texture):null}}}return d}function a(d,f){return f===Ko?d.mapping=Xi:f===Zo&&(d.mapping=_s),d}function l(d){let f=0;const p=6;for(let g=0;g=65535?lp:ap)(d,1);m.version=g;const _=s.get(h);_&&e.remove(_),s.set(h,m)}function u(h){const d=s.get(h);if(d){const f=h.index;f!==null&&d.versione.maxTextureSize&&(E=Math.ceil(S/e.maxTextureSize),S=e.maxTextureSize);const T=new Float32Array(S*E*4*h),A=new sp(T,S,E,h);A.type=Zt,A.needsUpdate=!0;const y=v*4;for(let P=0;P #include void main() { gl_FragColor = texture2D( tDiffuse, vUv ); #ifdef LINEAR_TONE_MAPPING gl_FragColor.rgb = LinearToneMapping( gl_FragColor.rgb ); #elif defined( REINHARD_TONE_MAPPING ) gl_FragColor.rgb = ReinhardToneMapping( gl_FragColor.rgb ); #elif defined( CINEON_TONE_MAPPING ) gl_FragColor.rgb = CineonToneMapping( gl_FragColor.rgb ); #elif defined( ACES_FILMIC_TONE_MAPPING ) gl_FragColor.rgb = ACESFilmicToneMapping( gl_FragColor.rgb ); #elif defined( AGX_TONE_MAPPING ) gl_FragColor.rgb = AgXToneMapping( gl_FragColor.rgb ); #elif defined( NEUTRAL_TONE_MAPPING ) gl_FragColor.rgb = NeutralToneMapping( gl_FragColor.rgb ); #elif defined( CUSTOM_TONE_MAPPING ) gl_FragColor.rgb = CustomToneMapping( gl_FragColor.rgb ); #endif #ifdef SRGB_TRANSFER gl_FragColor = sRGBTransferOETF( gl_FragColor ); #endif }`,depthTest:!1,depthWrite:!1}),c=new gn(a,l),u=new Va(-1,1,1,-1,0,1);let h=null,d=null,f=!1,p,g=null,m=[],_=!1;this.setSize=function(x,v){s.setSize(x,v),o.setSize(x,v);for(let S=0;S0&&m[0].isRenderPass===!0;const v=s.width,S=s.height;for(let E=0;E0)return r;const i=e*t;let s=Ym[i];if(s===void 0&&(s=new Float32Array(i),Ym[i]=s),e!==0){n.toArray(s,0);for(let o=1,a=0;o!==e;++o)a+=t,r[o].toArray(s,a)}return s}function Tn(r,e){if(r.length!==e.length)return!1;for(let t=0,n=r.length;t0&&(this.seq=i.concat(s))}setValue(e,t,n,i){const s=this.map[t];s!==void 0&&s.setValue(e,n,i)}setOptional(e,t,n){const i=t[n];i!==void 0&&this.setValue(e,n,i)}static upload(e,t,n,i){for(let s=0,o=t.length;s!==o;++s){const a=t[s],l=n[a.id];l.needsUpdate!==!1&&a.setValue(e,l.value,i)}}static seqWithValue(e,t){const n=[];for(let i=0,s=e.length;i!==s;++i){const o=e[i];o.id in t&&n.push(o)}return n}}function tg(r,e,t){const n=r.createShader(e);return r.shaderSource(n,t),r.compileShader(n),n}const FA=37297;let IA=0;function BA(r,e){const t=r.split(` `),n=[],i=Math.max(e-6,0),s=Math.min(e+6,t.length);for(let o=i;o":" "} ${a}: ${t[o]}`)}return n.join(` `)}const ng=new Ke;function OA(r){Xe._getMatrix(ng,Xe.workingColorSpace,r);const e=`mat3( ${ng.elements.map(t=>t.toFixed(4))} )`;switch(Xe.getTransfer(r)){case Na:return[e,"LinearTransferOETF"];case Ee:return[e,"sRGBTransferOETF"];default:return ee("WebGLProgram: Unsupported color space: ",r),[e,"LinearTransferOETF"]}}function ig(r,e,t){const n=r.getShaderParameter(e,r.COMPILE_STATUS),s=(r.getShaderInfoLog(e)||"").trim();if(n&&s==="")return"";const o=/ERROR: 0:(\d+)/.exec(s);if(o){const a=parseInt(o[1]);return t.toUpperCase()+` `+s+` `+BA(r.getShaderSource(e),a)}else return s}function kA(r,e){const t=OA(e);return[`vec4 ${r}( vec4 value ) {`,` return ${t[1]}( vec4( value.rgb * ${t[0]}, value.a ) );`,"}"].join(` `)}const GA={[Hf]:"Linear",[Wf]:"Reinhard",[$f]:"Cineon",[Xf]:"ACESFilmic",[qf]:"AgX",[jf]:"Neutral",[_x]:"Custom"};function VA(r,e){const t=GA[e];return t===void 0?(ee("WebGLProgram: Unsupported toneMapping:",e),"vec3 "+r+"( vec3 color ) { return LinearToneMapping( color ); }"):"vec3 "+r+"( vec3 color ) { return "+t+"ToneMapping( color ); }"}const Hc=new C;function zA(){Xe.getLuminanceCoefficients(Hc);const r=Hc.x.toFixed(4),e=Hc.y.toFixed(4),t=Hc.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${r}, ${e}, ${t} );`," return dot( weights, rgb );","}"].join(` `)}function HA(r){return[r.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",r.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(_l).join(` `)}function WA(r){const e=[];for(const t in r){const n=r[t];n!==!1&&e.push("#define "+t+" "+n)}return e.join(` `)}function $A(r,e){const t={},n=r.getProgramParameter(e,r.ACTIVE_ATTRIBUTES);for(let i=0;i/gm;function of(r){return r.replace(XA,jA)}const qA=new Map;function jA(r,e){let t=lt[e];if(t===void 0){const n=qA.get(e);if(n!==void 0)t=lt[n],ee('WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,n);else throw new Error("Can not resolve #include <"+e+">")}return of(t)}const YA=/#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 og(r){return r.replace(YA,KA)}function KA(r,e,t,n){let i="";for(let s=parseInt(e);s0&&(m+=` `),_=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,p].filter(_l).join(` `),_.length>0&&(_+=` `)):(m=[ag(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,p,t.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",t.batching?"#define USE_BATCHING":"",t.batchingColor?"#define USE_BATCHING_COLOR":"",t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.instancingMorph?"#define USE_INSTANCING_MORPH":"",t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+u:"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.displacementMap?"#define USE_DISPLACEMENTMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.mapUv?"#define MAP_UV "+t.mapUv:"",t.alphaMapUv?"#define ALPHAMAP_UV "+t.alphaMapUv:"",t.lightMapUv?"#define LIGHTMAP_UV "+t.lightMapUv:"",t.aoMapUv?"#define AOMAP_UV "+t.aoMapUv:"",t.emissiveMapUv?"#define EMISSIVEMAP_UV "+t.emissiveMapUv:"",t.bumpMapUv?"#define BUMPMAP_UV "+t.bumpMapUv:"",t.normalMapUv?"#define NORMALMAP_UV "+t.normalMapUv:"",t.displacementMapUv?"#define DISPLACEMENTMAP_UV "+t.displacementMapUv:"",t.metalnessMapUv?"#define METALNESSMAP_UV "+t.metalnessMapUv:"",t.roughnessMapUv?"#define ROUGHNESSMAP_UV "+t.roughnessMapUv:"",t.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+t.anisotropyMapUv:"",t.clearcoatMapUv?"#define CLEARCOATMAP_UV "+t.clearcoatMapUv:"",t.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+t.clearcoatNormalMapUv:"",t.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+t.clearcoatRoughnessMapUv:"",t.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+t.iridescenceMapUv:"",t.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+t.iridescenceThicknessMapUv:"",t.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+t.sheenColorMapUv:"",t.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+t.sheenRoughnessMapUv:"",t.specularMapUv?"#define SPECULARMAP_UV "+t.specularMapUv:"",t.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+t.specularColorMapUv:"",t.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+t.specularIntensityMapUv:"",t.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+t.transmissionMapUv:"",t.thicknessMapUv?"#define THICKNESSMAP_UV "+t.thicknessMapUv:"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexNormals?"#define HAS_NORMAL":"",t.vertexColors?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.flatShading?"#define FLAT_SHADED":"",t.skinning?"#define USE_SKINNING":"",t.morphTargets?"#define USE_MORPHTARGETS":"",t.morphNormals&&t.flatShading===!1?"#define USE_MORPHNORMALS":"",t.morphColors?"#define USE_MORPHCOLORS":"",t.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+t.morphTextureStride:"",t.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+t.morphTargetsCount:"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.sizeAttenuation?"#define USE_SIZEATTENUATION":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.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"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH"," uniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1"," attribute vec2 uv1;","#endif","#ifdef USE_UV2"," attribute vec2 uv2;","#endif","#ifdef USE_UV3"," attribute vec2 uv3;","#endif","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",` `].filter(_l).join(` `),_=[ag(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,p,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+c:"",t.envMap?"#define "+u:"",t.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":"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.packedNormalMap?"#define USE_PACKED_NORMALMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoat?"#define USE_CLEARCOAT":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.dispersion?"#define USE_DISPERSION":"",t.iridescence?"#define USE_IRIDESCENCE":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaTest?"#define USE_ALPHATEST":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.sheen?"#define USE_SHEEN":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors||t.instancingColor?"#define USE_COLOR":"",t.vertexAlphas||t.batchingColor?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.gradientMap?"#define USE_GRADIENTMAP":"",t.flatShading?"#define FLAT_SHADED":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+l:"",t.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.numLightProbeGrids>0?"#define USE_LIGHT_PROBES_GRID":"",t.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",t.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",t.toneMapping!==Un?"#define TONE_MAPPING":"",t.toneMapping!==Un?lt.tonemapping_pars_fragment:"",t.toneMapping!==Un?VA("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",lt.colorspace_pars_fragment,kA("linearToOutputTexel",t.outputColorSpace),zA(),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",` `].filter(_l).join(` `)),o=of(o),o=sg(o,t),o=rg(o,t),a=of(a),a=sg(a,t),a=rg(a,t),o=og(o),a=og(a),t.isRawShaderMaterial!==!0&&(x=`#version 300 es `,m=[f,"#define attribute in","#define varying out","#define texture2D texture"].join(` `)+` `+m,_=["#define varying in",t.glslVersion===dm?"":"layout(location = 0) out highp vec4 pc_fragColor;",t.glslVersion===dm?"":"#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(` `)+` `+_);const v=x+m+o,S=x+_+a,E=tg(i,i.VERTEX_SHADER,v),T=tg(i,i.FRAGMENT_SHADER,S);i.attachShader(g,E),i.attachShader(g,T),t.index0AttributeName!==void 0?i.bindAttribLocation(g,0,t.index0AttributeName):t.morphTargets===!0&&i.bindAttribLocation(g,0,"position"),i.linkProgram(g);function A(N){if(r.debug.checkShaderErrors){const U=i.getProgramInfoLog(g)||"",G=i.getShaderInfoLog(E)||"",V=i.getShaderInfoLog(T)||"",L=U.trim(),B=G.trim(),H=V.trim();let ie=!0,ce=!0;if(i.getProgramParameter(g,i.LINK_STATUS)===!1)if(ie=!1,typeof r.debug.onShaderError=="function")r.debug.onShaderError(i,g,E,T);else{const ve=ig(i,E,"vertex"),Ce=ig(i,T,"fragment");ne("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(g,i.VALIDATE_STATUS)+` Material Name: `+N.name+` Material Type: `+N.type+` Program Info Log: `+L+` `+ve+` `+Ce)}else L!==""?ee("WebGLProgram: Program Info Log:",L):(B===""||H==="")&&(ce=!1);ce&&(N.diagnostics={runnable:ie,programLog:L,vertexShader:{log:B,prefix:m},fragmentShader:{log:H,prefix:_}})}i.deleteShader(E),i.deleteShader(T),y=new bu(i,g),R=$A(i,g)}let y;this.getUniforms=function(){return y===void 0&&A(this),y};let R;this.getAttributes=function(){return R===void 0&&A(this),R};let P=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return P===!1&&(P=i.getProgramParameter(g,FA)),P},this.destroy=function(){n.releaseStatesOfProgram(this),i.deleteProgram(g),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=IA++,this.cacheKey=e,this.usedTimes=1,this.program=g,this.vertexShader=E,this.fragmentShader=T,this}let aR=0;class lR{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,n=e.fragmentShader,i=this._getShaderStage(t),s=this._getShaderStage(n),o=this._getShaderCacheForMaterial(e);return o.has(i)===!1&&(o.add(i),i.usedTimes++),o.has(s)===!1&&(o.add(s),s.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const n of t)n.usedTimes--,n.usedTimes===0&&this.shaderCache.delete(n.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let n=t.get(e);return n===void 0&&(n=new Set,t.set(e,n)),n}_getShaderStage(e){const t=this.shaderCache;let n=t.get(e);return n===void 0&&(n=new cR(e),t.set(e,n)),n}}class cR{constructor(e){this.id=aR++,this.code=e,this.usedTimes=0}}function uR(r){return r===Fn||r===Rr||r===wr}function hR(r,e,t,n,i,s){const o=new rp,a=new lR,l=new Set,c=[],u=new Map,h=n.logarithmicDepthBuffer;let d=n.precision;const f={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distance",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function p(y){return l.add(y),y===0?"uv":`uv${y}`}function g(y,R,P,N,U,G){const V=N.fog,L=U.geometry,B=y.isMeshStandardMaterial||y.isMeshLambertMaterial||y.isMeshPhongMaterial?N.environment:null,H=y.isMeshStandardMaterial||y.isMeshLambertMaterial&&!y.envMap||y.isMeshPhongMaterial&&!y.envMap,ie=e.get(y.envMap||B,H),ce=ie&&ie.mapping===so?ie.image.height:null,ve=f[y.type];y.precision!==null&&(d=n.getMaxPrecision(y.precision),d!==y.precision&&ee("WebGLProgram.getParameters:",y.precision,"not supported, using",d,"instead."));const Ce=L.morphAttributes.position||L.morphAttributes.normal||L.morphAttributes.color,ke=Ce!==void 0?Ce.length:0;let ut=0;L.morphAttributes.position!==void 0&&(ut=1),L.morphAttributes.normal!==void 0&&(ut=2),L.morphAttributes.color!==void 0&&(ut=3);let Mt,oe,W,se;if(ve){const it=as[ve];Mt=it.vertexShader,oe=it.fragmentShader}else Mt=y.vertexShader,oe=y.fragmentShader,a.update(y),W=a.getVertexShaderID(y),se=a.getFragmentShaderID(y);const le=r.getRenderTarget(),Ne=r.state.buffers.depth.getReversed(),Le=U.isInstancedMesh===!0,we=U.isBatchedMesh===!0,xt=!!y.map,Qe=!!y.matcap,ft=!!ie,Et=!!y.aoMap,Je=!!y.lightMap,It=!!y.bumpMap,Dt=!!y.normalMap,di=!!y.displacementMap,O=!!y.emissiveMap,yn=!!y.metalnessMap,mt=!!y.roughnessMap,Xt=y.anisotropy>0,be=y.clearcoat>0,rn=y.dispersion>0,w=y.iridescence>0,b=y.sheen>0,z=y.transmission>0,re=Xt&&!!y.anisotropyMap,he=be&&!!y.clearcoatMap,fe=be&&!!y.clearcoatNormalMap,ye=be&&!!y.clearcoatRoughnessMap,J=w&&!!y.iridescenceMap,ae=w&&!!y.iridescenceThicknessMap,Re=b&&!!y.sheenColorMap,Ue=b&&!!y.sheenRoughnessMap,_e=!!y.specularMap,pe=!!y.specularColorMap,et=!!y.specularIntensityMap,at=z&&!!y.transmissionMap,St=z&&!!y.thicknessMap,F=!!y.gradientMap,me=!!y.alphaMap,te=y.alphaTest>0,Pe=!!y.alphaHash,xe=!!y.extensions;let ue=Un;y.toneMapped&&(le===null||le.isXRRenderTarget===!0)&&(ue=r.toneMapping);const ze={shaderID:ve,shaderType:y.type,shaderName:y.name,vertexShader:Mt,fragmentShader:oe,defines:y.defines,customVertexShaderID:W,customFragmentShaderID:se,isRawShaderMaterial:y.isRawShaderMaterial===!0,glslVersion:y.glslVersion,precision:d,batching:we,batchingColor:we&&U._colorsTexture!==null,instancing:Le,instancingColor:Le&&U.instanceColor!==null,instancingMorph:Le&&U.morphTexture!==null,outputColorSpace:le===null?r.outputColorSpace:le.isXRRenderTarget===!0?le.texture.colorSpace:Xe.workingColorSpace,alphaToCoverage:!!y.alphaToCoverage,map:xt,matcap:Qe,envMap:ft,envMapMode:ft&&ie.mapping,envMapCubeUVHeight:ce,aoMap:Et,lightMap:Je,bumpMap:It,normalMap:Dt,displacementMap:di,emissiveMap:O,normalMapObjectSpace:Dt&&y.normalMapType===yx,normalMapTangentSpace:Dt&&y.normalMapType===Wi,packedNormalMap:Dt&&y.normalMapType===Wi&&uR(y.normalMap.format),metalnessMap:yn,roughnessMap:mt,anisotropy:Xt,anisotropyMap:re,clearcoat:be,clearcoatMap:he,clearcoatNormalMap:fe,clearcoatRoughnessMap:ye,dispersion:rn,iridescence:w,iridescenceMap:J,iridescenceThicknessMap:ae,sheen:b,sheenColorMap:Re,sheenRoughnessMap:Ue,specularMap:_e,specularColorMap:pe,specularIntensityMap:et,transmission:z,transmissionMap:at,thicknessMap:St,gradientMap:F,opaque:y.transparent===!1&&y.blending===Jn&&y.alphaToCoverage===!1,alphaMap:me,alphaTest:te,alphaHash:Pe,combine:y.combine,mapUv:xt&&p(y.map.channel),aoMapUv:Et&&p(y.aoMap.channel),lightMapUv:Je&&p(y.lightMap.channel),bumpMapUv:It&&p(y.bumpMap.channel),normalMapUv:Dt&&p(y.normalMap.channel),displacementMapUv:di&&p(y.displacementMap.channel),emissiveMapUv:O&&p(y.emissiveMap.channel),metalnessMapUv:yn&&p(y.metalnessMap.channel),roughnessMapUv:mt&&p(y.roughnessMap.channel),anisotropyMapUv:re&&p(y.anisotropyMap.channel),clearcoatMapUv:he&&p(y.clearcoatMap.channel),clearcoatNormalMapUv:fe&&p(y.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:ye&&p(y.clearcoatRoughnessMap.channel),iridescenceMapUv:J&&p(y.iridescenceMap.channel),iridescenceThicknessMapUv:ae&&p(y.iridescenceThicknessMap.channel),sheenColorMapUv:Re&&p(y.sheenColorMap.channel),sheenRoughnessMapUv:Ue&&p(y.sheenRoughnessMap.channel),specularMapUv:_e&&p(y.specularMap.channel),specularColorMapUv:pe&&p(y.specularColorMap.channel),specularIntensityMapUv:et&&p(y.specularIntensityMap.channel),transmissionMapUv:at&&p(y.transmissionMap.channel),thicknessMapUv:St&&p(y.thicknessMap.channel),alphaMapUv:me&&p(y.alphaMap.channel),vertexTangents:!!L.attributes.tangent&&(Dt||Xt),vertexNormals:!!L.attributes.normal,vertexColors:y.vertexColors,vertexAlphas:y.vertexColors===!0&&!!L.attributes.color&&L.attributes.color.itemSize===4,pointsUvs:U.isPoints===!0&&!!L.attributes.uv&&(xt||me),fog:!!V,useFog:y.fog===!0,fogExp2:!!V&&V.isFogExp2,flatShading:y.wireframe===!1&&(y.flatShading===!0||L.attributes.normal===void 0&&Dt===!1&&(y.isMeshLambertMaterial||y.isMeshPhongMaterial||y.isMeshStandardMaterial||y.isMeshPhysicalMaterial)),sizeAttenuation:y.sizeAttenuation===!0,logarithmicDepthBuffer:h,reversedDepthBuffer:Ne,skinning:U.isSkinnedMesh===!0,morphTargets:L.morphAttributes.position!==void 0,morphNormals:L.morphAttributes.normal!==void 0,morphColors:L.morphAttributes.color!==void 0,morphTargetsCount:ke,morphTextureStride:ut,numDirLights:R.directional.length,numPointLights:R.point.length,numSpotLights:R.spot.length,numSpotLightMaps:R.spotLightMap.length,numRectAreaLights:R.rectArea.length,numHemiLights:R.hemi.length,numDirLightShadows:R.directionalShadowMap.length,numPointLightShadows:R.pointShadowMap.length,numSpotLightShadows:R.spotShadowMap.length,numSpotLightShadowsWithMaps:R.numSpotLightShadowsWithMaps,numLightProbes:R.numLightProbes,numLightProbeGrids:G.length,numClippingPlanes:s.numPlanes,numClipIntersection:s.numIntersection,dithering:y.dithering,shadowMapEnabled:r.shadowMap.enabled&&P.length>0,shadowMapType:r.shadowMap.type,toneMapping:ue,decodeVideoTexture:xt&&y.map.isVideoTexture===!0&&Xe.getTransfer(y.map.colorSpace)===Ee,decodeVideoTextureEmissive:O&&y.emissiveMap.isVideoTexture===!0&&Xe.getTransfer(y.emissiveMap.colorSpace)===Ee,premultipliedAlpha:y.premultipliedAlpha,doubleSided:y.side===wn,flipSided:y.side===Pt,useDepthPacking:y.depthPacking>=0,depthPacking:y.depthPacking||0,index0AttributeName:y.index0AttributeName,extensionClipCullDistance:xe&&y.extensions.clipCullDistance===!0&&t.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(xe&&y.extensions.multiDraw===!0||we)&&t.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:t.has("KHR_parallel_shader_compile"),customProgramCacheKey:y.customProgramCacheKey()};return ze.vertexUv1s=l.has(1),ze.vertexUv2s=l.has(2),ze.vertexUv3s=l.has(3),l.clear(),ze}function m(y){const R=[];if(y.shaderID?R.push(y.shaderID):(R.push(y.customVertexShaderID),R.push(y.customFragmentShaderID)),y.defines!==void 0)for(const P in y.defines)R.push(P),R.push(y.defines[P]);return y.isRawShaderMaterial===!1&&(_(R,y),x(R,y),R.push(r.outputColorSpace)),R.push(y.customProgramCacheKey),R.join()}function _(y,R){y.push(R.precision),y.push(R.outputColorSpace),y.push(R.envMapMode),y.push(R.envMapCubeUVHeight),y.push(R.mapUv),y.push(R.alphaMapUv),y.push(R.lightMapUv),y.push(R.aoMapUv),y.push(R.bumpMapUv),y.push(R.normalMapUv),y.push(R.displacementMapUv),y.push(R.emissiveMapUv),y.push(R.metalnessMapUv),y.push(R.roughnessMapUv),y.push(R.anisotropyMapUv),y.push(R.clearcoatMapUv),y.push(R.clearcoatNormalMapUv),y.push(R.clearcoatRoughnessMapUv),y.push(R.iridescenceMapUv),y.push(R.iridescenceThicknessMapUv),y.push(R.sheenColorMapUv),y.push(R.sheenRoughnessMapUv),y.push(R.specularMapUv),y.push(R.specularColorMapUv),y.push(R.specularIntensityMapUv),y.push(R.transmissionMapUv),y.push(R.thicknessMapUv),y.push(R.combine),y.push(R.fogExp2),y.push(R.sizeAttenuation),y.push(R.morphTargetsCount),y.push(R.morphAttributeCount),y.push(R.numDirLights),y.push(R.numPointLights),y.push(R.numSpotLights),y.push(R.numSpotLightMaps),y.push(R.numHemiLights),y.push(R.numRectAreaLights),y.push(R.numDirLightShadows),y.push(R.numPointLightShadows),y.push(R.numSpotLightShadows),y.push(R.numSpotLightShadowsWithMaps),y.push(R.numLightProbes),y.push(R.shadowMapType),y.push(R.toneMapping),y.push(R.numClippingPlanes),y.push(R.numClipIntersection),y.push(R.depthPacking)}function x(y,R){o.disableAll(),R.instancing&&o.enable(0),R.instancingColor&&o.enable(1),R.instancingMorph&&o.enable(2),R.matcap&&o.enable(3),R.envMap&&o.enable(4),R.normalMapObjectSpace&&o.enable(5),R.normalMapTangentSpace&&o.enable(6),R.clearcoat&&o.enable(7),R.iridescence&&o.enable(8),R.alphaTest&&o.enable(9),R.vertexColors&&o.enable(10),R.vertexAlphas&&o.enable(11),R.vertexUv1s&&o.enable(12),R.vertexUv2s&&o.enable(13),R.vertexUv3s&&o.enable(14),R.vertexTangents&&o.enable(15),R.anisotropy&&o.enable(16),R.alphaHash&&o.enable(17),R.batching&&o.enable(18),R.dispersion&&o.enable(19),R.batchingColor&&o.enable(20),R.gradientMap&&o.enable(21),R.packedNormalMap&&o.enable(22),R.vertexNormals&&o.enable(23),y.push(o.mask),o.disableAll(),R.fog&&o.enable(0),R.useFog&&o.enable(1),R.flatShading&&o.enable(2),R.logarithmicDepthBuffer&&o.enable(3),R.reversedDepthBuffer&&o.enable(4),R.skinning&&o.enable(5),R.morphTargets&&o.enable(6),R.morphNormals&&o.enable(7),R.morphColors&&o.enable(8),R.premultipliedAlpha&&o.enable(9),R.shadowMapEnabled&&o.enable(10),R.doubleSided&&o.enable(11),R.flipSided&&o.enable(12),R.useDepthPacking&&o.enable(13),R.dithering&&o.enable(14),R.transmission&&o.enable(15),R.sheen&&o.enable(16),R.opaque&&o.enable(17),R.pointsUvs&&o.enable(18),R.decodeVideoTexture&&o.enable(19),R.decodeVideoTextureEmissive&&o.enable(20),R.alphaToCoverage&&o.enable(21),R.numLightProbeGrids>0&&o.enable(22),y.push(o.mask)}function v(y){const R=f[y.type];let P;if(R){const N=as[R];P=Lx.clone(N.uniforms)}else P=y.uniforms;return P}function S(y,R){let P=u.get(R);return P!==void 0?++P.usedTimes:(P=new oR(r,R,y,i),c.push(P),u.set(R,P)),P}function E(y){if(--y.usedTimes===0){const R=c.indexOf(y);c[R]=c[c.length-1],c.pop(),u.delete(y.cacheKey),y.destroy()}}function T(y){a.remove(y)}function A(){a.dispose()}return{getParameters:g,getProgramCacheKey:m,getUniforms:v,acquireProgram:S,releaseProgram:E,releaseShaderCache:T,programs:c,dispose:A}}function dR(){let r=new WeakMap;function e(o){return r.has(o)}function t(o){let a=r.get(o);return a===void 0&&(a={},r.set(o,a)),a}function n(o){r.delete(o)}function i(o,a,l){r.get(o)[a]=l}function s(){r=new WeakMap}return{has:e,get:t,remove:n,update:i,dispose:s}}function fR(r,e){return r.groupOrder!==e.groupOrder?r.groupOrder-e.groupOrder:r.renderOrder!==e.renderOrder?r.renderOrder-e.renderOrder:r.material.id!==e.material.id?r.material.id-e.material.id:r.materialVariant!==e.materialVariant?r.materialVariant-e.materialVariant:r.z!==e.z?r.z-e.z:r.id-e.id}function lg(r,e){return r.groupOrder!==e.groupOrder?r.groupOrder-e.groupOrder:r.renderOrder!==e.renderOrder?r.renderOrder-e.renderOrder:r.z!==e.z?e.z-r.z:r.id-e.id}function cg(){const r=[];let e=0;const t=[],n=[],i=[];function s(){e=0,t.length=0,n.length=0,i.length=0}function o(d){let f=0;return d.isInstancedMesh&&(f+=2),d.isSkinnedMesh&&(f+=1),f}function a(d,f,p,g,m,_){let x=r[e];return x===void 0?(x={id:d.id,object:d,geometry:f,material:p,materialVariant:o(d),groupOrder:g,renderOrder:d.renderOrder,z:m,group:_},r[e]=x):(x.id=d.id,x.object=d,x.geometry=f,x.material=p,x.materialVariant=o(d),x.groupOrder=g,x.renderOrder=d.renderOrder,x.z=m,x.group=_),e++,x}function l(d,f,p,g,m,_){const x=a(d,f,p,g,m,_);p.transmission>0?n.push(x):p.transparent===!0?i.push(x):t.push(x)}function c(d,f,p,g,m,_){const x=a(d,f,p,g,m,_);p.transmission>0?n.unshift(x):p.transparent===!0?i.unshift(x):t.unshift(x)}function u(d,f){t.length>1&&t.sort(d||fR),n.length>1&&n.sort(f||lg),i.length>1&&i.sort(f||lg)}function h(){for(let d=e,f=r.length;d=s.length?(o=new cg,s.push(o)):o=s[i],o}function t(){r=new WeakMap}return{get:e,dispose:t}}function mR(){const r={};return{get:function(e){if(r[e.id]!==void 0)return r[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new C,color:new Ve};break;case"SpotLight":t={position:new C,direction:new C,color:new Ve,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new C,color:new Ve,distance:0,decay:0};break;case"HemisphereLight":t={direction:new C,skyColor:new Ve,groundColor:new Ve};break;case"RectAreaLight":t={color:new Ve,position:new C,halfWidth:new C,halfHeight:new C};break}return r[e.id]=t,t}}}function gR(){const r={};return{get:function(e){if(r[e.id]!==void 0)return r[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new de};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new de};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new de,shadowCameraNear:1,shadowCameraFar:1e3};break}return r[e.id]=t,t}}}let _R=0;function xR(r,e){return(e.castShadow?2:0)-(r.castShadow?2:0)+(e.map?1:0)-(r.map?1:0)}function yR(r){const e=new mR,t=gR(),n={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 c=0;c<9;c++)n.probe.push(new C);const i=new C,s=new dt,o=new dt;function a(c){let u=0,h=0,d=0;for(let R=0;R<9;R++)n.probe[R].set(0,0,0);let f=0,p=0,g=0,m=0,_=0,x=0,v=0,S=0,E=0,T=0,A=0;c.sort(xR);for(let R=0,P=c.length;R0&&(r.has("OES_texture_float_linear")===!0?(n.rectAreaLTC1=Te.LTC_FLOAT_1,n.rectAreaLTC2=Te.LTC_FLOAT_2):(n.rectAreaLTC1=Te.LTC_HALF_1,n.rectAreaLTC2=Te.LTC_HALF_2)),n.ambient[0]=u,n.ambient[1]=h,n.ambient[2]=d;const y=n.hash;(y.directionalLength!==f||y.pointLength!==p||y.spotLength!==g||y.rectAreaLength!==m||y.hemiLength!==_||y.numDirectionalShadows!==x||y.numPointShadows!==v||y.numSpotShadows!==S||y.numSpotMaps!==E||y.numLightProbes!==A)&&(n.directional.length=f,n.spot.length=g,n.rectArea.length=m,n.point.length=p,n.hemi.length=_,n.directionalShadow.length=x,n.directionalShadowMap.length=x,n.pointShadow.length=v,n.pointShadowMap.length=v,n.spotShadow.length=S,n.spotShadowMap.length=S,n.directionalShadowMatrix.length=x,n.pointShadowMatrix.length=v,n.spotLightMatrix.length=S+E-T,n.spotLightMap.length=E,n.numSpotLightShadowsWithMaps=T,n.numLightProbes=A,y.directionalLength=f,y.pointLength=p,y.spotLength=g,y.rectAreaLength=m,y.hemiLength=_,y.numDirectionalShadows=x,y.numPointShadows=v,y.numSpotShadows=S,y.numSpotMaps=E,y.numLightProbes=A,n.version=_R++)}function l(c,u){let h=0,d=0,f=0,p=0,g=0;const m=u.matrixWorldInverse;for(let _=0,x=c.length;_=o.length?(a=new ug(r),o.push(a)):a=o[s],a}function n(){e=new WeakMap}return{get:t,dispose:n}}const SR=`void main() { gl_Position = vec4( position, 1.0 ); }`,bR=`uniform sampler2D shadow_pass; uniform vec2 resolution; uniform float radius; void main() { const float samples = float( VSM_SAMPLES ); float mean = 0.0; float squared_mean = 0.0; float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); float uvStart = samples <= 1.0 ? 0.0 : - 1.0; for ( float i = 0.0; i < samples; i ++ ) { float uvOffset = uvStart + i * uvStride; #ifdef HORIZONTAL_PASS vec2 distribution = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ).rg; mean += distribution.x; squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; #else float depth = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ).r; mean += depth; squared_mean += depth * depth; #endif } mean = mean / samples; squared_mean = squared_mean / samples; float std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) ); gl_FragColor = vec4( mean, std_dev, 0.0, 1.0 ); }`,TR=[new C(1,0,0),new C(-1,0,0),new C(0,1,0),new C(0,-1,0),new C(0,0,1),new C(0,0,-1)],MR=[new C(0,-1,0),new C(0,-1,0),new C(0,0,1),new C(0,0,-1),new C(0,-1,0),new C(0,-1,0)],hg=new dt,il=new C,Jh=new C;function ER(r,e,t){let n=new lc;const i=new de,s=new de,o=new tt,a=new Eb,l=new Ab,c={},u=t.maxTextureSize,h={[ni]:Pt,[Pt]:ni,[wn]:wn},d=new Ui({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new de},radius:{value:4}},vertexShader:SR,fragmentShader:bR}),f=d.clone();f.defines.HORIZONTAL_PASS=1;const p=new Pn;p.setAttribute("position",new In(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const g=new gn(p,d),m=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=Yo;let _=this.type;this.render=function(T,A,y){if(m.enabled===!1||m.autoUpdate===!1&&m.needsUpdate===!1||T.length===0)return;this.type===hx&&(ee("WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead."),this.type=Yo);const R=r.getRenderTarget(),P=r.getActiveCubeFace(),N=r.getActiveMipmapLevel(),U=r.state;U.setBlending(Cn),U.buffers.depth.getReversed()===!0?U.buffers.color.setClear(0,0,0,0):U.buffers.color.setClear(1,1,1,1),U.buffers.depth.setTest(!0),U.setScissorTest(!1);const G=_!==this.type;G&&A.traverse(function(V){V.material&&(Array.isArray(V.material)?V.material.forEach(L=>L.needsUpdate=!0):V.material.needsUpdate=!0)});for(let V=0,L=T.length;Vu||i.y>u)&&(i.x>u&&(s.x=Math.floor(u/ie.x),i.x=s.x*ie.x,H.mapSize.x=s.x),i.y>u&&(s.y=Math.floor(u/ie.y),i.y=s.y*ie.y,H.mapSize.y=s.y));const ce=r.state.buffers.depth.getReversed();if(H.camera._reversedDepth=ce,H.map===null||G===!0){if(H.map!==null&&(H.map.depthTexture!==null&&(H.map.depthTexture.dispose(),H.map.depthTexture=null),H.map.dispose()),this.type===fs){if(B.isPointLight){ee("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}H.map=new $i(i.x,i.y,{format:Fn,type:en,minFilter:Ut,magFilter:Ut,generateMipmaps:!1}),H.map.texture.name=B.name+".shadowMap",H.map.depthTexture=new Xn(i.x,i.y,Zt),H.map.depthTexture.name=B.name+".shadowMapDepth",H.map.depthTexture.format=Nn,H.map.depthTexture.compareFunction=null,H.map.depthTexture.minFilter=bt,H.map.depthTexture.magFilter=bt}else B.isPointLight?(H.map=new $x(i.x),H.map.depthTexture=new wx(i.x,wt)):(H.map=new $i(i.x,i.y),H.map.depthTexture=new Xn(i.x,i.y,wt)),H.map.depthTexture.name=B.name+".shadowMap",H.map.depthTexture.format=Nn,this.type===Yo?(H.map.depthTexture.compareFunction=ce?$s:Dr,H.map.depthTexture.minFilter=Ut,H.map.depthTexture.magFilter=Ut):(H.map.depthTexture.compareFunction=null,H.map.depthTexture.minFilter=bt,H.map.depthTexture.magFilter=bt);H.camera.updateProjectionMatrix()}const ve=H.map.isWebGLCubeRenderTarget?6:1;for(let Ce=0;Ce0||A.map&&A.alphaTest>0||A.alphaToCoverage===!0){const U=P.uuid,G=A.uuid;let V=c[U];V===void 0&&(V={},c[U]=V);let L=V[G];L===void 0&&(L=P.clone(),V[G]=L,A.addEventListener("dispose",E)),P=L}if(P.visible=A.visible,P.wireframe=A.wireframe,R===fs?P.side=A.shadowSide!==null?A.shadowSide:A.side:P.side=A.shadowSide!==null?A.shadowSide:h[A.side],P.alphaMap=A.alphaMap,P.alphaTest=A.alphaToCoverage===!0?.5:A.alphaTest,P.map=A.map,P.clipShadows=A.clipShadows,P.clippingPlanes=A.clippingPlanes,P.clipIntersection=A.clipIntersection,P.displacementMap=A.displacementMap,P.displacementScale=A.displacementScale,P.displacementBias=A.displacementBias,P.wireframeLinewidth=A.wireframeLinewidth,P.linewidth=A.linewidth,y.isPointLight===!0&&P.isMeshDistanceMaterial===!0){const U=r.properties.get(P);U.light=y}return P}function S(T,A,y,R,P){if(T.visible===!1)return;if(T.layers.test(A.layers)&&(T.isMesh||T.isLine||T.isPoints)&&(T.castShadow||T.receiveShadow&&P===fs)&&(!T.frustumCulled||n.intersectsObject(T))){T.modelViewMatrix.multiplyMatrices(y.matrixWorldInverse,T.matrixWorld);const G=e.update(T),V=T.material;if(Array.isArray(V)){const L=G.groups;for(let B=0,H=L.length;B=1):ce.indexOf("OpenGL ES")!==-1&&(ie=parseFloat(/^OpenGL ES (\d)/.exec(ce)[1]),H=ie>=2);let ve=null,Ce={};const ke=r.getParameter(r.SCISSOR_BOX),ut=r.getParameter(r.VIEWPORT),Mt=new tt().fromArray(ke),oe=new tt().fromArray(ut);function W(F,me,te,Pe){const xe=new Uint8Array(4),ue=r.createTexture();r.bindTexture(F,ue),r.texParameteri(F,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(F,r.TEXTURE_MAG_FILTER,r.NEAREST);for(let ze=0;ze"u"?!1:/OculusBrowser/g.test(navigator.userAgent),c=new de,u=new WeakMap,h=new Set;let d;const f=new WeakMap;let p=!1;try{p=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function g(w,b){return p?new OffscreenCanvas(w,b):Yl("canvas")}function m(w,b,z){let re=1;const he=rn(w);if((he.width>z||he.height>z)&&(re=z/Math.max(he.width,he.height)),re<1)if(typeof HTMLImageElement<"u"&&w instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&w instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&w instanceof ImageBitmap||typeof VideoFrame<"u"&&w instanceof VideoFrame){const fe=Math.floor(re*he.width),ye=Math.floor(re*he.height);d===void 0&&(d=g(fe,ye));const J=b?g(fe,ye):d;return J.width=fe,J.height=ye,J.getContext("2d").drawImage(w,0,0,fe,ye),ee("WebGLRenderer: Texture has been resized from ("+he.width+"x"+he.height+") to ("+fe+"x"+ye+")."),J}else return"data"in w&&ee("WebGLRenderer: Image in DataTexture is too big ("+he.width+"x"+he.height+")."),w;return w}function _(w){return w.generateMipmaps}function x(w){r.generateMipmap(w)}function v(w){return w.isWebGLCubeRenderTarget?r.TEXTURE_CUBE_MAP:w.isWebGL3DRenderTarget?r.TEXTURE_3D:w.isWebGLArrayRenderTarget||w.isCompressedArrayTexture?r.TEXTURE_2D_ARRAY:r.TEXTURE_2D}function S(w,b,z,re,he,fe=!1){if(w!==null){if(r[w]!==void 0)return r[w];ee("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+w+"'")}let ye;re&&(ye=e.get("EXT_texture_norm16"),ye||ee("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let J=b;if(b===r.RED&&(z===r.FLOAT&&(J=r.R32F),z===r.HALF_FLOAT&&(J=r.R16F),z===r.UNSIGNED_BYTE&&(J=r.R8),z===r.UNSIGNED_SHORT&&ye&&(J=ye.R16_EXT),z===r.SHORT&&ye&&(J=ye.R16_SNORM_EXT)),b===r.RED_INTEGER&&(z===r.UNSIGNED_BYTE&&(J=r.R8UI),z===r.UNSIGNED_SHORT&&(J=r.R16UI),z===r.UNSIGNED_INT&&(J=r.R32UI),z===r.BYTE&&(J=r.R8I),z===r.SHORT&&(J=r.R16I),z===r.INT&&(J=r.R32I)),b===r.RG&&(z===r.FLOAT&&(J=r.RG32F),z===r.HALF_FLOAT&&(J=r.RG16F),z===r.UNSIGNED_BYTE&&(J=r.RG8),z===r.UNSIGNED_SHORT&&ye&&(J=ye.RG16_EXT),z===r.SHORT&&ye&&(J=ye.RG16_SNORM_EXT)),b===r.RG_INTEGER&&(z===r.UNSIGNED_BYTE&&(J=r.RG8UI),z===r.UNSIGNED_SHORT&&(J=r.RG16UI),z===r.UNSIGNED_INT&&(J=r.RG32UI),z===r.BYTE&&(J=r.RG8I),z===r.SHORT&&(J=r.RG16I),z===r.INT&&(J=r.RG32I)),b===r.RGB_INTEGER&&(z===r.UNSIGNED_BYTE&&(J=r.RGB8UI),z===r.UNSIGNED_SHORT&&(J=r.RGB16UI),z===r.UNSIGNED_INT&&(J=r.RGB32UI),z===r.BYTE&&(J=r.RGB8I),z===r.SHORT&&(J=r.RGB16I),z===r.INT&&(J=r.RGB32I)),b===r.RGBA_INTEGER&&(z===r.UNSIGNED_BYTE&&(J=r.RGBA8UI),z===r.UNSIGNED_SHORT&&(J=r.RGBA16UI),z===r.UNSIGNED_INT&&(J=r.RGBA32UI),z===r.BYTE&&(J=r.RGBA8I),z===r.SHORT&&(J=r.RGBA16I),z===r.INT&&(J=r.RGBA32I)),b===r.RGB&&(z===r.UNSIGNED_SHORT&&ye&&(J=ye.RGB16_EXT),z===r.SHORT&&ye&&(J=ye.RGB16_SNORM_EXT),z===r.UNSIGNED_INT_5_9_9_9_REV&&(J=r.RGB9_E5),z===r.UNSIGNED_INT_10F_11F_11F_REV&&(J=r.R11F_G11F_B10F)),b===r.RGBA){const ae=fe?Na:Xe.getTransfer(he);z===r.FLOAT&&(J=r.RGBA32F),z===r.HALF_FLOAT&&(J=r.RGBA16F),z===r.UNSIGNED_BYTE&&(J=ae===Ee?r.SRGB8_ALPHA8:r.RGBA8),z===r.UNSIGNED_SHORT&&ye&&(J=ye.RGBA16_EXT),z===r.SHORT&&ye&&(J=ye.RGBA16_SNORM_EXT),z===r.UNSIGNED_SHORT_4_4_4_4&&(J=r.RGBA4),z===r.UNSIGNED_SHORT_5_5_5_1&&(J=r.RGB5_A1)}return(J===r.R16F||J===r.R32F||J===r.RG16F||J===r.RG32F||J===r.RGBA16F||J===r.RGBA32F)&&e.get("EXT_color_buffer_float"),J}function E(w,b){let z;return w?b===null||b===wt||b===ui?z=r.DEPTH24_STENCIL8:b===Zt?z=r.DEPTH32F_STENCIL8:b===Ci&&(z=r.DEPTH24_STENCIL8,ee("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):b===null||b===wt||b===ui?z=r.DEPTH_COMPONENT24:b===Zt?z=r.DEPTH_COMPONENT32F:b===Ci&&(z=r.DEPTH_COMPONENT16),z}function T(w,b){return _(w)===!0||w.isFramebufferTexture&&w.minFilter!==bt&&w.minFilter!==Ut?Math.log2(Math.max(b.width,b.height))+1:w.mipmaps!==void 0&&w.mipmaps.length>0?w.mipmaps.length:w.isCompressedTexture&&Array.isArray(w.image)?b.mipmaps.length:1}function A(w){const b=w.target;b.removeEventListener("dispose",A),R(b),b.isVideoTexture&&u.delete(b),b.isHTMLTexture&&h.delete(b)}function y(w){const b=w.target;b.removeEventListener("dispose",y),N(b)}function R(w){const b=n.get(w);if(b.__webglInit===void 0)return;const z=w.source,re=f.get(z);if(re){const he=re[b.__cacheKey];he.usedTimes--,he.usedTimes===0&&P(w),Object.keys(re).length===0&&f.delete(z)}n.remove(w)}function P(w){const b=n.get(w);r.deleteTexture(b.__webglTexture);const z=w.source,re=f.get(z);delete re[b.__cacheKey],o.memory.textures--}function N(w){const b=n.get(w);if(w.depthTexture&&(w.depthTexture.dispose(),n.remove(w.depthTexture)),w.isWebGLCubeRenderTarget)for(let re=0;re<6;re++){if(Array.isArray(b.__webglFramebuffer[re]))for(let he=0;he=i.maxTextures&&ee("WebGLTextures: Trying to use "+w+" texture units while this GPU supports only "+i.maxTextures),U+=1,w}function H(w){const b=[];return b.push(w.wrapS),b.push(w.wrapT),b.push(w.wrapR||0),b.push(w.magFilter),b.push(w.minFilter),b.push(w.anisotropy),b.push(w.internalFormat),b.push(w.format),b.push(w.type),b.push(w.generateMipmaps),b.push(w.premultiplyAlpha),b.push(w.flipY),b.push(w.unpackAlignment),b.push(w.colorSpace),b.join()}function ie(w,b){const z=n.get(w);if(w.isVideoTexture&&Xt(w),w.isRenderTargetTexture===!1&&w.isExternalTexture!==!0&&w.version>0&&z.__version!==w.version){const re=w.image;if(re===null)ee("WebGLRenderer: Texture marked for update but no image data found.");else if(re.complete===!1)ee("WebGLRenderer: Texture marked for update but image is incomplete");else{Ne(z,w,b);return}}else w.isExternalTexture&&(z.__webglTexture=w.sourceTexture?w.sourceTexture:null);t.bindTexture(r.TEXTURE_2D,z.__webglTexture,r.TEXTURE0+b)}function ce(w,b){const z=n.get(w);if(w.isRenderTargetTexture===!1&&w.version>0&&z.__version!==w.version){Ne(z,w,b);return}else w.isExternalTexture&&(z.__webglTexture=w.sourceTexture?w.sourceTexture:null);t.bindTexture(r.TEXTURE_2D_ARRAY,z.__webglTexture,r.TEXTURE0+b)}function ve(w,b){const z=n.get(w);if(w.isRenderTargetTexture===!1&&w.version>0&&z.__version!==w.version){Ne(z,w,b);return}t.bindTexture(r.TEXTURE_3D,z.__webglTexture,r.TEXTURE0+b)}function Ce(w,b){const z=n.get(w);if(w.isCubeDepthTexture!==!0&&w.version>0&&z.__version!==w.version){Le(z,w,b);return}t.bindTexture(r.TEXTURE_CUBE_MAP,z.__webglTexture,r.TEXTURE0+b)}const ke={[ro]:r.REPEAT,[ai]:r.CLAMP_TO_EDGE,[oo]:r.MIRRORED_REPEAT},ut={[bt]:r.NEAREST,[Kf]:r.NEAREST_MIPMAP_NEAREST,[Gs]:r.NEAREST_MIPMAP_LINEAR,[Ut]:r.LINEAR,[Qo]:r.LINEAR_MIPMAP_NEAREST,[li]:r.LINEAR_MIPMAP_LINEAR},Mt={[Zf]:r.NEVER,[ep]:r.ALWAYS,[Ku]:r.LESS,[Dr]:r.LEQUAL,[Qf]:r.EQUAL,[$s]:r.GEQUAL,[jl]:r.GREATER,[Jf]:r.NOTEQUAL};function oe(w,b){if(b.type===Zt&&e.has("OES_texture_float_linear")===!1&&(b.magFilter===Ut||b.magFilter===Qo||b.magFilter===Gs||b.magFilter===li||b.minFilter===Ut||b.minFilter===Qo||b.minFilter===Gs||b.minFilter===li)&&ee("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),r.texParameteri(w,r.TEXTURE_WRAP_S,ke[b.wrapS]),r.texParameteri(w,r.TEXTURE_WRAP_T,ke[b.wrapT]),(w===r.TEXTURE_3D||w===r.TEXTURE_2D_ARRAY)&&r.texParameteri(w,r.TEXTURE_WRAP_R,ke[b.wrapR]),r.texParameteri(w,r.TEXTURE_MAG_FILTER,ut[b.magFilter]),r.texParameteri(w,r.TEXTURE_MIN_FILTER,ut[b.minFilter]),b.compareFunction&&(r.texParameteri(w,r.TEXTURE_COMPARE_MODE,r.COMPARE_REF_TO_TEXTURE),r.texParameteri(w,r.TEXTURE_COMPARE_FUNC,Mt[b.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(b.magFilter===bt||b.minFilter!==Gs&&b.minFilter!==li||b.type===Zt&&e.has("OES_texture_float_linear")===!1)return;if(b.anisotropy>1||n.get(b).__currentAnisotropy){const z=e.get("EXT_texture_filter_anisotropic");r.texParameterf(w,z.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(b.anisotropy,i.getMaxAnisotropy())),n.get(b).__currentAnisotropy=b.anisotropy}}}function W(w,b){let z=!1;w.__webglInit===void 0&&(w.__webglInit=!0,b.addEventListener("dispose",A));const re=b.source;let he=f.get(re);he===void 0&&(he={},f.set(re,he));const fe=H(b);if(fe!==w.__cacheKey){he[fe]===void 0&&(he[fe]={texture:r.createTexture(),usedTimes:0},o.memory.textures++,z=!0),he[fe].usedTimes++;const ye=he[w.__cacheKey];ye!==void 0&&(he[w.__cacheKey].usedTimes--,ye.usedTimes===0&&P(b)),w.__cacheKey=fe,w.__webglTexture=he[fe].texture}return z}function se(w,b,z){return Math.floor(Math.floor(w/z)/b)}function le(w,b,z,re){const fe=w.updateRanges;if(fe.length===0)t.texSubImage2D(r.TEXTURE_2D,0,0,0,b.width,b.height,z,re,b.data);else{fe.sort((Ue,_e)=>Ue.start-_e.start);let ye=0;for(let Ue=1;Ue0){at&&St&&t.texStorage2D(r.TEXTURE_2D,me,_e,et[0].width,et[0].height);for(let te=0,Pe=et.length;te0){const xe=sf(pe.width,pe.height,b.format,b.type);for(const ue of b.layerUpdates){const ze=pe.data.subarray(ue*xe/pe.data.BYTES_PER_ELEMENT,(ue+1)*xe/pe.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(r.TEXTURE_2D_ARRAY,te,0,0,ue,pe.width,pe.height,1,Re,ze)}b.clearLayerUpdates()}else t.compressedTexSubImage3D(r.TEXTURE_2D_ARRAY,te,0,0,0,pe.width,pe.height,ae.depth,Re,pe.data)}else t.compressedTexImage3D(r.TEXTURE_2D_ARRAY,te,_e,pe.width,pe.height,ae.depth,0,pe.data,0,0);else ee("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else at?F&&t.texSubImage3D(r.TEXTURE_2D_ARRAY,te,0,0,0,pe.width,pe.height,ae.depth,Re,Ue,pe.data):t.texImage3D(r.TEXTURE_2D_ARRAY,te,_e,pe.width,pe.height,ae.depth,0,Re,Ue,pe.data)}else{at&&St&&t.texStorage2D(r.TEXTURE_2D,me,_e,et[0].width,et[0].height);for(let te=0,Pe=et.length;te0){const te=sf(ae.width,ae.height,b.format,b.type);for(const Pe of b.layerUpdates){const xe=ae.data.subarray(Pe*te/ae.data.BYTES_PER_ELEMENT,(Pe+1)*te/ae.data.BYTES_PER_ELEMENT);t.texSubImage3D(r.TEXTURE_2D_ARRAY,0,0,0,Pe,ae.width,ae.height,1,Re,Ue,xe)}b.clearLayerUpdates()}else t.texSubImage3D(r.TEXTURE_2D_ARRAY,0,0,0,0,ae.width,ae.height,ae.depth,Re,Ue,ae.data)}else t.texImage3D(r.TEXTURE_2D_ARRAY,0,_e,ae.width,ae.height,ae.depth,0,Re,Ue,ae.data);else if(b.isData3DTexture)at?(St&&t.texStorage3D(r.TEXTURE_3D,me,_e,ae.width,ae.height,ae.depth),F&&t.texSubImage3D(r.TEXTURE_3D,0,0,0,0,ae.width,ae.height,ae.depth,Re,Ue,ae.data)):t.texImage3D(r.TEXTURE_3D,0,_e,ae.width,ae.height,ae.depth,0,Re,Ue,ae.data);else if(b.isFramebufferTexture){if(St)if(at)t.texStorage2D(r.TEXTURE_2D,me,_e,ae.width,ae.height);else{let te=ae.width,Pe=ae.height;for(let xe=0;xe>=1,Pe>>=1}}else if(b.isHTMLTexture){if("texElementImage2D"in r){const te=r.canvas;if(te.hasAttribute("layoutsubtree")||te.setAttribute("layoutsubtree","true"),ae.parentNode!==te){te.appendChild(ae),h.add(b),te.onpaint=it=>{const ln=it.changedElements;for(const Bt of h)ln.includes(Bt.image)&&(Bt.needsUpdate=!0)},te.requestPaint();return}const Pe=0,xe=r.RGBA,ue=r.RGBA,ze=r.UNSIGNED_BYTE;r.texElementImage2D(r.TEXTURE_2D,Pe,xe,ue,ze,ae),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE)}}else if(et.length>0){if(at&&St){const te=rn(et[0]);t.texStorage2D(r.TEXTURE_2D,me,_e,te.width,te.height)}for(let te=0,Pe=et.length;te0&&Pe++;const ue=rn(_e[0]);t.texStorage2D(r.TEXTURE_CUBE_MAP,Pe,St,ue.width,ue.height)}for(let ue=0;ue<6;ue++)if(Ue){F?te&&t.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+ue,0,0,0,_e[ue].width,_e[ue].height,et,at,_e[ue].data):t.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+ue,0,St,_e[ue].width,_e[ue].height,0,et,at,_e[ue].data);for(let ze=0;ze>fe),pe=Math.max(1,b.height>>fe);he===r.TEXTURE_3D||he===r.TEXTURE_2D_ARRAY?t.texImage3D(he,fe,ae,_e,pe,b.depth,0,ye,J,null):t.texImage2D(he,fe,ae,_e,pe,0,ye,J,null)}t.bindFramebuffer(r.FRAMEBUFFER,w),mt(b)?a.framebufferTexture2DMultisampleEXT(r.FRAMEBUFFER,re,he,Ue.__webglTexture,0,yn(b)):(he===r.TEXTURE_2D||he>=r.TEXTURE_CUBE_MAP_POSITIVE_X&&he<=r.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&r.framebufferTexture2D(r.FRAMEBUFFER,re,he,Ue.__webglTexture,fe),t.bindFramebuffer(r.FRAMEBUFFER,null)}function xt(w,b,z){if(r.bindRenderbuffer(r.RENDERBUFFER,w),b.depthBuffer){const re=b.depthTexture,he=re&&re.isDepthTexture?re.type:null,fe=E(b.stencilBuffer,he),ye=b.stencilBuffer?r.DEPTH_STENCIL_ATTACHMENT:r.DEPTH_ATTACHMENT;mt(b)?a.renderbufferStorageMultisampleEXT(r.RENDERBUFFER,yn(b),fe,b.width,b.height):z?r.renderbufferStorageMultisample(r.RENDERBUFFER,yn(b),fe,b.width,b.height):r.renderbufferStorage(r.RENDERBUFFER,fe,b.width,b.height),r.framebufferRenderbuffer(r.FRAMEBUFFER,ye,r.RENDERBUFFER,w)}else{const re=b.textures;for(let he=0;he{delete b.__boundDepthTexture,delete b.__depthDisposeCallback,re.removeEventListener("dispose",he)};re.addEventListener("dispose",he),b.__depthDisposeCallback=he}b.__boundDepthTexture=re}if(w.depthTexture&&!b.__autoAllocateDepthBuffer)if(z)for(let re=0;re<6;re++)Qe(b.__webglFramebuffer[re],w,re);else{const re=w.texture.mipmaps;re&&re.length>0?Qe(b.__webglFramebuffer[0],w,0):Qe(b.__webglFramebuffer,w,0)}else if(z){b.__webglDepthbuffer=[];for(let re=0;re<6;re++)if(t.bindFramebuffer(r.FRAMEBUFFER,b.__webglFramebuffer[re]),b.__webglDepthbuffer[re]===void 0)b.__webglDepthbuffer[re]=r.createRenderbuffer(),xt(b.__webglDepthbuffer[re],w,!1);else{const he=w.stencilBuffer?r.DEPTH_STENCIL_ATTACHMENT:r.DEPTH_ATTACHMENT,fe=b.__webglDepthbuffer[re];r.bindRenderbuffer(r.RENDERBUFFER,fe),r.framebufferRenderbuffer(r.FRAMEBUFFER,he,r.RENDERBUFFER,fe)}}else{const re=w.texture.mipmaps;if(re&&re.length>0?t.bindFramebuffer(r.FRAMEBUFFER,b.__webglFramebuffer[0]):t.bindFramebuffer(r.FRAMEBUFFER,b.__webglFramebuffer),b.__webglDepthbuffer===void 0)b.__webglDepthbuffer=r.createRenderbuffer(),xt(b.__webglDepthbuffer,w,!1);else{const he=w.stencilBuffer?r.DEPTH_STENCIL_ATTACHMENT:r.DEPTH_ATTACHMENT,fe=b.__webglDepthbuffer;r.bindRenderbuffer(r.RENDERBUFFER,fe),r.framebufferRenderbuffer(r.FRAMEBUFFER,he,r.RENDERBUFFER,fe)}}t.bindFramebuffer(r.FRAMEBUFFER,null)}function Et(w,b,z){const re=n.get(w);b!==void 0&&we(re.__webglFramebuffer,w,w.texture,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,0),z!==void 0&&ft(w)}function Je(w){const b=w.texture,z=n.get(w),re=n.get(b);w.addEventListener("dispose",y);const he=w.textures,fe=w.isWebGLCubeRenderTarget===!0,ye=he.length>1;if(ye||(re.__webglTexture===void 0&&(re.__webglTexture=r.createTexture()),re.__version=b.version,o.memory.textures++),fe){z.__webglFramebuffer=[];for(let J=0;J<6;J++)if(b.mipmaps&&b.mipmaps.length>0){z.__webglFramebuffer[J]=[];for(let ae=0;ae0){z.__webglFramebuffer=[];for(let J=0;J0&&mt(w)===!1){z.__webglMultisampledFramebuffer=r.createFramebuffer(),z.__webglColorRenderbuffer=[],t.bindFramebuffer(r.FRAMEBUFFER,z.__webglMultisampledFramebuffer);for(let J=0;J0)for(let ae=0;ae0)for(let ae=0;ae0){if(mt(w)===!1){const b=w.textures,z=w.width,re=w.height;let he=r.COLOR_BUFFER_BIT;const fe=w.stencilBuffer?r.DEPTH_STENCIL_ATTACHMENT:r.DEPTH_ATTACHMENT,ye=n.get(w),J=b.length>1;if(J)for(let Re=0;Re0?t.bindFramebuffer(r.DRAW_FRAMEBUFFER,ye.__webglFramebuffer[0]):t.bindFramebuffer(r.DRAW_FRAMEBUFFER,ye.__webglFramebuffer);for(let Re=0;Re0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&b.__useRenderToTexture!==!1}function Xt(w){const b=o.render.frame;u.get(w)!==b&&(u.set(w,b),w.update())}function be(w,b){const z=w.colorSpace,re=w.format,he=w.type;return w.isCompressedTexture===!0||w.isVideoTexture===!0||z!==ql&&z!==ri&&(Xe.getTransfer(z)===Ee?(re!==an||he!==$t)&&ee("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):ne("WebGLTextures: Unsupported texture color space:",z)),b}function rn(w){return typeof HTMLImageElement<"u"&&w instanceof HTMLImageElement?(c.width=w.naturalWidth||w.width,c.height=w.naturalHeight||w.height):typeof VideoFrame<"u"&&w instanceof VideoFrame?(c.width=w.displayWidth,c.height=w.displayHeight):(c.width=w.width,c.height=w.height),c}this.allocateTextureUnit=B,this.resetTextureUnits=G,this.getTextureUnits=V,this.setTextureUnits=L,this.setTexture2D=ie,this.setTexture2DArray=ce,this.setTexture3D=ve,this.setTextureCube=Ce,this.rebindTextures=Et,this.setupRenderTarget=Je,this.updateRenderTargetMipmap=It,this.updateMultisampleRenderTarget=O,this.setupDepthRenderbuffer=ft,this.setupFrameBufferTexture=we,this.useMultisampledRTT=mt,this.isReversedDepthBuffer=function(){return t.buffers.depth.getReversed()}}function wR(r,e){function t(n,i=ri){let s;const o=Xe.getTransfer(i);if(n===$t)return r.UNSIGNED_BYTE;if(n===ic)return r.UNSIGNED_SHORT_4_4_4_4;if(n===sc)return r.UNSIGNED_SHORT_5_5_5_1;if(n===rc)return r.UNSIGNED_INT_5_9_9_9_REV;if(n===oc)return r.UNSIGNED_INT_10F_11F_11F_REV;if(n===_r)return r.BYTE;if(n===xr)return r.SHORT;if(n===Ci)return r.UNSIGNED_SHORT;if(n===Sn)return r.INT;if(n===wt)return r.UNSIGNED_INT;if(n===Zt)return r.FLOAT;if(n===en)return r.HALF_FLOAT;if(n===Yu)return r.ALPHA;if(n===Ba)return r.RGB;if(n===an)return r.RGBA;if(n===Nn)return r.DEPTH_COMPONENT;if(n===$n)return r.DEPTH_STENCIL;if(n===Oa)return r.RED;if(n===mo)return r.RED_INTEGER;if(n===Fn)return r.RG;if(n===go)return r.RG_INTEGER;if(n===ka)return r.RGBA_INTEGER;if(n===yr||n===vr||n===Sr||n===br)if(o===Ee)if(s=e.get("WEBGL_compressed_texture_s3tc_srgb"),s!==null){if(n===yr)return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===vr)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===Sr)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===br)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(s=e.get("WEBGL_compressed_texture_s3tc"),s!==null){if(n===yr)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===vr)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===Sr)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===br)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(n===Hl||n===Wl||n===$l||n===Xl)if(s=e.get("WEBGL_compressed_texture_pvrtc"),s!==null){if(n===Hl)return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===Wl)return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===$l)return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===Xl)return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(n===oa||n===aa||n===la||n===ca||n===ua||n===Rr||n===ha)if(s=e.get("WEBGL_compressed_texture_etc"),s!==null){if(n===oa||n===aa)return o===Ee?s.COMPRESSED_SRGB8_ETC2:s.COMPRESSED_RGB8_ETC2;if(n===la)return o===Ee?s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:s.COMPRESSED_RGBA8_ETC2_EAC;if(n===ca)return s.COMPRESSED_R11_EAC;if(n===ua)return s.COMPRESSED_SIGNED_R11_EAC;if(n===Rr)return s.COMPRESSED_RG11_EAC;if(n===ha)return s.COMPRESSED_SIGNED_RG11_EAC}else return null;if(n===da||n===fa||n===pa||n===ma||n===ga||n===_a||n===xa||n===ya||n===va||n===Sa||n===ba||n===Ta||n===Ma||n===Ea)if(s=e.get("WEBGL_compressed_texture_astc"),s!==null){if(n===da)return o===Ee?s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:s.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===fa)return o===Ee?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:s.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===pa)return o===Ee?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:s.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===ma)return o===Ee?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:s.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===ga)return o===Ee?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:s.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===_a)return o===Ee?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:s.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===xa)return o===Ee?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:s.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===ya)return o===Ee?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:s.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===va)return o===Ee?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:s.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===Sa)return o===Ee?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:s.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===ba)return o===Ee?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:s.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===Ta)return o===Ee?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:s.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===Ma)return o===Ee?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:s.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===Ea)return o===Ee?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:s.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(n===Aa||n===Jd||n===ef)if(s=e.get("EXT_texture_compression_bptc"),s!==null){if(n===Aa)return o===Ee?s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:s.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===Jd)return s.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===ef)return s.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(n===Ra||n===wa||n===wr||n===Ca)if(s=e.get("EXT_texture_compression_rgtc"),s!==null){if(n===Ra)return s.COMPRESSED_RED_RGTC1_EXT;if(n===wa)return s.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===wr)return s.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===Ca)return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return n===ui?r.UNSIGNED_INT_24_8:r[n]!==void 0?r[n]:null}return{convert:t}}const CR=` void main() { gl_Position = vec4( position, 1.0 ); }`,NR=` uniform sampler2DArray depthColor; uniform float depthWidth; uniform float depthHeight; void main() { vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight ); if ( coord.x >= 1.0 ) { gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; } else { gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; } }`;class PR{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){const n=new Cx(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=n}}getMesh(e){if(this.texture!==null&&this.mesh===null){const t=e.cameras[0].viewport,n=new Ui({vertexShader:CR,fragmentShader:NR,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new gn(new uc(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class DR extends Ii{constructor(e,t){super();const n=this;let i=null,s=1,o=null,a="local-floor",l=1,c=null,u=null,h=null,d=null,f=null,p=null;const g=typeof XRWebGLBinding<"u",m=new PR,_={},x=t.getContextAttributes();let v=null,S=null;const E=[],T=[],A=new de;let y=null;const R=new Rn;R.viewport=new tt;const P=new Rn;P.viewport=new tt;const N=[R,P],U=new Gx;let G=null,V=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(W){let se=E[W];return se===void 0&&(se=new Su,E[W]=se),se.getTargetRaySpace()},this.getControllerGrip=function(W){let se=E[W];return se===void 0&&(se=new Su,E[W]=se),se.getGripSpace()},this.getHand=function(W){let se=E[W];return se===void 0&&(se=new Su,E[W]=se),se.getHandSpace()};function L(W){const se=T.indexOf(W.inputSource);if(se===-1)return;const le=E[se];le!==void 0&&(le.update(W.inputSource,W.frame,c||o),le.dispatchEvent({type:W.type,data:W.inputSource}))}function B(){i.removeEventListener("select",L),i.removeEventListener("selectstart",L),i.removeEventListener("selectend",L),i.removeEventListener("squeeze",L),i.removeEventListener("squeezestart",L),i.removeEventListener("squeezeend",L),i.removeEventListener("end",B),i.removeEventListener("inputsourceschange",H);for(let W=0;W=0&&(T[Ne]=null,E[Ne].disconnect(le))}for(let se=0;se=T.length){T.push(le),Ne=we;break}else if(T[we]===null){T[we]=le,Ne=we;break}if(Ne===-1)break}const Le=E[Ne];Le&&Le.connect(le)}}const ie=new C,ce=new C;function ve(W,se,le){ie.setFromMatrixPosition(se.matrixWorld),ce.setFromMatrixPosition(le.matrixWorld);const Ne=ie.distanceTo(ce),Le=se.projectionMatrix.elements,we=le.projectionMatrix.elements,xt=Le[14]/(Le[10]-1),Qe=Le[14]/(Le[10]+1),ft=(Le[9]+1)/Le[5],Et=(Le[9]-1)/Le[5],Je=(Le[8]-1)/Le[0],It=(we[8]+1)/we[0],Dt=xt*Je,di=xt*It,O=Ne/(-Je+It),yn=O*-Je;if(se.matrixWorld.decompose(W.position,W.quaternion,W.scale),W.translateX(yn),W.translateZ(O),W.matrixWorld.compose(W.position,W.quaternion,W.scale),W.matrixWorldInverse.copy(W.matrixWorld).invert(),Le[10]===-1)W.projectionMatrix.copy(se.projectionMatrix),W.projectionMatrixInverse.copy(se.projectionMatrixInverse);else{const mt=xt+O,Xt=Qe+O,be=Dt-yn,rn=di+(Ne-yn),w=ft*Qe/Xt*mt,b=Et*Qe/Xt*mt;W.projectionMatrix.makePerspective(be,rn,w,b,mt,Xt),W.projectionMatrixInverse.copy(W.projectionMatrix).invert()}}function Ce(W,se){se===null?W.matrixWorld.copy(W.matrix):W.matrixWorld.multiplyMatrices(se.matrixWorld,W.matrix),W.matrixWorldInverse.copy(W.matrixWorld).invert()}this.updateCamera=function(W){if(i===null)return;let se=W.near,le=W.far;m.texture!==null&&(m.depthNear>0&&(se=m.depthNear),m.depthFar>0&&(le=m.depthFar)),U.near=P.near=R.near=se,U.far=P.far=R.far=le,(G!==U.near||V!==U.far)&&(i.updateRenderState({depthNear:U.near,depthFar:U.far}),G=U.near,V=U.far),U.layers.mask=W.layers.mask|6,R.layers.mask=U.layers.mask&-5,P.layers.mask=U.layers.mask&-3;const Ne=W.parent,Le=U.cameras;Ce(U,Ne);for(let we=0;we0&&(m.alphaTest.value=_.alphaTest);const x=e.get(_),v=x.envMap,S=x.envMapRotation;v&&(m.envMap.value=v,m.envMapRotation.value.setFromMatrix4(LR.makeRotationFromEuler(S)).transpose(),v.isCubeTexture&&v.isRenderTargetTexture===!1&&m.envMapRotation.value.premultiply(Kx),m.reflectivity.value=_.reflectivity,m.ior.value=_.ior,m.refractionRatio.value=_.refractionRatio),_.lightMap&&(m.lightMap.value=_.lightMap,m.lightMapIntensity.value=_.lightMapIntensity,t(_.lightMap,m.lightMapTransform)),_.aoMap&&(m.aoMap.value=_.aoMap,m.aoMapIntensity.value=_.aoMapIntensity,t(_.aoMap,m.aoMapTransform))}function o(m,_){m.diffuse.value.copy(_.color),m.opacity.value=_.opacity,_.map&&(m.map.value=_.map,t(_.map,m.mapTransform))}function a(m,_){m.dashSize.value=_.dashSize,m.totalSize.value=_.dashSize+_.gapSize,m.scale.value=_.scale}function l(m,_,x,v){m.diffuse.value.copy(_.color),m.opacity.value=_.opacity,m.size.value=_.size*x,m.scale.value=v*.5,_.map&&(m.map.value=_.map,t(_.map,m.uvTransform)),_.alphaMap&&(m.alphaMap.value=_.alphaMap,t(_.alphaMap,m.alphaMapTransform)),_.alphaTest>0&&(m.alphaTest.value=_.alphaTest)}function c(m,_){m.diffuse.value.copy(_.color),m.opacity.value=_.opacity,m.rotation.value=_.rotation,_.map&&(m.map.value=_.map,t(_.map,m.mapTransform)),_.alphaMap&&(m.alphaMap.value=_.alphaMap,t(_.alphaMap,m.alphaMapTransform)),_.alphaTest>0&&(m.alphaTest.value=_.alphaTest)}function u(m,_){m.specular.value.copy(_.specular),m.shininess.value=Math.max(_.shininess,1e-4)}function h(m,_){_.gradientMap&&(m.gradientMap.value=_.gradientMap)}function d(m,_){m.metalness.value=_.metalness,_.metalnessMap&&(m.metalnessMap.value=_.metalnessMap,t(_.metalnessMap,m.metalnessMapTransform)),m.roughness.value=_.roughness,_.roughnessMap&&(m.roughnessMap.value=_.roughnessMap,t(_.roughnessMap,m.roughnessMapTransform)),_.envMap&&(m.envMapIntensity.value=_.envMapIntensity)}function f(m,_,x){m.ior.value=_.ior,_.sheen>0&&(m.sheenColor.value.copy(_.sheenColor).multiplyScalar(_.sheen),m.sheenRoughness.value=_.sheenRoughness,_.sheenColorMap&&(m.sheenColorMap.value=_.sheenColorMap,t(_.sheenColorMap,m.sheenColorMapTransform)),_.sheenRoughnessMap&&(m.sheenRoughnessMap.value=_.sheenRoughnessMap,t(_.sheenRoughnessMap,m.sheenRoughnessMapTransform))),_.clearcoat>0&&(m.clearcoat.value=_.clearcoat,m.clearcoatRoughness.value=_.clearcoatRoughness,_.clearcoatMap&&(m.clearcoatMap.value=_.clearcoatMap,t(_.clearcoatMap,m.clearcoatMapTransform)),_.clearcoatRoughnessMap&&(m.clearcoatRoughnessMap.value=_.clearcoatRoughnessMap,t(_.clearcoatRoughnessMap,m.clearcoatRoughnessMapTransform)),_.clearcoatNormalMap&&(m.clearcoatNormalMap.value=_.clearcoatNormalMap,t(_.clearcoatNormalMap,m.clearcoatNormalMapTransform),m.clearcoatNormalScale.value.copy(_.clearcoatNormalScale),_.side===Pt&&m.clearcoatNormalScale.value.negate())),_.dispersion>0&&(m.dispersion.value=_.dispersion),_.iridescence>0&&(m.iridescence.value=_.iridescence,m.iridescenceIOR.value=_.iridescenceIOR,m.iridescenceThicknessMinimum.value=_.iridescenceThicknessRange[0],m.iridescenceThicknessMaximum.value=_.iridescenceThicknessRange[1],_.iridescenceMap&&(m.iridescenceMap.value=_.iridescenceMap,t(_.iridescenceMap,m.iridescenceMapTransform)),_.iridescenceThicknessMap&&(m.iridescenceThicknessMap.value=_.iridescenceThicknessMap,t(_.iridescenceThicknessMap,m.iridescenceThicknessMapTransform))),_.transmission>0&&(m.transmission.value=_.transmission,m.transmissionSamplerMap.value=x.texture,m.transmissionSamplerSize.value.set(x.width,x.height),_.transmissionMap&&(m.transmissionMap.value=_.transmissionMap,t(_.transmissionMap,m.transmissionMapTransform)),m.thickness.value=_.thickness,_.thicknessMap&&(m.thicknessMap.value=_.thicknessMap,t(_.thicknessMap,m.thicknessMapTransform)),m.attenuationDistance.value=_.attenuationDistance,m.attenuationColor.value.copy(_.attenuationColor)),_.anisotropy>0&&(m.anisotropyVector.value.set(_.anisotropy*Math.cos(_.anisotropyRotation),_.anisotropy*Math.sin(_.anisotropyRotation)),_.anisotropyMap&&(m.anisotropyMap.value=_.anisotropyMap,t(_.anisotropyMap,m.anisotropyMapTransform))),m.specularIntensity.value=_.specularIntensity,m.specularColor.value.copy(_.specularColor),_.specularColorMap&&(m.specularColorMap.value=_.specularColorMap,t(_.specularColorMap,m.specularColorMapTransform)),_.specularIntensityMap&&(m.specularIntensityMap.value=_.specularIntensityMap,t(_.specularIntensityMap,m.specularIntensityMapTransform))}function p(m,_){_.matcap&&(m.matcap.value=_.matcap)}function g(m,_){const x=e.get(_).light;m.referencePosition.value.setFromMatrixPosition(x.matrixWorld),m.nearDistance.value=x.shadow.camera.near,m.farDistance.value=x.shadow.camera.far}return{refreshFogUniforms:n,refreshMaterialUniforms:i}}function FR(r,e,t,n){let i={},s={},o=[];const a=r.getParameter(r.MAX_UNIFORM_BUFFER_BINDINGS);function l(x,v){const S=v.program;n.uniformBlockBinding(x,S)}function c(x,v){let S=i[x.id];S===void 0&&(p(x),S=u(x),i[x.id]=S,x.addEventListener("dispose",m));const E=v.program;n.updateUBOMapping(x,E);const T=e.render.frame;s[x.id]!==T&&(d(x),s[x.id]=T)}function u(x){const v=h();x.__bindingPointIndex=v;const S=r.createBuffer(),E=x.__size,T=x.usage;return r.bindBuffer(r.UNIFORM_BUFFER,S),r.bufferData(r.UNIFORM_BUFFER,E,T),r.bindBuffer(r.UNIFORM_BUFFER,null),r.bindBufferBase(r.UNIFORM_BUFFER,v,S),S}function h(){for(let x=0;x0&&(S+=E-T),x.__size=S,x.__cache={},this}function g(x){const v={boundary:0,storage:0};return typeof x=="number"||typeof x=="boolean"?(v.boundary=4,v.storage=4):x.isVector2?(v.boundary=8,v.storage=8):x.isVector3||x.isColor?(v.boundary=16,v.storage=12):x.isVector4?(v.boundary=16,v.storage=16):x.isMatrix3?(v.boundary=48,v.storage=48):x.isMatrix4?(v.boundary=64,v.storage=64):x.isTexture?ee("WebGLRenderer: Texture samplers can not be part of an uniforms group."):ArrayBuffer.isView(x)?(v.boundary=16,v.storage=x.byteLength):ee("WebGLRenderer: Unsupported uniform value type.",x),v}function m(x){const v=x.target;v.removeEventListener("dispose",m);const S=o.indexOf(v.__bindingPointIndex);o.splice(S,1),r.deleteBuffer(i[v.id]),delete i[v.id],delete s[v.id]}function _(){for(const x in i)r.deleteBuffer(i[x]);o=[],i={},s={}}return{bind:l,update:c,dispose:_}}const IR=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 Qi=null;function BR(){return Qi===null&&(Qi=new up(IR,16,16,Fn,en),Qi.name="DFG_LUT",Qi.minFilter=Ut,Qi.magFilter=Ut,Qi.wrapS=ai,Qi.wrapT=ai,Qi.generateMipmaps=!1,Qi.needsUpdate=!0),Qi}class OR{constructor(e={}){const{canvas:t=Sx(),context:n=null,depth:i=!0,stencil:s=!1,alpha:o=!1,antialias:a=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:c=!1,powerPreference:u="default",failIfMajorPerformanceCaveat:h=!1,reversedDepthBuffer:d=!1,outputBufferType:f=$t}=e;this.isWebGLRenderer=!0;let p;if(n!==null){if(typeof WebGLRenderingContext<"u"&&n instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");p=n.getContextAttributes().alpha}else p=o;const g=f,m=new Set([ka,go,mo]),_=new Set([$t,wt,Ci,ui,ic,sc]),x=new Uint32Array(4),v=new Int32Array(4),S=new C;let E=null,T=null;const A=[],y=[];let R=null;this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=Un,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const P=this;let N=!1,U=null;this._outputColorSpace=Qn;let G=0,V=0,L=null,B=-1,H=null;const ie=new tt,ce=new tt;let ve=null;const Ce=new Ve(0);let ke=0,ut=t.width,Mt=t.height,oe=1,W=null,se=null;const le=new tt(0,0,ut,Mt),Ne=new tt(0,0,ut,Mt);let Le=!1;const we=new lc;let xt=!1,Qe=!1;const ft=new dt,Et=new C,Je=new tt,It={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let Dt=!1;function di(){return L===null?oe:1}let O=n;function yn(M,k){return t.getContext(M,k)}try{const M={alpha:!0,depth:i,stencil:s,antialias:a,premultipliedAlpha:l,preserveDrawingBuffer:c,powerPreference:u,failIfMajorPerformanceCaveat:h};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${po}`),t.addEventListener("webglcontextlost",ue,!1),t.addEventListener("webglcontextrestored",ze,!1),t.addEventListener("webglcontextcreationerror",it,!1),O===null){const k="webgl2";if(O=yn(k,M),O===null)throw yn(k)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(M){throw ne("WebGLRenderer: "+M.message),M}let mt,Xt,be,rn,w,b,z,re,he,fe,ye,J,ae,Re,Ue,_e,pe,et,at,St,F,me,te;function Pe(){mt=new BE(O),mt.init(),F=new wR(O,mt),Xt=new CE(O,mt,e,F),be=new AR(O,mt),Xt.reversedDepthBuffer&&d&&be.buffers.depth.setReversed(!0),rn=new GE(O),w=new dR,b=new RR(O,mt,be,w,Xt,F,rn),z=new IE(P),re=new Wb(O),me=new RE(O,re),he=new OE(O,re,rn,me),fe=new zE(O,he,re,me,rn),et=new VE(O,Xt,b),Ue=new NE(w),ye=new hR(P,z,mt,Xt,me,Ue),J=new UR(P,w),ae=new pR,Re=new vR(mt),pe=new AE(P,z,be,fe,p,l),_e=new ER(P,fe,Xt),te=new FR(O,rn,Xt,be),at=new wE(O,mt,rn),St=new kE(O,mt,rn),rn.programs=ye.programs,P.capabilities=Xt,P.extensions=mt,P.properties=w,P.renderLists=ae,P.shadowMap=_e,P.state=be,P.info=rn}Pe(),g!==$t&&(R=new WE(g,t.width,t.height,i,s));const xe=new DR(P,O);this.xr=xe,this.getContext=function(){return O},this.getContextAttributes=function(){return O.getContextAttributes()},this.forceContextLoss=function(){const M=mt.get("WEBGL_lose_context");M&&M.loseContext()},this.forceContextRestore=function(){const M=mt.get("WEBGL_lose_context");M&&M.restoreContext()},this.getPixelRatio=function(){return oe},this.setPixelRatio=function(M){M!==void 0&&(oe=M,this.setSize(ut,Mt,!1))},this.getSize=function(M){return M.set(ut,Mt)},this.setSize=function(M,k,q=!0){if(xe.isPresenting){ee("WebGLRenderer: Can't change size while VR device is presenting.");return}ut=M,Mt=k,t.width=Math.floor(M*oe),t.height=Math.floor(k*oe),q===!0&&(t.style.width=M+"px",t.style.height=k+"px"),R!==null&&R.setSize(t.width,t.height),this.setViewport(0,0,M,k)},this.getDrawingBufferSize=function(M){return M.set(ut*oe,Mt*oe).floor()},this.setDrawingBufferSize=function(M,k,q){ut=M,Mt=k,oe=q,t.width=Math.floor(M*q),t.height=Math.floor(k*q),this.setViewport(0,0,M,k)},this.setEffects=function(M){if(g===$t){ne("THREE.WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(M){for(let k=0;k{function Ae(){if($.forEach(function(Fe){w.get(Fe).currentProgram.isReady()&&$.delete(Fe)}),$.size===0){X(M);return}setTimeout(Ae,10)}mt.get("KHR_parallel_shader_compile")!==null?Ae():setTimeout(Ae,10)})};let xh=null;function Sv(M){xh&&xh(M)}function nm(){Ir.stop()}function im(){Ir.start()}const Ir=new Hx;Ir.setAnimationLoop(Sv),typeof self<"u"&&Ir.setContext(self),this.setAnimationLoop=function(M){xh=M,xe.setAnimationLoop(M),M===null?Ir.stop():Ir.start()},xe.addEventListener("sessionstart",nm),xe.addEventListener("sessionend",im),this.render=function(M,k){if(k!==void 0&&k.isCamera!==!0){ne("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(N===!0)return;U!==null&&U.renderStart(M,k);const q=xe.enabled===!0&&xe.isPresenting===!0,$=R!==null&&(L===null||q)&&R.begin(P,L);if(M.matrixWorldAutoUpdate===!0&&M.updateMatrixWorld(),k.parent===null&&k.matrixWorldAutoUpdate===!0&&k.updateMatrixWorld(),xe.enabled===!0&&xe.isPresenting===!0&&(R===null||R.isCompositing()===!1)&&(xe.cameraAutoUpdate===!0&&xe.updateCamera(k),k=xe.getCamera()),M.isScene===!0&&M.onBeforeRender(P,M,k,L),T=Re.get(M,y.length),T.init(k),T.state.textureUnits=b.getTextureUnits(),y.push(T),ft.multiplyMatrices(k.projectionMatrix,k.matrixWorldInverse),we.setFromProjectionMatrix(ft,ti,k.reversedDepth),Qe=this.localClippingEnabled,xt=Ue.init(this.clippingPlanes,Qe),E=ae.get(M,A.length),E.init(),A.push(E),xe.enabled===!0&&xe.isPresenting===!0){const Fe=P.xr.getDepthSensingMesh();Fe!==null&&yh(Fe,k,-1/0,P.sortObjects)}yh(M,k,0,P.sortObjects),E.finish(),P.sortObjects===!0&&E.sort(W,se),Dt=xe.enabled===!1||xe.isPresenting===!1||xe.hasDepthSensing()===!1,Dt&&pe.addToRenderList(E,M),this.info.render.frame++,xt===!0&&Ue.beginShadows();const X=T.state.shadowsArray;if(_e.render(X,M,k),xt===!0&&Ue.endShadows(),this.info.autoReset===!0&&this.info.reset(),($&&R.hasRenderPass())===!1){const Fe=E.opaque,Me=E.transmissive;if(T.setupLights(),k.isArrayCamera){const Ge=k.cameras;if(Me.length>0)for(let He=0,st=Ge.length;He0&&rm(Fe,Me,M,k),Dt&&pe.render(M),sm(E,M,k)}L!==null&&V===0&&(b.updateMultisampleRenderTarget(L),b.updateRenderTargetMipmap(L)),$&&R.end(P),M.isScene===!0&&M.onAfterRender(P,M,k),me.resetDefaultState(),B=-1,H=null,y.pop(),y.length>0?(T=y[y.length-1],b.setTextureUnits(T.state.textureUnits),xt===!0&&Ue.setGlobalState(P.clippingPlanes,T.state.camera)):T=null,A.pop(),A.length>0?E=A[A.length-1]:E=null,U!==null&&U.renderEnd()};function yh(M,k,q,$){if(M.visible===!1)return;if(M.layers.test(k.layers)){if(M.isGroup)q=M.renderOrder;else if(M.isLOD)M.autoUpdate===!0&&M.update(k);else if(M.isLightProbeGrid)T.pushLightProbeGrid(M);else if(M.isLight)T.pushLight(M),M.castShadow&&T.pushShadow(M);else if(M.isSprite){if(!M.frustumCulled||we.intersectsSprite(M)){$&&Je.setFromMatrixPosition(M.matrixWorld).applyMatrix4(ft);const Fe=fe.update(M),Me=M.material;Me.visible&&E.push(M,Fe,Me,q,Je.z,null)}}else if((M.isMesh||M.isLine||M.isPoints)&&(!M.frustumCulled||we.intersectsObject(M))){const Fe=fe.update(M),Me=M.material;if($&&(M.boundingSphere!==void 0?(M.boundingSphere===null&&M.computeBoundingSphere(),Je.copy(M.boundingSphere.center)):(Fe.boundingSphere===null&&Fe.computeBoundingSphere(),Je.copy(Fe.boundingSphere.center)),Je.applyMatrix4(M.matrixWorld).applyMatrix4(ft)),Array.isArray(Me)){const Ge=Fe.groups;for(let He=0,st=Ge.length;He0&&xc(X,k,q),Ae.length>0&&xc(Ae,k,q),Fe.length>0&&xc(Fe,k,q),be.buffers.depth.setTest(!0),be.buffers.depth.setMask(!0),be.buffers.color.setMask(!0),be.setPolygonOffset(!1)}function rm(M,k,q,$){if((q.isScene===!0?q.overrideMaterial:null)!==null)return;if(T.state.transmissionRenderTarget[$.id]===void 0){const $e=mt.has("EXT_color_buffer_half_float")||mt.has("EXT_color_buffer_float");T.state.transmissionRenderTarget[$.id]=new $i(1,1,{generateMipmaps:!0,type:$e?en:$t,minFilter:li,samples:Math.max(4,Xt.samples),stencilBuffer:s,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Xe.workingColorSpace})}const Ae=T.state.transmissionRenderTarget[$.id],Fe=$.viewport||ie;Ae.setSize(Fe.z*P.transmissionResolutionScale,Fe.w*P.transmissionResolutionScale);const Me=P.getRenderTarget(),Ge=P.getActiveCubeFace(),He=P.getActiveMipmapLevel();P.setRenderTarget(Ae),P.getClearColor(Ce),ke=P.getClearAlpha(),ke<1&&P.setClearColor(16777215,.5),P.clear(),Dt&&pe.render(q);const st=P.toneMapping;P.toneMapping=Un;const ct=$.viewport;if($.viewport!==void 0&&($.viewport=void 0),T.setupLightsView($),xt===!0&&Ue.setGlobalState(P.clippingPlanes,$),xc(M,q,$),b.updateMultisampleRenderTarget(Ae),b.updateRenderTargetMipmap(Ae),mt.has("WEBGL_multisampled_render_to_texture")===!1){let $e=!1;for(let Ot=0,cn=k.length;Ot0,$.currentProgram=ct,$.uniformsList=null,ct}function am(M){if(M.uniformsList===null){const k=M.currentProgram.getUniforms();M.uniformsList=bu.seqWithValue(k.seq,M.uniforms)}return M.uniformsList}function lm(M,k){const q=w.get(M);q.outputColorSpace=k.outputColorSpace,q.batching=k.batching,q.batchingColor=k.batchingColor,q.instancing=k.instancing,q.instancingColor=k.instancingColor,q.instancingMorph=k.instancingMorph,q.skinning=k.skinning,q.morphTargets=k.morphTargets,q.morphNormals=k.morphNormals,q.morphColors=k.morphColors,q.morphTargetsCount=k.morphTargetsCount,q.numClippingPlanes=k.numClippingPlanes,q.numIntersection=k.numClipIntersection,q.vertexAlphas=k.vertexAlphas,q.vertexTangents=k.vertexTangents,q.toneMapping=k.toneMapping}function bv(M,k){if(M.length===0)return null;if(M.length===1)return M[0].texture!==null?M[0]:null;S.setFromMatrixPosition(k.matrixWorld);for(let q=0,$=M.length;q<$;q++){const X=M[q];if(X.texture!==null&&X.boundingBox.containsPoint(S))return X}return null}function Tv(M,k,q,$,X){k.isScene!==!0&&(k=It),b.resetTextureUnits();const Ae=k.fog,Fe=$.isMeshStandardMaterial||$.isMeshLambertMaterial||$.isMeshPhongMaterial?k.environment:null,Me=L===null?P.outputColorSpace:L.isXRRenderTarget===!0?L.texture.colorSpace:Xe.workingColorSpace,Ge=$.isMeshStandardMaterial||$.isMeshLambertMaterial&&!$.envMap||$.isMeshPhongMaterial&&!$.envMap,He=z.get($.envMap||Fe,Ge),st=$.vertexColors===!0&&!!q.attributes.color&&q.attributes.color.itemSize===4,ct=!!q.attributes.tangent&&(!!$.normalMap||$.anisotropy>0),$e=!!q.morphAttributes.position,Ot=!!q.morphAttributes.normal,cn=!!q.morphAttributes.color;let on=Un;$.toneMapped&&(L===null||L.isXRRenderTarget===!0)&&(on=P.toneMapping);const Vt=q.morphAttributes.position||q.morphAttributes.normal||q.morphAttributes.color,kn=Vt!==void 0?Vt.length:0,De=w.get($),fi=T.state.lights;if(xt===!0&&(Qe===!0||M!==H)){const qt=M===H&&$.id===B;Ue.setState($,M,qt)}let vt=!1;$.version===De.__version?(De.needsLights&&De.lightsStateVersion!==fi.state.version||De.outputColorSpace!==Me||X.isBatchedMesh&&De.batching===!1||!X.isBatchedMesh&&De.batching===!0||X.isBatchedMesh&&De.batchingColor===!0&&X.colorTexture===null||X.isBatchedMesh&&De.batchingColor===!1&&X.colorTexture!==null||X.isInstancedMesh&&De.instancing===!1||!X.isInstancedMesh&&De.instancing===!0||X.isSkinnedMesh&&De.skinning===!1||!X.isSkinnedMesh&&De.skinning===!0||X.isInstancedMesh&&De.instancingColor===!0&&X.instanceColor===null||X.isInstancedMesh&&De.instancingColor===!1&&X.instanceColor!==null||X.isInstancedMesh&&De.instancingMorph===!0&&X.morphTexture===null||X.isInstancedMesh&&De.instancingMorph===!1&&X.morphTexture!==null||De.envMap!==He||$.fog===!0&&De.fog!==Ae||De.numClippingPlanes!==void 0&&(De.numClippingPlanes!==Ue.numPlanes||De.numIntersection!==Ue.numIntersection)||De.vertexAlphas!==st||De.vertexTangents!==ct||De.morphTargets!==$e||De.morphNormals!==Ot||De.morphColors!==cn||De.toneMapping!==on||De.morphTargetsCount!==kn||!!De.lightProbeGrid!=T.state.lightProbeGridArray.length>0)&&(vt=!0):(vt=!0,De.__version=$.version);let bi=De.currentProgram;vt===!0&&(bi=yc($,k,X),U&&$.isNodeMaterial&&U.onUpdateProgram($,bi,De));let ji=!1,Ys=!1,Mo=!1;const zt=bi.getUniforms(),un=De.uniforms;if(be.useProgram(bi.program)&&(ji=!0,Ys=!0,Mo=!0),$.id!==B&&(B=$.id,Ys=!0),De.needsLights){const qt=bv(T.state.lightProbeGridArray,X);De.lightProbeGrid!==qt&&(De.lightProbeGrid=qt,Ys=!0)}if(ji||H!==M){be.buffers.depth.getReversed()&&M.reversedDepth!==!0&&(M._reversedDepth=!0,M.updateProjectionMatrix()),zt.setValue(O,"projectionMatrix",M.projectionMatrix),zt.setValue(O,"viewMatrix",M.matrixWorldInverse);const Zs=zt.map.cameraPosition;Zs!==void 0&&Zs.setValue(O,Et.setFromMatrixPosition(M.matrixWorld)),Xt.logarithmicDepthBuffer&&zt.setValue(O,"logDepthBufFC",2/(Math.log(M.far+1)/Math.LN2)),($.isMeshPhongMaterial||$.isMeshToonMaterial||$.isMeshLambertMaterial||$.isMeshBasicMaterial||$.isMeshStandardMaterial||$.isShaderMaterial)&&zt.setValue(O,"isOrthographic",M.isOrthographicCamera===!0),H!==M&&(H=M,Ys=!0,Mo=!0)}if(De.needsLights&&(fi.state.directionalShadowMap.length>0&&zt.setValue(O,"directionalShadowMap",fi.state.directionalShadowMap,b),fi.state.spotShadowMap.length>0&&zt.setValue(O,"spotShadowMap",fi.state.spotShadowMap,b),fi.state.pointShadowMap.length>0&&zt.setValue(O,"pointShadowMap",fi.state.pointShadowMap,b)),X.isSkinnedMesh){zt.setOptional(O,X,"bindMatrix"),zt.setOptional(O,X,"bindMatrixInverse");const qt=X.skeleton;qt&&(qt.boneTexture===null&&qt.computeBoneTexture(),zt.setValue(O,"boneTexture",qt.boneTexture,b))}X.isBatchedMesh&&(zt.setOptional(O,X,"batchingTexture"),zt.setValue(O,"batchingTexture",X._matricesTexture,b),zt.setOptional(O,X,"batchingIdTexture"),zt.setValue(O,"batchingIdTexture",X._indirectTexture,b),zt.setOptional(O,X,"batchingColorTexture"),X._colorsTexture!==null&&zt.setValue(O,"batchingColorTexture",X._colorsTexture,b));const Ks=q.morphAttributes;if((Ks.position!==void 0||Ks.normal!==void 0||Ks.color!==void 0)&&et.update(X,q,bi),(Ys||De.receiveShadow!==X.receiveShadow)&&(De.receiveShadow=X.receiveShadow,zt.setValue(O,"receiveShadow",X.receiveShadow)),($.isMeshStandardMaterial||$.isMeshLambertMaterial||$.isMeshPhongMaterial)&&$.envMap===null&&k.environment!==null&&(un.envMapIntensity.value=k.environmentIntensity),un.dfgLUT!==void 0&&(un.dfgLUT.value=BR()),Ys){if(zt.setValue(O,"toneMappingExposure",P.toneMappingExposure),De.needsLights&&Mv(un,Mo),Ae&&$.fog===!0&&J.refreshFogUniforms(un,Ae),J.refreshMaterialUniforms(un,$,oe,Mt,T.state.transmissionRenderTarget[M.id]),De.needsLights&&De.lightProbeGrid){const qt=De.lightProbeGrid;un.probesSH.value=qt.texture,un.probesMin.value.copy(qt.boundingBox.min),un.probesMax.value.copy(qt.boundingBox.max),un.probesResolution.value.copy(qt.resolution)}bu.upload(O,am(De),un,b)}if($.isShaderMaterial&&$.uniformsNeedUpdate===!0&&(bu.upload(O,am(De),un,b),$.uniformsNeedUpdate=!1),$.isSpriteMaterial&&zt.setValue(O,"center",X.center),zt.setValue(O,"modelViewMatrix",X.modelViewMatrix),zt.setValue(O,"normalMatrix",X.normalMatrix),zt.setValue(O,"modelMatrix",X.matrixWorld),$.uniformsGroups!==void 0){const qt=$.uniformsGroups;for(let Zs=0,Eo=qt.length;Zs0&&b.useMultisampledRTT(M)===!1?$=w.get(M).__webglMultisampledFramebuffer:Array.isArray(He)?$=He[q]:$=He,ie.copy(M.viewport),ce.copy(M.scissor),ve=M.scissorTest}else ie.copy(le).multiplyScalar(oe).floor(),ce.copy(Ne).multiplyScalar(oe).floor(),ve=Le;if(q!==0&&($=Av),be.bindFramebuffer(O.FRAMEBUFFER,$)&&be.drawBuffers(M,$),be.viewport(ie),be.scissor(ce),be.setScissorTest(ve),X){const Me=w.get(M.texture);O.framebufferTexture2D(O.FRAMEBUFFER,O.COLOR_ATTACHMENT0,O.TEXTURE_CUBE_MAP_POSITIVE_X+k,Me.__webglTexture,q)}else if(Ae){const Me=k;for(let Ge=0;Ge1&&O.readBuffer(O.COLOR_ATTACHMENT0+Me),!Xt.textureFormatReadable(st)){ne("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!Xt.textureTypeReadable(ct)){ne("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}k>=0&&k<=M.width-$&&q>=0&&q<=M.height-X&&O.readPixels(k,q,$,X,F.convert(st),F.convert(ct),Ae)}finally{const He=L!==null?w.get(L).__webglFramebuffer:null;be.bindFramebuffer(O.FRAMEBUFFER,He)}}},this.readRenderTargetPixelsAsync=async function(M,k,q,$,X,Ae,Fe,Me=0){if(!(M&&M.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Ge=w.get(M).__webglFramebuffer;if(M.isWebGLCubeRenderTarget&&Fe!==void 0&&(Ge=Ge[Fe]),Ge)if(k>=0&&k<=M.width-$&&q>=0&&q<=M.height-X){be.bindFramebuffer(O.FRAMEBUFFER,Ge);const He=M.textures[Me],st=He.format,ct=He.type;if(M.textures.length>1&&O.readBuffer(O.COLOR_ATTACHMENT0+Me),!Xt.textureFormatReadable(st))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!Xt.textureTypeReadable(ct))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const $e=O.createBuffer();O.bindBuffer(O.PIXEL_PACK_BUFFER,$e),O.bufferData(O.PIXEL_PACK_BUFFER,Ae.byteLength,O.STREAM_READ),O.readPixels(k,q,$,X,F.convert(st),F.convert(ct),0);const Ot=L!==null?w.get(L).__webglFramebuffer:null;be.bindFramebuffer(O.FRAMEBUFFER,Ot);const cn=O.fenceSync(O.SYNC_GPU_COMMANDS_COMPLETE,0);return O.flush(),await fS(O,cn,4),O.bindBuffer(O.PIXEL_PACK_BUFFER,$e),O.getBufferSubData(O.PIXEL_PACK_BUFFER,0,Ae),O.deleteBuffer($e),O.deleteSync(cn),Ae}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(M,k=null,q=0){const $=Math.pow(2,-q),X=Math.floor(M.image.width*$),Ae=Math.floor(M.image.height*$),Fe=k!==null?k.x:0,Me=k!==null?k.y:0;b.setTexture2D(M,0),O.copyTexSubImage2D(O.TEXTURE_2D,q,0,0,Fe,Me,X,Ae),be.unbindTexture()};const Rv=O.createFramebuffer(),wv=O.createFramebuffer();this.copyTextureToTexture=function(M,k,q=null,$=null,X=0,Ae=0){let Fe,Me,Ge,He,st,ct,$e,Ot,cn;const on=M.isCompressedTexture?M.mipmaps[Ae]:M.image;if(q!==null)Fe=q.max.x-q.min.x,Me=q.max.y-q.min.y,Ge=q.isBox3?q.max.z-q.min.z:1,He=q.min.x,st=q.min.y,ct=q.isBox3?q.min.z:0;else{const un=Math.pow(2,-X);Fe=Math.floor(on.width*un),Me=Math.floor(on.height*un),M.isDataArrayTexture?Ge=on.depth:M.isData3DTexture?Ge=Math.floor(on.depth*un):Ge=1,He=0,st=0,ct=0}$!==null?($e=$.x,Ot=$.y,cn=$.z):($e=0,Ot=0,cn=0);const Vt=F.convert(k.format),kn=F.convert(k.type);let De;k.isData3DTexture?(b.setTexture3D(k,0),De=O.TEXTURE_3D):k.isDataArrayTexture||k.isCompressedArrayTexture?(b.setTexture2DArray(k,0),De=O.TEXTURE_2D_ARRAY):(b.setTexture2D(k,0),De=O.TEXTURE_2D),be.activeTexture(O.TEXTURE0),be.pixelStorei(O.UNPACK_FLIP_Y_WEBGL,k.flipY),be.pixelStorei(O.UNPACK_PREMULTIPLY_ALPHA_WEBGL,k.premultiplyAlpha),be.pixelStorei(O.UNPACK_ALIGNMENT,k.unpackAlignment);const fi=be.getParameter(O.UNPACK_ROW_LENGTH),vt=be.getParameter(O.UNPACK_IMAGE_HEIGHT),bi=be.getParameter(O.UNPACK_SKIP_PIXELS),ji=be.getParameter(O.UNPACK_SKIP_ROWS),Ys=be.getParameter(O.UNPACK_SKIP_IMAGES);be.pixelStorei(O.UNPACK_ROW_LENGTH,on.width),be.pixelStorei(O.UNPACK_IMAGE_HEIGHT,on.height),be.pixelStorei(O.UNPACK_SKIP_PIXELS,He),be.pixelStorei(O.UNPACK_SKIP_ROWS,st),be.pixelStorei(O.UNPACK_SKIP_IMAGES,ct);const Mo=M.isDataArrayTexture||M.isData3DTexture,zt=k.isDataArrayTexture||k.isData3DTexture;if(M.isDepthTexture){const un=w.get(M),Ks=w.get(k),qt=w.get(un.__renderTarget),Zs=w.get(Ks.__renderTarget);be.bindFramebuffer(O.READ_FRAMEBUFFER,qt.__webglFramebuffer),be.bindFramebuffer(O.DRAW_FRAMEBUFFER,Zs.__webglFramebuffer);for(let Eo=0;Eo0){const i=Bs[0].object;ea.setFromNormalAndCoplanarPoint(e.getWorldDirection(ea.normal),af.setFromMatrixPosition(i.matrixWorld)),ss!==i&&ss!==null&&(this.dispatchEvent({type:"hoveroff",object:ss}),t.style.cursor="auto",ss=null),ss!==i&&(this.dispatchEvent({type:"hoveron",object:i}),t.style.cursor="pointer",ss=i)}else ss!==null&&(this.dispatchEvent({type:"hoveroff",object:ss}),t.style.cursor="auto",ss=null);Tu.copy(Is)}}function VR(r){const e=this.object,t=this.domElement,n=this.raycaster;this.enabled!==!1&&(this._updatePointer(r),this._updateState(r),Bs.length=0,n.setFromCamera(Is,e),n.intersectObjects(this.objects,this.recursive,Bs),Bs.length>0&&(this.transformGroup===!0?Hn=t0(Bs[0].object):Hn=Bs[0].object,ea.setFromNormalAndCoplanarPoint(e.getWorldDirection(ea.normal),af.setFromMatrixPosition(Hn.matrixWorld)),n.ray.intersectPlane(ea,Iu)&&(this.state===Tr.PAN?(Qx.copy(Hn.parent.matrixWorld).invert(),Zx.copy(Iu).sub(af.setFromMatrixPosition(Hn.matrixWorld)),t.style.cursor="move",this.dispatchEvent({type:"dragstart",object:Hn})):this.state===Tr.ROTATE&&(Jx.set(0,1,0).applyQuaternion(e.quaternion).normalize(),e0.set(1,0,0).applyQuaternion(e.quaternion).normalize(),t.style.cursor="move",this.dispatchEvent({type:"dragstart",object:Hn})))),Tu.copy(Is))}function zR(){this.enabled!==!1&&(Hn&&(this.dispatchEvent({type:"dragend",object:Hn}),Hn=null),this.domElement.style.cursor=ss?"pointer":"auto",this.state=Tr.NONE)}function HR(r){this.enabled!==!1&&r.preventDefault()}function t0(r,e=null){return r.isGroup&&(e=r),r.parent===null?e:t0(r.parent,e)}function lf(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,n=Array(e);t1&&arguments[1]!==void 0?arguments[1]:{},s=i.dataBindAttr,o=s===void 0?"__data":s,a=i.objBindAttr,l=a===void 0?"__threeObj":a;return s0(this,e),n=i0(this,e),nh(n,"scene",void 0),dg(n,id,void 0),dg(n,Wc,void 0),n.scene=t,fg(id,n,o),fg(Wc,n,l),n.onRemoveObj(function(){}),n}return a0(e,r),o0(e,[{key:"onCreateObj",value:function(n){var i=this;return nd(e,"onCreateObj",this)([function(s){var o=n(s);return s[td(Wc,i)]=o,o[td(id,i)]=s,i.scene.add(o),o}]),this}},{key:"onRemoveObj",value:function(n){var i=this;return nd(e,"onRemoveObj",this)([function(s,o){var a=nd(e,"getData",i)([s]);n(s,o),i.scene.remove(s),vp(s),delete a[td(Wc,i)]}]),this}}])}(Pv),rl=function(e){return isNaN(e)?parseInt(lx(e).toHex(),16):e},sd=function(e){return isNaN(e)?lx(e).getAlpha():1},iw=Dv(Lv);function gg(r,e,t){!e||typeof t!="string"||r.filter(function(n){return!n[t]}).forEach(function(n){n[t]=iw(e(n))})}function sw(r,e){var t=r.nodes,n=r.links,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},s=i.nodeFilter,o=s===void 0?function(){return!0}:s,a=i.onLoopError,l=a===void 0?function(f){throw"Invalid DAG structure! Found cycle in node path: ".concat(f.join(" -> "),".")}:a,c={};t.forEach(function(f){return c[e(f)]={data:f,out:[],depth:-1,skip:!o(f)}}),n.forEach(function(f){var p=f.source,g=f.target,m=S(p),_=S(g);if(!c.hasOwnProperty(m))throw"Missing source node with id: ".concat(m);if(!c.hasOwnProperty(_))throw"Missing target node with id: ".concat(_);var x=c[m],v=c[_];x.out.push(v);function S(E){return hf(E)==="object"?e(E):E}});var u=[];d(Object.values(c));var h=Object.assign.apply(Object,[{}].concat(zi(Object.entries(c).filter(function(f){var p=El(f,2),g=p[1];return!g.skip}).map(function(f){var p=El(f,2),g=p[0],m=p[1];return nh({},g,m.depth)}))));return h;function d(f){for(var p=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[],g=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,m=function(){var S=f[_];if(p.indexOf(S)!==-1){var E=[].concat(zi(p.slice(p.indexOf(S))),[S]).map(function(T){return e(T.data)});return u.some(function(T){return T.length===E.length&&T.every(function(A,y){return A===E[y]})})||(u.push(E),l(E)),1}g>S.depth&&(S.depth=g,d(S.out,[].concat(zi(p),[S]),g+(S.skip?0:1)))},_=0,x=f.length;_2?-60:-30),e<3&&i(t.graphData.nodes,"z"),e<2&&i(t.graphData.nodes,"y");function i(s,o){s.forEach(function(a){delete a[o],delete a["v".concat(o)]})}}},dagMode:{onChange:function(e,t){!e&&t.forceEngine==="d3"&&(t.graphData.nodes||[]).forEach(function(n){return n.fx=n.fy=n.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 n===void 0?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=e.forceEngine!=="ngraph";return e.engineRunning&&n(),i(),s(),this;function n(){++e.cntTicks>e.cooldownTicks||new Date-e.startTickTime>e.cooldownTime||t&&e.d3AlphaMin>0&&e.d3ForceLayout.alpha()0){var T=g.x-p.x,A=g.y-p.y||0,y=new Ye.Vector3().subVectors(x,_),R=y.clone().multiplyScalar(m).cross(T!==0||A!==0?new Ye.Vector3(0,0,1):new Ye.Vector3(0,1,0)).applyAxisAngle(y.normalize(),E).add(new Ye.Vector3().addVectors(_,x).divideScalar(2));S=new Ye.QuadraticBezierCurve3(_,R,x)}else{var P=m*70,N=-E,U=N+Math.PI/2;S=new Ye.CubicBezierCurve3(_,new Ye.Vector3(P*Math.cos(U),P*Math.sin(U),0).add(_),new Ye.Vector3(P*Math.cos(N),P*Math.sin(N),0).add(_),x)}d.__curve=S}}}}function i(){var o=gt(e.linkDirectionalArrowRelPos),a=gt(e.linkDirectionalArrowLength),l=gt(e.nodeVal);e.arrowDataMapper.entries().forEach(function(c){var u=El(c,2),h=u[0],d=u[1];if(d){var f=t?h:e.layout.getLinkPosition(e.layout.graph.getLink(h.source,h.target).id),p=f[t?"source":"from"],g=f[t?"target":"to"];if(!(!p||!g||!p.hasOwnProperty("x")||!g.hasOwnProperty("x"))){var m=Math.cbrt(Math.max(0,l(p)||1))*e.nodeRelSize,_=Math.cbrt(Math.max(0,l(g)||1))*e.nodeRelSize,x=a(h),v=o(h),S=h.__curve?function(P){return h.__curve.getPoint(P)}:function(P){var N=function(G,V,L,B){return V[G]+(L[G]-V[G])*B||0};return{x:N("x",p,g,P),y:N("y",p,g,P),z:N("z",p,g,P)}},E=h.__curve?h.__curve.getLength():Math.sqrt(["x","y","z"].map(function(P){return Math.pow((g[P]||0)-(p[P]||0),2)}).reduce(function(P,N){return P+N},0)),T=m+x+(E-m-_-x)*v,A=S(T/E),y=S((T-x)/E);["x","y","z"].forEach(function(P){return d.position[P]=y[P]});var R=r0(Ye.Vector3,zi(["x","y","z"].map(function(P){return A[P]})));d.parent.localToWorld(R),d.lookAt(R)}}})}function s(){var o=gt(e.linkDirectionalParticleSpeed),a=gt(e.linkDirectionalParticleOffset);e.graphData.links.forEach(function(l){var c=e.particlesDataMapper.getObj(l),u=c&&c.children,h=l.__singleHopPhotonsObj&&l.__singleHopPhotonsObj.children;if(!((!h||!h.length)&&(!u||!u.length))){var d=t?l:e.layout.getLinkPosition(e.layout.graph.getLink(l.source,l.target).id),f=d[t?"source":"from"],p=d[t?"target":"to"];if(!(!f||!p||!f.hasOwnProperty("x")||!p.hasOwnProperty("x"))){var g=o(l),m=Math.abs(a(l)),_=l.__curve?function(v){return l.__curve.getPoint(v)}:function(v){var S=function(T,A,y,R){return A[T]+(y[T]-A[T])*R||0};return{x:S("x",f,p,v),y:S("y",f,p,v),z:S("z",f,p,v)}},x=[].concat(zi(u||[]),zi(h||[]));x.forEach(function(v,S){var E=v.parent.__linkThreeObjType==="singleHopPhotons";if(v.hasOwnProperty("__progressRatio")||(v.__progressRatio=E?g<0?1:0:(S+m)/u.length),v.__progressRatio+=g,v.__progressRatio>=1||v.__progressRatio<0)if(!E)v.__progressRatio=v.__progressRatio%1,v.__progressRatio<0&&v.__progressRatio++;else{v.parent.remove(v),mg(v);return}var T=v.__progressRatio,A=_(T);v.geometry.type!=="SphereGeometry"&&v.lookAt(A.x,A.y,A.z),["x","y","z"].forEach(function(y){return v.position[y]=A[y]})})}}})}},emitParticle:function(e,t){if(t&&e.graphData.links.includes(t)){if(!t.__singleHopPhotonsObj){var n=new Ye.Group;n.__linkThreeObjType="singleHopPhotons",t.__singleHopPhotonsObj=n,e.graphScene.add(n)}var i=gt(e.linkDirectionalParticleThreeObject)(t);if(i&&e.linkDirectionalParticleThreeObject===i&&(i=i.clone()),!i){var s=gt(e.linkDirectionalParticleWidth),o=Math.ceil(s(t)*10)/10/2,a=e.linkDirectionalParticleResolution,l=new Ye.SphereGeometry(o,a,a),c=gt(e.linkColor),u=gt(e.linkDirectionalParticleColor),h=u(t)||c(t)||"#f0f0f0",d=new Ye.Color(rl(h)),f=e.linkOpacity*3,p=new Ye.MeshLambertMaterial({color:d,transparent:!0,opacity:f});i=new Ye.Mesh(l,p)}t.__singleHopPhotonsObj.add(i)}return this},getGraphBbox:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:function(){return!0};if(!e.initialised)return null;var n=function i(s){var o=[];if(s.geometry){s.geometry.computeBoundingBox();var a=new Ye.Box3;a.copy(s.geometry.boundingBox).applyMatrix4(s.matrixWorld),o.push(a)}return o.concat.apply(o,zi((s.children||[]).filter(function(l){return!l.hasOwnProperty("__graphObjType")||l.__graphObjType==="node"&&t(l.__data)}).map(i)))}(e.graphScene);return n.length?Object.assign.apply(Object,zi(["x","y","z"].map(function(i){return nh({},i,[kv(n,function(s){return s.min[i]}),Gv(n,function(s){return s.max[i]})])}))):null}},stateInit:function(){return{d3ForceLayout:Fv().force("link",Iv()).force("charge",Bv()).force("center",Ov()).force("dagRadial",null).stop(),engineRunning:!1}},init:function(e,t){t.graphScene=e,t.nodeDataMapper=new sl(e,{objBindAttr:"__threeObj"}),t.linkDataMapper=new sl(e,{objBindAttr:"__lineObj"}),t.arrowDataMapper=new sl(e,{objBindAttr:"__arrowObj"}),t.particlesDataMapper=new sl(e,{objBindAttr:"__photonsObj"})},update:function(e,t){var n=function(W){return W.some(function(se){return t.hasOwnProperty(se)})};if(e.engineRunning=!1,typeof e.onUpdate=="function"&&e.onUpdate(),e.nodeAutoColorBy!==null&&n(["nodeAutoColorBy","graphData","nodeColor"])&&gg(e.graphData.nodes,gt(e.nodeAutoColorBy),e.nodeColor),e.linkAutoColorBy!==null&&n(["linkAutoColorBy","graphData","linkColor"])&&gg(e.graphData.links,gt(e.linkAutoColorBy),e.linkColor),e._flushObjects||n(["graphData","nodeThreeObject","nodeThreeObjectExtend","nodeVal","nodeColor","nodeVisibility","nodeRelSize","nodeResolution","nodeOpacity"])){var i=gt(e.nodeThreeObject),s=gt(e.nodeThreeObjectExtend),o=gt(e.nodeVal),a=gt(e.nodeColor),l=gt(e.nodeVisibility),c={},u={};(e._flushObjects||n(["nodeThreeObject","nodeThreeObjectExtend"]))&&e.nodeDataMapper.clear(),e.nodeDataMapper.onCreateObj(function(oe){var W=i(oe),se=s(oe);W&&e.nodeThreeObject===W&&(W=W.clone());var le;return W&&!se?le=W:(le=new Ye.Mesh,le.__graphDefaultObj=!0,W&&se&&le.add(W)),le.__graphObjType="node",le}).onUpdateObj(function(oe,W){if(oe.__graphDefaultObj){var se=o(W)||1,le=Math.cbrt(se)*e.nodeRelSize,Ne=e.nodeResolution;(!oe.geometry.type.match(/^Sphere(Buffer)?Geometry$/)||oe.geometry.parameters.radius!==le||oe.geometry.parameters.widthSegments!==Ne)&&(c.hasOwnProperty(se)||(c[se]=new Ye.SphereGeometry(le,Ne,Ne)),oe.geometry.dispose(),oe.geometry=c[se]);var Le=a(W),we=new Ye.Color(rl(Le||"#ffffaa")),xt=e.nodeOpacity*sd(Le);(oe.material.type!=="MeshLambertMaterial"||!oe.material.color.equals(we)||oe.material.opacity!==xt)&&(u.hasOwnProperty(Le)||(u[Le]=new Ye.MeshLambertMaterial({color:we,transparent:!0,opacity:xt})),oe.material.dispose(),oe.material=u[Le])}}).digest(e.graphData.nodes.filter(l))}if(e._flushObjects||n(["graphData","linkThreeObject","linkThreeObjectExtend","linkMaterial","linkColor","linkWidth","linkVisibility","linkResolution","linkOpacity","linkDirectionalArrowLength","linkDirectionalArrowColor","linkDirectionalArrowResolution","linkDirectionalParticles","linkDirectionalParticleWidth","linkDirectionalParticleColor","linkDirectionalParticleResolution","linkDirectionalParticleThreeObject"])){var h=gt(e.linkThreeObject),d=gt(e.linkThreeObjectExtend),f=gt(e.linkMaterial),p=gt(e.linkVisibility),g=gt(e.linkColor),m=gt(e.linkWidth),_={},x={},v={},S=e.graphData.links.filter(p);if((e._flushObjects||n(["linkThreeObject","linkThreeObjectExtend","linkWidth"]))&&e.linkDataMapper.clear(),e.linkDataMapper.onRemoveObj(function(oe){var W=oe.__data&&oe.__data.__singleHopPhotonsObj;W&&(W.parent.remove(W),mg(W),delete oe.__data.__singleHopPhotonsObj)}).onCreateObj(function(oe){var W=h(oe),se=d(oe);W&&e.linkThreeObject===W&&(W=W.clone());var le;if(!W||se){var Ne=!!m(oe);if(Ne)le=new Ye.Mesh;else{var Le=new Ye.BufferGeometry;Le[rd]("position",new Ye.BufferAttribute(new Float32Array(2*3),3)),le=new Ye.Line(Le)}}var we;return W?se?(we=new Ye.Group,we.__graphDefaultObj=!0,we.add(le),we.add(W)):we=W:(we=le,we.__graphDefaultObj=!0),we.renderOrder=10,we.__graphObjType="link",we}).onUpdateObj(function(oe,W){if(oe.__graphDefaultObj){var se=oe.children.length?oe.children[0]:oe,le=Math.ceil(m(W)*10)/10,Ne=!!le;if(Ne){var Le=le/2,we=e.linkResolution;if(!se.geometry.type.match(/^Cylinder(Buffer)?Geometry$/)||se.geometry.parameters.radiusTop!==Le||se.geometry.parameters.radialSegments!==we){if(!_.hasOwnProperty(le)){var xt=new Ye.CylinderGeometry(Le,Le,1,we,1,!1);xt[$c](new Ye.Matrix4().makeTranslation(0,1/2,0)),xt[$c](new Ye.Matrix4().makeRotationX(Math.PI/2)),_[le]=xt}se.geometry.dispose(),se.geometry=_[le]}}var Qe=f(W);if(Qe)se.material=Qe;else{var ft=g(W),Et=new Ye.Color(rl(ft||"#f0f0f0")),Je=e.linkOpacity*sd(ft),It=Ne?"MeshLambertMaterial":"LineBasicMaterial";if(se.material.type!==It||!se.material.color.equals(Et)||se.material.opacity!==Je){var Dt=Ne?x:v;Dt.hasOwnProperty(ft)||(Dt[ft]=new Ye[It]({color:Et,transparent:Je<1,opacity:Je,depthWrite:Je>=1})),se.material.dispose(),se.material=Dt[ft]}}}}).digest(S),e.linkDirectionalArrowLength||t.hasOwnProperty("linkDirectionalArrowLength")){var E=gt(e.linkDirectionalArrowLength),T=gt(e.linkDirectionalArrowColor);e.arrowDataMapper.onCreateObj(function(){var oe=new Ye.Mesh(void 0,new Ye.MeshLambertMaterial({transparent:!0}));return oe.__linkThreeObjType="arrow",oe}).onUpdateObj(function(oe,W){var se=E(W),le=e.linkDirectionalArrowResolution;if(!oe.geometry.type.match(/^Cone(Buffer)?Geometry$/)||oe.geometry.parameters.height!==se||oe.geometry.parameters.radialSegments!==le){var Ne=new Ye.ConeGeometry(se*.25,se,le);Ne.translate(0,se/2,0),Ne.rotateX(Math.PI/2),oe.geometry.dispose(),oe.geometry=Ne}var Le=T(W)||g(W)||"#f0f0f0";oe.material.color=new Ye.Color(rl(Le)),oe.material.opacity=e.linkOpacity*3*sd(Le)}).digest(S.filter(E))}if(e.linkDirectionalParticles||t.hasOwnProperty("linkDirectionalParticles")){var A=gt(e.linkDirectionalParticles),y=gt(e.linkDirectionalParticleWidth),R=gt(e.linkDirectionalParticleColor),P=gt(e.linkDirectionalParticleThreeObject),N={},U={};e.particlesDataMapper.onCreateObj(function(){var oe=new Ye.Group;return oe.__linkThreeObjType="photons",oe.__photonDataMapper=new sl(oe),oe}).onUpdateObj(function(oe,W){var se=!!oe.children.length&&oe.children[0],le=P(W),Ne,Le;if(le)Ne=le.geometry,Le=le.material;else{var we=Math.ceil(y(W)*10)/10/2,xt=e.linkDirectionalParticleResolution;se&&se.geometry.parameters.radius===we&&se.geometry.parameters.widthSegments===xt?Ne=se.geometry:(U.hasOwnProperty(we)||(U[we]=new Ye.SphereGeometry(we,xt,xt)),Ne=U[we]);var Qe=R(W)||g(W)||"#f0f0f0",ft=new Ye.Color(rl(Qe)),Et=e.linkOpacity*3;se&&se.material.color.equals(ft)&&se.material.opacity===Et?Le=se.material:(N.hasOwnProperty(Qe)||(N[Qe]=new Ye.MeshLambertMaterial({color:ft,transparent:!0,opacity:Et})),Le=N[Qe])}se&&(se.geometry!==Ne&&se.geometry.dispose(),se.material!==Le&&se.material.dispose());var Je=Math.round(Math.abs(A(W)));oe.__photonDataMapper.id(function(It){return It.idx}).onCreateObj(function(){return new Ye.Mesh(Ne,Le)}).onUpdateObj(function(It){It.geometry=Ne,It.material=Le}).digest(zi(new Array(Je)).map(function(It,Dt){return{idx:Dt}}))}).digest(S.filter(A))}}if(e._flushObjects=!1,n(["graphData","nodeId","linkSource","linkTarget","numDimensions","forceEngine","dagMode","dagNodeFilter","dagLevelDistance"])){e.engineRunning=!1,e.graphData.links.forEach(function(oe){oe.source=oe[e.linkSource],oe.target=oe[e.linkTarget]});var G=e.forceEngine!=="ngraph",V;if(G){(V=e.d3ForceLayout).stop().alpha(1).numDimensions(e.numDimensions).nodes(e.graphData.nodes);var L=e.d3ForceLayout.force("link");L&&L.id(function(oe){return oe[e.nodeId]}).links(e.graphData.links);var B=e.dagMode&&sw(e.graphData,function(oe){return oe[e.nodeId]},{nodeFilter:e.dagNodeFilter,onLoopError:e.onDagError||void 0}),H=Math.max.apply(Math,zi(Object.values(B||[]))),ie=e.dagLevelDistance||e.graphData.nodes.length/(H||1)*rw*(["radialin","radialout"].indexOf(e.dagMode)!==-1?.7:1);if(["lr","rl","td","bu","zin","zout"].includes(t.dagMode)){var ce=["lr","rl"].includes(t.dagMode)?"fx":["td","bu"].includes(t.dagMode)?"fy":"fz";e.graphData.nodes.filter(e.dagNodeFilter).forEach(function(oe){return delete oe[ce]})}if(["lr","rl","td","bu","zin","zout"].includes(e.dagMode)){var ve=["rl","td","zout"].includes(e.dagMode),Ce=function(W){return(B[W[e.nodeId]]-H/2)*ie*(ve?-1:1)},ke=["lr","rl"].includes(e.dagMode)?"fx":["td","bu"].includes(e.dagMode)?"fy":"fz";e.graphData.nodes.filter(e.dagNodeFilter).forEach(function(oe){return oe[ke]=Ce(oe)})}e.d3ForceLayout.force("dagRadial",["radialin","radialout"].indexOf(e.dagMode)!==-1?Uv(function(oe){var W=B[oe[e.nodeId]]||-1;return(e.dagMode==="radialin"?H-W:W)*ie}).strength(function(oe){return e.dagNodeFilter(oe)?1:0}):null)}else{var ut=_g.graph();e.graphData.nodes.forEach(function(oe){ut.addNode(oe[e.nodeId])}),e.graphData.links.forEach(function(oe){ut.addLink(oe.source,oe.target)}),V=_g.forcelayout(ut,JR({dimensions:e.numDimensions},e.ngraphPhysics)),V.graph=ut}for(var Mt=0;Mt0&&e.d3ForceLayout.alpha()1&&arguments[1]!==void 0?arguments[1]:Object,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,n=function(i){function s(){var o;s0(this,s);for(var a=arguments.length,l=new Array(a),c=0;c0){const{width:s,height:o}=e.context;t.bufferWidth=s,t.bufferHeight=o}t.lights=this.getLightsData(e.lightsNode.getLights()),this.renderObjects.set(e,t)}return t}getAttributesData(e){const t={};for(const n in e){const i=e[n];t[n]={id:i.id,version:i.version}}return t}containsNode(e){const t=e.material;for(const n in t)if(t[n]&&t[n].isNode)return!0;return!!(e.context.modelViewMatrix||e.context.modelNormalViewMatrix||e.context.getAO||e.context.getShadow)}getGeometryData(e){let t=yg.get(e);return t===void 0&&(t={_renderId:-1,_equal:!1,attributes:this.getAttributesData(e.attributes),indexId:e.index?e.index.id:null,indexVersion:e.index?e.index.version:null,drawRange:{start:e.drawRange.start,count:e.drawRange.count}},yg.set(e,t)),t}getMaterialData(e){let t=xg.get(e);if(t===void 0){t={_renderId:-1,_equal:!1};for(const n of this.refreshUniforms){const i=e[n];i!=null&&(typeof i=="object"&&i.clone!==void 0?i.isTexture===!0?t[n]={id:i.id,version:i.version}:t[n]=i.clone():t[n]=i)}xg.set(e,t)}return t}equals(e,t,n){const{object:i,material:s,geometry:o}=e,a=this.getRenderObjectData(e);if(a.worldMatrix.equals(i.matrixWorld)!==!0)return a.worldMatrix.copy(i.matrixWorld),!1;const l=this.getMaterialData(e.material);if(l._renderId!==n){l._renderId=n;for(const u in l){const h=l[u],d=s[u];if(u!=="_renderId"&&u!=="_equal"){if(h.equals!==void 0){if(h.equals(d)===!1)return h.copy(d),l._equal=!1,!1}else if(d.isTexture===!0){if(h.id!==d.id||h.version!==d.version)return h.id=d.id,h.version=d.version,l._equal=!1,!1}else if(h!==d)return l[u]=d,l._equal=!1,!1}}if(l.transmission>0){const{width:u,height:h}=e.context;if(a.bufferWidth!==u||a.bufferHeight!==h)return a.bufferWidth=u,a.bufferHeight=h,l._equal=!1,!1}l._equal=!0}else if(l._equal===!1)return!1;if(a.geometryId!==o.id)return a.geometryId=o.id,!1;const c=this.getGeometryData(e.geometry);if(c._renderId!==n){c._renderId=n;const u=o.attributes,h=c.attributes;let d=0,f=0;for(const v in u)d++;for(const v in h){f++;const S=h[v],E=u[v];if(E===void 0)return delete h[v],c._equal=!1,!1;if(S.id!==E.id||S.version!==E.version)return S.id=E.id,S.version=E.version,c._equal=!1,!1}if(f!==d)return c.attributes=this.getAttributesData(u),c._equal=!1,!1;const p=o.index,g=c.indexId,m=c.indexVersion,_=p?p.id:null,x=p?p.version:null;if(g!==_||m!==x)return c.indexId=_,c.indexVersion=x,c._equal=!1,!1;if(c.drawRange.start!==o.drawRange.start||c.drawRange.count!==o.drawRange.count)return c.drawRange.start=o.drawRange.start,c.drawRange.count=o.drawRange.count,c._equal=!1,!1;c._equal=!0}else if(c._equal===!1)return!1;if(a.morphTargetInfluences){let u=!1;for(let h=0;h{const n=t.match(e);if(!n)return null;const i=n[1]||n[2]||"",s=n[3].split("?")[0],o=parseInt(n[4],10),a=parseInt(n[5],10),l=s.split("/").pop();return{fn:i,file:l,line:o,column:a}}).filter(t=>t&&!hw.some(n=>n.test(t.file)))}class jn{constructor(e=null){this.isStackTrace=!0,this.stack=dw(e||new Error().stack)}getLocation(){if(this.stack.length===0)return"[Unknown location]";const e=this.stack[0],t=e.fn;return`${t?`"${t}()" at `:""}"${e.file}:${e.line}"`}getError(e){if(this.stack.length===0)return e;const t=this.stack.map(n=>{const i=`${n.file}:${n.line}:${n.column}`;return n.fn?` at ${n.fn} (${i})`:` at ${i}`}).join(` `);return`${e} ${t}`}}function Sp(r,e=0){let t=3735928559^e,n=1103547991^e;if(Array.isArray(r))for(let i=0,s;i>>16,2246822507),t^=Math.imul(n^n>>>13,3266489909),n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(t^t>>>13,3266489909),4294967296*(2097151&n)+(t>>>0)}const Ha=r=>Sp(r),dc=r=>Sp(r),Al=(...r)=>Sp(r),fw=new Map([[1,"float"],[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),vg=new WeakMap;function d0(r){return fw.get(r)}function Bu(r){if(r==null)return null;const e=typeof r;return r.isNode===!0?"node":e==="number"?"float":e==="boolean"?"bool":e==="string"?"string":e==="function"?"shader":r.isVector2===!0?"vec2":r.isVector3===!0?"vec3":r.isVector4===!0?"vec4":r.isMatrix2===!0?"mat2":r.isMatrix3===!0?"mat3":r.isMatrix4===!0?"mat4":r.isColor===!0?"color":r instanceof ArrayBuffer?"ArrayBuffer":null}function bp(r,...e){const t=r?r.slice(-4):void 0;return e.length===1&&(t==="vec2"?e=[e[0],e[0]]:t==="vec3"?e=[e[0],e[0],e[0]]:t==="vec4"&&(e=[e[0],e[0],e[0],e[0]])),r==="color"?new Ve(...e):t==="vec2"?new de(...e):t==="vec3"?new C(...e):t==="vec4"?new tt(...e):t==="mat2"?new Fu(...e):t==="mat3"?new Ke(...e):t==="mat4"?new dt(...e):r==="bool"?e[0]||!1:r==="float"||r==="int"||r==="uint"?e[0]||0:r==="string"?e[0]||"":r==="ArrayBuffer"?mw(e[0]):null}function f0(r){let e=vg.get(r);return e===void 0&&(e={},vg.set(r,e)),e}function pw(r){let e="";const t=new Uint8Array(r);for(let n=0;ne.charCodeAt(0)).buffer}const Xc={VERTEX:"vertex"},je={NONE:"none",FRAME:"frame",RENDER:"render",OBJECT:"object"},Ni={READ_ONLY:"readOnly",WRITE_ONLY:"writeOnly",READ_WRITE:"readWrite"},gw=["fragment","vertex"],ad=["setup","analyze","generate"],ld=[...gw,"compute"],Wa=["x","y","z","w"],_w={analyze:"setup",generate:"analyze"};let xw=0;class Oe extends Ii{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=je.NONE,this.updateBeforeType=je.NONE,this.updateAfterType=je.NONE,this.version=0,this.name="",this.global=!1,this.parents=!1,this.isNode=!0,this._beforeNodes=null,this._cacheKey=null,this._uuid=null,this._cacheKeyVersion=0,this.id=xw++,this.stackTrace=null,Oe.captureStackTrace===!0&&(this.stackTrace=new jn)}set needsUpdate(e){e===!0&&this.version++}get uuid(){return this._uuid===null&&(this._uuid=Du.generateUUID()),this._uuid}get type(){return this.constructor.type}onUpdate(e,t){return this.updateType=t,this.update=e.bind(this),this}onFrameUpdate(e){return this.onUpdate(e,je.FRAME)}onRenderUpdate(e){return this.onUpdate(e,je.RENDER)}onObjectUpdate(e){return this.onUpdate(e,je.OBJECT)}onReference(e){return this.updateReference=e.bind(this),this}updateReference(){return this}isGlobal(){return this.global}*getChildren(){for(const{childNode:e}of this._getChildren())yield e}dispose(){this.dispatchEvent({type:"dispose"})}traverse(e){e(this);for(const t of this.getChildren())t.traverse(e)}_getChildren(e=new Set){const t=[];e.add(this);for(const n of Object.getOwnPropertyNames(this)){const i=this[n];if(!(n.startsWith("_")===!0||e.has(i))){if(Array.isArray(i)===!0)for(let s=0;s0&&(e.inputNodes=n)}deserialize(e){if(e.inputNodes!==void 0){const t=e.meta.nodes;for(const n in e.inputNodes)if(Array.isArray(e.inputNodes[n])){const i=[];for(const s of e.inputNodes[n])i.push(t[s]);this[n]=i}else if(typeof e.inputNodes[n]=="object"){const i={};for(const s in e.inputNodes[n]){const o=e.inputNodes[n][s];i[s]=t[o]}this[n]=i}else{const i=e.inputNodes[n];this[n]=t[i]}}}toJSON(e){const{uuid:t,type:n}=this,i=e===void 0||typeof e=="string";i&&(e={textures:{},images:{},nodes:{}});let s=e.nodes[t];s===void 0&&(s={uuid:t,type:n,meta:e,metadata:{version:4.7,type:"Node",generator:"Node.toJSON"}},i!==!0&&(e.nodes[s.uuid]=s),this.serialize(s),delete s.meta);function o(a){const l=[];for(const c in a){const u=a[c];delete u.metadata,l.push(u)}return l}if(i){const a=o(e.textures),l=o(e.images),c=o(e.nodes);a.length>0&&(s.textures=a),l.length>0&&(s.images=l),c.length>0&&(s.nodes=c)}return s}}Oe.captureStackTrace=!1;class $a extends Oe{static get type(){return"ArrayElementNode"}constructor(e,t){super(),this.node=e,this.indexNode=t,this.isArrayElementNode=!0}generateNodeType(e){return this.node.getElementType(e)}getMemberType(e,t){return this.node.getMemberType(e,t)}generate(e){const t=this.indexNode.getNodeType(e),n=this.node.build(e),i=this.indexNode.build(e,!e.isVector(t)&&e.isInteger(t)?t:"uint");return`${n}[ ${i} ]`}}class p0 extends Oe{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}generateNodeType(e){const t=this.node.getNodeType(e);let n=null;for(const i of this.convertTo.split("|"))(n===null||e.getTypeLength(t)===e.getTypeLength(i))&&(n=i);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,i=this.getNodeType(e),s=n.build(e,i);return e.format(s,i,t)}}class _n extends Oe{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(e.getBuildStage()==="generate"){const i=e.getVectorType(this.getNodeType(e,t)),s=e.getDataFromNode(this);if(s.propertyName!==void 0)return e.format(s.propertyName,i,t);if(i!=="void"&&t!=="void"&&this.hasDependencies(e)){const o=super.build(e,i),a=e.getVarFromNode(this,null,i),l=e.getPropertyName(a);return e.addLineFlowCode(`${l} = ${o}`,this),s.snippet=o,s.propertyName=l,e.format(s.propertyName,i,t)}}return super.build(e,t)}}class yw extends _n{static get type(){return"JoinNode"}constructor(e=[],t=null){super(t),this.nodes=e}generateNodeType(e){return this.nodeType!==null?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),i=e.getTypeLength(n),s=this.nodes,o=e.getComponentType(n),a=[];let l=0;for(const u of s){if(l>=i){ne(`TSL: Length of parameters exceeds maximum length of function '${n}()' type.`,this.stackTrace);break}let h=u.getNodeType(e),d=e.getTypeLength(h),f;if(l+d>i&&(ne(`TSL: Length of '${n}()' data exceeds maximum length of output type.`,this.stackTrace),d=i-l,h=e.getTypeFromLength(d)),l+=d,f=u.build(e,h),e.getComponentType(h)!==o){const g=e.getTypeFromLength(d,o);f=e.format(f,h,g)}a.push(f)}const c=`${e.getType(n)}( ${a.join(", ")} )`;return e.format(c,n,t)}}const vw=Wa.join("");class Sw extends Oe{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(Wa.indexOf(t)+1,e);return e}getComponentType(e){return e.getComponentType(this.node.getNodeType(e))}generateNodeType(e){return e.getTypeFromLength(this.components.length,this.getComponentType(e))}getScope(){return this.node.getScope()}generate(e,t){const n=this.node,i=e.getTypeLength(n.getNodeType(e));let s=null;if(i>1){let o=null;this.getVectorLength()>=i&&(o=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));const l=n.build(e,o);this.components.length===i&&this.components===vw.slice(0,this.components.length)?s=e.format(l,o,t):s=e.format(`${l}.${this.components}`,this.getNodeType(e),t)}else s=n.build(e,t);return s}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}}class bw extends _n{static get type(){return"SetNode"}constructor(e,t,n){super(),this.sourceNode=e,this.components=t,this.targetNode=n}generateNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{sourceNode:t,components:n,targetNode:i}=this,s=this.getNodeType(e),o=e.getComponentType(i.getNodeType(e)),a=e.getTypeFromLength(n.length,o),l=i.build(e,a),c=t.build(e,s),u=e.getTypeLength(s),h=[];for(let d=0;dr.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"),bg=r=>Ew(r).split("").sort().join("");Oe.prototype.assign=function(...r){if(this.isStackNode!==!0)return lo!==null?lo.assign(this,...r):ne("TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().",new jn),this;{const e=df.get("assign");return this.addToStack(e(...r))}};Oe.prototype.toVarIntent=function(){return this};Oe.prototype.get=function(r){return new Mw(this,r)};const Rl={};function qc(r,e,t){Rl[r]=Rl[e]=Rl[t]={get(){this._cache=this._cache||{};let o=this._cache[r];return o===void 0&&(o=new Sw(this,r),this._cache[r]=o),o},set(o){this[r].assign(Be(o))}};const n=r.toUpperCase(),i=e.toUpperCase(),s=t.toUpperCase();Oe.prototype["set"+n]=Oe.prototype["set"+i]=Oe.prototype["set"+s]=function(o){const a=bg(r);return new bw(this,a,Be(o))},Oe.prototype["flip"+n]=Oe.prototype["flip"+i]=Oe.prototype["flip"+s]=function(){const o=bg(r);return new Tw(this,o)}}const Ji=["x","y","z","w"],es=["r","g","b","a"],ts=["s","t","p","q"];for(let r=0;r<4;r++){let e=Ji[r],t=es[r],n=ts[r];qc(e,t,n);for(let i=0;i<4;i++){e=Ji[r]+Ji[i],t=es[r]+es[i],n=ts[r]+ts[i],qc(e,t,n);for(let s=0;s<4;s++){e=Ji[r]+Ji[i]+Ji[s],t=es[r]+es[i]+es[s],n=ts[r]+ts[i]+ts[s],qc(e,t,n);for(let o=0;o<4;o++)e=Ji[r]+Ji[i]+Ji[s]+Ji[o],t=es[r]+es[i]+es[s]+es[o],n=ts[r]+ts[i]+ts[s]+ts[o],qc(e,t,n)}}}for(let r=0;r<32;r++)Rl[r]={get(){this._cache=this._cache||{};let e=this._cache[r];return e===void 0&&(e=new $a(this,new Ts(r,"uint")),this._cache[r]=e),e},set(e){this[r].assign(Be(e))}};Object.defineProperties(Oe.prototype,Rl);const Tg=new WeakMap,Aw=function(r,e=null){const t=Bu(r);return t==="node"?r:e===null&&(t==="float"||t==="boolean")||t&&t!=="shader"&&t!=="string"?Be(ff(r,e)):t==="shader"?r.isFn?r:Q(r):r},Rw=function(r,e=null){for(const t in r)r[t]=Be(r[t],e);return r},ww=function(r,e=null){const t=r.length;for(let n=0;nl?(ne(`TSL: "${h}" parameter length exceeds limit.`,new jn),u.slice(0,l)):u}return e===null?s=(...u)=>i(new r(...ta(c(u)))):t!==null?(t=Be(t),s=(...u)=>i(new r(e,...ta(c(u)),t))):s=(...u)=>i(new r(e,...ta(c(u)))),s.setParameterLength=(...u)=>(u.length===1?a=l=u[0]:u.length===2&&([a,l]=u),s),s.setName=u=>(o=u,s),s},Cw=function(r,...e){return new r(...ta(e))};class Nw extends Oe{constructor(e,t){super(),this.shaderNode=e,this.rawInputs=t,this.isShaderCallNodeInternal=!0}generateNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}getElementType(e){return this.getOutputNode(e).getElementType(e)}getMemberType(e,t){return this.getOutputNode(e).getMemberType(e,t)}call(e){const{shaderNode:t,rawInputs:n}=this,i=e.getNodeProperties(t),s=e.getClosestSubBuild(t.subBuilds)||"",o=s||"default";if(i[o])return i[o];const a=e.subBuildFn,l=e.fnCall;e.subBuildFn=s,e.fnCall=this;let c=null;if(t.layout){let u=Tg.get(e.constructor);u===void 0&&(u=new WeakMap,Tg.set(e.constructor,u));let h=u.get(t);h===void 0&&(h=Be(e.buildFunctionNode(t)),u.set(t,h)),e.addInclude(h);const d=n?Pw(n):null;c=Be(h.call(d))}else{const u=new Proxy(e,{get:(g,m,_)=>{let x;return Symbol.iterator===m?x=function*(){yield void 0}:x=Reflect.get(g,m,_),x}}),h=n?Dw(n):null,d=Array.isArray(n)?n.length>0:n!==null,f=t.jsFunc,p=d||f.length>1?f(h,u):f(u);c=Be(p)}return e.subBuildFn=a,e.fnCall=l,t.once&&(i[o]=c),c}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 i=e.getBuildStage(),s=e.getNodeProperties(this),o=e.getSubBuildOutput(this),a=this.getOutputNode(e),l=e.fnCall;if(e.fnCall=this,i==="setup"){const c=e.getSubBuildProperty("initialized",this);if(s[c]!==!0&&(s[c]=!0,s[o]=this.getOutputNode(e),s[o].build(e),this.shaderNode.subBuilds))for(const u of e.chaining){const h=e.getDataFromNode(u,"any");h.subBuilds=h.subBuilds||new Set;for(const d of this.shaderNode.subBuilds)h.subBuilds.add(d)}n=s[o]}else i==="analyze"?a.build(e,t):i==="generate"&&(n=a.build(e,t)||"");return e.fnCall=l,n}}function Pw(r){let e;return Rp(r),r[0]&&(r[0].isNode||Object.getPrototypeOf(r[0])!==Object.prototype)?e=[...r]:e=r[0],e}function Dw(r){let e=0;return Rp(r),new Proxy(r,{get:(t,n,i)=>{let s;if(n==="length")return s=r.length,s;if(Symbol.iterator===n)s=function*(){for(const o of r)yield Be(o)};else{if(r.length>0)if(Object.getPrototypeOf(r[0])===Object.prototype){const o=r[0];o[n]===void 0?s=o[e++]:s=Reflect.get(o,n,i)}else r[0]instanceof Oe&&(r[n]===void 0?s=r[e++]:s=Reflect.get(r,n,i));else s=Reflect.get(t,n,i);s=Be(s)}return s}})}class Lw extends Oe{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 Nw(this,e)}setup(){return this.call()}}const Uw=[!1,!0],Fw=[0,1,2,3],Iw=[-1,-2],g0=[.5,1.5,1/3,1e-6,1e6,Math.PI,Math.PI*2,1/Math.PI,2/Math.PI,1/(Math.PI*2),Math.PI/2],Mp=new Map;for(const r of Uw)Mp.set(r,new Ts(r));const Ep=new Map;for(const r of Fw)Ep.set(r,new Ts(r,"uint"));const Ap=new Map([...Ep].map(r=>new Ts(r.value,"int")));for(const r of Iw)Ap.set(r,new Ts(r,"int"));const ih=new Map([...Ap].map(r=>new Ts(r.value)));for(const r of g0)ih.set(r,new Ts(r));for(const r of g0)ih.set(-r,new Ts(-r));const sh={bool:Mp,uint:Ep,ints:Ap,float:ih},Mg=new Map([...Mp,...ih]),ff=(r,e)=>Mg.has(r)?Mg.get(r):r.isNode===!0?r:new Ts(r,e),xn=function(r,e=null){return(...t)=>{for(const i of t)if(i===void 0)return ne(`TSL: Invalid parameter for the type "${r}".`,new jn),new Ts(0,r);if((t.length===0||!["bool","float","int","uint"].includes(r)&&t.every(i=>{const s=typeof i;return s!=="object"&&s!=="function"}))&&(t=[bp(r,...t)]),t.length===1&&e!==null&&e.has(t[0]))return jc(e.get(t[0]));if(t.length===1){const i=ff(t[0],r);return i.nodeType===r?jc(i):jc(new p0(i,r))}const n=t.map(i=>ff(i));return jc(new yw(n,r))}};function pf(r){return r&&r.isNode&&r.traverse(e=>{e.isConstNode&&(r=e.value)}),!!r}const Bw=r=>r!=null?r.nodeType||r.convertTo||(typeof r=="string"?r:null):null;function xl(r,e){return new Lw(r,e)}const Be=(r,e=null)=>Aw(r,e),jc=(r,e=null)=>Be(r,e).toVarIntent(),Rp=(r,e=null)=>new Rw(r,e),ta=(r,e=null)=>new ww(r,e),Ft=(r,e=null,t=null,n=null)=>new m0(r,e,t,n),ge=(r,...e)=>new Cw(r,...e),Se=(r,e=null,t=null,n={})=>new m0(r,e,t,{...n,intent:!0});let Ow=0;class kw extends Oe{constructor(e,t=null){super();let n=null;t!==null&&(typeof t=="object"?n=t.return:(typeof t=="string"?n=t:ne("TSL: Invalid layout type.",new jn),t=null)),this.shaderNode=new xl(e,n),t!==null&&this.setLayout(t),this.isFn=!0}setLayout(e){const t=this.shaderNode.nodeType;if(typeof e.inputs!="object"){const n={name:"fn"+Ow++,type:t,inputs:[]};for(const i in e)i!=="return"&&n.inputs.push({name:i,type:e[i]});e=n}return this.shaderNode.setLayout(e),this}generateNodeType(e){return this.shaderNode.getNodeType(e)||"float"}call(...e){const t=this.shaderNode.call(e);return this.shaderNode.nodeType==="void"&&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 ne('TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".',this.stackTrace),e.generateConst(t)}}function Q(r,e=null){const t=new kw(r,e);return new Proxy(()=>{},{apply(n,i,s){return t.call(...s)},get(n,i,s){return Reflect.get(t,i,s)},set(n,i,s,o){return Reflect.set(t,i,s,o)}})}const Ou=r=>{lo=r},_0=()=>lo,Lt=(...r)=>lo.If(...r);function x0(r){return lo&&lo.addToStack(r),r}Y("toStack",x0);const Gw=new xn("color"),j=new xn("float",sh.float),Kt=new xn("int",sh.ints),ht=new xn("uint",sh.uint),rh=new xn("bool",sh.bool),Ie=new xn("vec2"),ls=new xn("ivec2"),y0=new xn("uvec2"),Vw=new xn("bvec2"),K=new xn("vec3"),v0=new xn("ivec3"),S0=new xn("uvec3"),zw=new xn("bvec3"),Ze=new xn("vec4"),b0=new xn("ivec4"),T0=new xn("uvec4"),Hw=new xn("bvec4"),wp=new xn("mat2"),Bn=new xn("mat3"),eo=new xn("mat4");Y("toColor",Gw);Y("toFloat",j);Y("toInt",Kt);Y("toUint",ht);Y("toBool",rh);Y("toVec2",Ie);Y("toIVec2",ls);Y("toUVec2",y0);Y("toBVec2",Vw);Y("toVec3",K);Y("toIVec3",v0);Y("toUVec3",S0);Y("toBVec3",zw);Y("toVec4",Ze);Y("toIVec4",b0);Y("toUVec4",T0);Y("toBVec4",Hw);Y("toMat2",wp);Y("toMat3",Bn);Y("toMat4",eo);const Ww=Ft($a).setParameterLength(2),$w=(r,e)=>new p0(Be(r),e);Y("element",Ww);Y("convert",$w);Y("append",r=>(ee("TSL: .append() has been renamed to .toStack().",new jn),x0(r)));class Tt extends Oe{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 Ha(this.type+":"+(this.name||"")+":"+(this.varying?"1":"0"))}getHash(e){return this.name||super.getHash(e)}generate(e){let t;return this.varying===!0?(t=e.getVaryingFromNode(this,this.name),t.needsInterpolation=!0):t=e.getVarFromNode(this,this.name),e.getPropertyName(t)}}const Mr=(r,e)=>new Tt(r,e),ku=(r,e)=>new Tt(r,e,!0),Ct=ge(Tt,"vec4","DiffuseColor"),$o=ge(Tt,"vec3","DiffuseContribution"),Eg=ge(Tt,"vec3","EmissiveColor"),Os=ge(Tt,"float","Roughness"),mr=ge(Tt,"float","Metalness"),mf=ge(Tt,"float","Clearcoat"),wl=ge(Tt,"float","ClearcoatRoughness"),Ei=ge(Tt,"vec3","Sheen"),jr=ge(Tt,"float","SheenRoughness"),Cp=ge(Tt,"float","Iridescence"),gf=ge(Tt,"float","IridescenceIOR"),_f=ge(Tt,"float","IridescenceThickness"),xf=ge(Tt,"float","AlphaT"),Xr=ge(Tt,"float","Anisotropy"),Mu=ge(Tt,"vec3","AnisotropyT"),na=ge(Tt,"vec3","AnisotropyB"),co=ge(Tt,"color","SpecularColor"),qo=ge(Tt,"color","SpecularColorBlended"),jo=ge(Tt,"float","SpecularF90"),yf=ge(Tt,"float","Shininess"),Cl=ge(Tt,"vec4","Output"),cd=ge(Tt,"float","dashSize"),Ag=ge(Tt,"float","gapSize"),Eu=ge(Tt,"float","IOR"),vf=ge(Tt,"float","Transmission"),M0=ge(Tt,"float","Thickness"),E0=ge(Tt,"float","AttenuationDistance"),A0=ge(Tt,"color","AttenuationColor"),R0=ge(Tt,"float","Dispersion");class w0 extends Oe{static get type(){return"UniformGroupNode"}constructor(e,t=!1,n=1,i=null){super("string"),this.name=e,this.shared=t,this.order=n,this.updateType=i,this.isUniformGroup=!0}update(){this.needsUpdate=!0}serialize(e){super.serialize(e),e.name=this.name,e.version=this.version,e.shared=this.shared}deserialize(e){super.deserialize(e),this.name=e.name,this.version=e.version,this.shared=e.shared}}const Xw=(r,e=1,t=null)=>new w0(r,!1,e,t),Np=(r,e=0,t=null)=>new w0(r,!0,e,t);je.FRAME;const qe=Np("render",0,je.RENDER),qw=Xw("object",1,je.OBJECT);class fc extends Tp{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=qw}setName(e){return this.name=e,this}label(e){return ee('TSL: "label()" has been deprecated. Use "setName()" instead.',new jn),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(n=>{const i=e(n,this);i!==void 0&&(this.value=i)},t)}getInputType(e){let t=super.getInputType(e);return t==="bool"&&(t="uint"),t}generate(e,t){const n=this.getNodeType(e),i=this.getUniformHash(e);let s=e.getNodeFromHash(i);s===void 0&&(e.setHashNode(this,i),s=this);const o=s.getInputType(e),a=e.getUniformFromNode(s,o,e.shaderStage,this.name||e.context.nodeName),l=e.getPropertyName(a);e.context.nodeName!==void 0&&delete e.context.nodeName;let c=l;if(n==="bool"){const u=e.getDataFromNode(this);let h=u.propertyName;if(h===void 0){const d=e.getVarFromNode(this,null,"bool");h=e.getPropertyName(d),u.propertyName=h,c=e.format(l,o,n),e.addLineFlowCode(`${h} = ${c}`,this)}c=h}return e.format(c,n,t)}}const We=(r,e)=>{const t=Bw(e||r);if(t===r&&(r=bp(t)),r&&r.isNode===!0){let n=r.value;r.traverse(i=>{i.isConstNode===!0&&(n=i.value)}),r=n}return new fc(r,t)};class Rg extends _n{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}generateNodeType(e){return this.nodeType===null?this.values[0].getNodeType(e):this.nodeType}getElementType(e){return this.getNodeType(e)}getMemberType(e,t){return this.nodeType===null?this.values[0].getMemberType(e,t):super.getMemberType(e,t)}generate(e){const t=this.getNodeType(e);return e.generateArray(t,this.count,this.values)}}const jw=(...r)=>{let e;if(r.length===1){const t=r[0];e=new Rg(null,t.length,t)}else{const t=r[0],n=r[1];e=new Rg(t,n)}return Be(e)};Y("toArray",(r,e)=>jw(Array(e).fill(r)));class Yw extends _n{static get type(){return"AssignNode"}constructor(e,t){super(),this.targetNode=e,this.sourceNode=t,this.isAssignNode=!0}hasDependencies(){return!1}generateNodeType(e,t){return t!=="void"?this.targetNode.getNodeType(e):"void"}needsSplitAssign(e){const{targetNode:t}=this;if(e.isAvailable("swizzleAssign")===!1&&t.isSplitNode&&t.components.length>1){const n=e.getTypeLength(t.node.getNodeType(e));return Wa.join("").slice(0,n)!==t.components}return!1}setup(e){const{targetNode:t,sourceNode:n}=this,i=t.getScope(),s=e.getDataFromNode(i);s.assign=!0;const o=e.getNodeProperties(this);o.sourceNode=n,o.targetNode=t.context({assign:!0})}generate(e,t){const{targetNode:n,sourceNode:i}=e.getNodeProperties(this),s=this.needsSplitAssign(e),o=n.build(e),a=n.getNodeType(e),l=i.build(e,a),c=i.getNodeType(e),u=e.getDataFromNode(this);let h;if(u.initialized===!0)t!=="void"&&(h=o);else if(s){const d=e.getVarFromNode(this,null,a),f=e.getPropertyName(d);e.addLineFlowCode(`${f} = ${l}`,this);const p=n.node,m=p.node.context({assign:!0}).build(e);for(let _=0;_{const u=c.type,h=u==="pointer";let d;return h?d="&"+l.build(e):d=l.build(e,u),d};if(Array.isArray(s)){if(s.length>i.length)ne("TSL: The number of provided parameters exceeds the expected number of inputs in 'Fn()'."),s.length=i.length;else if(s.length(e=e.length>1||e[0]&&e[0].isNode===!0?ta(e):Rp(e[0]),new Zw(Be(r),e));Y("call",Qw);const Jw={"==":"equal","!=":"notEqual","<":"lessThan",">":"greaterThan","<=":"lessThanEqual",">=":"greaterThanEqual","%":"mod"};class nn extends _n{static get type(){return"OperatorNode"}constructor(e,t,n,...i){if(super(),i.length>0){let s=new nn(e,t,n);for(let o=0;o>"||n==="<<")return e.getIntegerType(o);if(n==="!"||n==="&&"||n==="||"||n==="^^")return"bool";if(n==="=="||n==="!="||n==="<"||n===">"||n==="<="||n===">="){const l=Math.max(e.getTypeLength(o),e.getTypeLength(a));return l>1?`bvec${l}`:"bool"}else{if(e.isMatrix(o)){if(a==="float")return o;if(e.isVector(a))return e.getVectorFromMatrix(o);if(e.isMatrix(a))return o}else if(e.isMatrix(a)){if(o==="float")return a;if(e.isVector(o))return e.getVectorFromMatrix(a)}return e.getTypeLength(a)>e.getTypeLength(o)?a:o}}generate(e,t){const n=this.op,{aNode:i,bNode:s}=this,o=this.getNodeType(e,t);let a=null,l=null;o!=="void"?(a=i.getNodeType(e),l=s?s.getNodeType(e):null,n==="<"||n===">"||n==="<="||n===">="||n==="=="||n==="!="?e.isVector(a)?l=a:e.isVector(l)?a=l:a!==l&&(a=l="float"):n===">>"||n==="<<"?(a=o,l=e.changeComponentType(l,"uint")):n==="%"?(a=o,l=e.isInteger(a)&&e.isInteger(l)?l:a):e.isMatrix(a)?l==="float"?l="float":e.isVector(l)?l=e.getVectorFromMatrix(a):e.isMatrix(l)||(a=l=o):e.isMatrix(l)?a==="float"?a="float":e.isVector(a)?a=e.getVectorFromMatrix(l):a=l=o:a=l=o):a=l=o;const c=i.build(e,a),u=s?s.build(e,l):null,h=e.getFunctionOperator(n);if(t!=="void"){const d=e.renderer.coordinateSystem===ti;if(n==="=="||n==="!="||n==="<"||n===">"||n==="<="||n===">=")return d?e.isVector(a)?e.format(`${this.getOperatorMethod(e,t)}( ${c}, ${u} )`,o,t):e.format(`( ${c} ${n} ${u} )`,o,t):e.format(`( ${c} ${n} ${u} )`,o,t);if(n==="%")return e.isInteger(l)?e.format(`( ${c} % ${u} )`,o,t):e.format(`${this.getOperatorMethod(e,o)}( ${c}, ${u} )`,o,t);if(n==="!"||n==="~")return e.format(`(${n}${c})`,a,t);if(h)return e.format(`${h}( ${c}, ${u} )`,o,t);if(e.isMatrix(a)&&l==="float")return e.format(`( ${u} ${n} ${c} )`,o,t);if(a==="float"&&e.isMatrix(l))return e.format(`${c} ${n} ${u}`,o,t);{let f=`( ${c} ${n} ${u} )`;return!d&&o==="bool"&&e.isVector(a)&&e.isVector(l)&&(f=`all${f}`),e.format(f,o,t)}}else if(a!=="void")return h?e.format(`${h}( ${c}, ${u} )`,o,t):e.isMatrix(a)&&l==="float"?e.format(`${u} ${n} ${c}`,o,t):e.format(`${c} ${n} ${u}`,o,t)}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const hi=Se(nn,"+").setParameterLength(2,1/0).setName("add"),si=Se(nn,"-").setParameterLength(2,1/0).setName("sub"),nt=Se(nn,"*").setParameterLength(2,1/0).setName("mul"),vs=Se(nn,"/").setParameterLength(2,1/0).setName("div"),Pp=Se(nn,"%").setParameterLength(2).setName("mod"),eC=Se(nn,"==").setParameterLength(2).setName("equal"),tC=Se(nn,"!=").setParameterLength(2).setName("notEqual"),nC=Se(nn,"<").setParameterLength(2).setName("lessThan"),iC=Se(nn,">").setParameterLength(2).setName("greaterThan"),sC=Se(nn,"<=").setParameterLength(2).setName("lessThanEqual"),rC=Se(nn,">=").setParameterLength(2).setName("greaterThanEqual"),oC=Se(nn,"&&").setParameterLength(2,1/0).setName("and"),aC=Se(nn,"||").setParameterLength(2,1/0).setName("or"),lC=Se(nn,"!").setParameterLength(1).setName("not"),cC=Se(nn,"^^").setParameterLength(2).setName("xor"),uC=Se(nn,"&").setParameterLength(2).setName("bitAnd"),hC=Se(nn,"~").setParameterLength(1).setName("bitNot"),dC=Se(nn,"|").setParameterLength(2).setName("bitOr"),fC=Se(nn,"^").setParameterLength(2).setName("bitXor"),pC=Se(nn,"<<").setParameterLength(2).setName("shiftLeft"),mC=Se(nn,">>").setParameterLength(2).setName("shiftRight"),gC=Q(([r])=>(r.addAssign(1),r)),_C=Q(([r])=>(r.subAssign(1),r)),xC=Q(([r])=>{const e=Kt(r).toConst();return r.addAssign(1),e}),yC=Q(([r])=>{const e=Kt(r).toConst();return r.subAssign(1),e});Y("add",hi);Y("sub",si);Y("mul",nt);Y("div",vs);Y("mod",Pp);Y("equal",eC);Y("notEqual",tC);Y("lessThan",nC);Y("greaterThan",iC);Y("lessThanEqual",sC);Y("greaterThanEqual",rC);Y("and",oC);Y("or",aC);Y("not",lC);Y("xor",cC);Y("bitAnd",uC);Y("bitNot",hC);Y("bitOr",dC);Y("bitXor",fC);Y("shiftLeft",pC);Y("shiftRight",mC);Y("incrementBefore",gC);Y("decrementBefore",_C);Y("increment",xC);Y("decrement",yC);const vC=(r,e)=>(ee('TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.',new jn),Pp(Kt(r),Kt(e)));Y("modInt",vC);class I extends _n{static get type(){return"MathNode"}constructor(e,t,n=null,i=null){if(super(),(e===I.MAX||e===I.MIN)&&arguments.length>3){let s=new I(e,t,n);for(let o=2;oo&&s>a?t:o>a?n:a>s?i:t}generateNodeType(e){const t=this.method;return t===I.LENGTH||t===I.DISTANCE||t===I.DOT?"float":t===I.CROSS?"vec3":t===I.ALL||t===I.ANY?"bool":t===I.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):this.getInputType(e)}setup(e){const{aNode:t,bNode:n,method:i}=this;let s=null;if(i===I.ONE_MINUS)s=si(1,t);else if(i===I.RECIPROCAL)s=vs(1,t);else if(i===I.DIFFERENCE)s=yi(si(t,n));else if(i===I.TRANSFORM_DIRECTION){let o=t,a=n;e.isMatrix(o.getNodeType(e))?a=Ze(K(a),0):o=Ze(K(o),0);const l=nt(o,a).xyz;s=gs(l)}return s!==null?s:super.setup(e)}generate(e,t){if(e.getNodeProperties(this).outputNode)return super.generate(e,t);let i=this.method;const s=this.getNodeType(e),o=this.getInputType(e),a=this.aNode,l=this.bNode,c=this.cNode,u=e.renderer.coordinateSystem;if(i===I.NEGATE)return e.format("( - "+a.build(e,o)+" )",s,t);{const h=[];return i===I.CROSS?h.push(a.build(e,s),l.build(e,s)):u===ti&&i===I.STEP?h.push(a.build(e,e.getTypeLength(a.getNodeType(e))===1?"float":o),l.build(e,o)):u===ti&&(i===I.MIN||i===I.MAX)?h.push(a.build(e,o),l.build(e,e.getTypeLength(l.getNodeType(e))===1?"float":o)):i===I.REFRACT?h.push(a.build(e,o),l.build(e,o),c.build(e,"float")):i===I.MIX?h.push(a.build(e,o),l.build(e,o),c.build(e,e.getTypeLength(c.getNodeType(e))===1?"float":o)):(u===xs&&i===I.ATAN&&l!==null&&(i="atan2"),e.shaderStage!=="fragment"&&(i===I.DFDX||i===I.DFDY)&&(ee(`TSL: '${i}' is not supported in the ${e.shaderStage} stage.`,this.stackTrace),i="/*"+i+"*/"),h.push(a.build(e,o)),l!==null&&h.push(l.build(e,o)),c!==null&&h.push(c.build(e,o))),e.format(`${e.getMethod(i,s)}( ${h.join(", ")} )`,s,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}I.ALL="all";I.ANY="any";I.RADIANS="radians";I.DEGREES="degrees";I.EXP="exp";I.EXP2="exp2";I.LOG="log";I.LOG2="log2";I.SQRT="sqrt";I.INVERSE_SQRT="inversesqrt";I.FLOOR="floor";I.CEIL="ceil";I.NORMALIZE="normalize";I.FRACT="fract";I.SIN="sin";I.SINH="sinh";I.COS="cos";I.COSH="cosh";I.TAN="tan";I.TANH="tanh";I.ASIN="asin";I.ASINH="asinh";I.ACOS="acos";I.ACOSH="acosh";I.ATAN="atan";I.ATANH="atanh";I.ABS="abs";I.SIGN="sign";I.LENGTH="length";I.NEGATE="negate";I.ONE_MINUS="oneMinus";I.DFDX="dFdx";I.DFDY="dFdy";I.ROUND="round";I.RECIPROCAL="reciprocal";I.TRUNC="trunc";I.FWIDTH="fwidth";I.TRANSPOSE="transpose";I.DETERMINANT="determinant";I.INVERSE="inverse";I.EQUALS="equals";I.MIN="min";I.MAX="max";I.STEP="step";I.REFLECT="reflect";I.DISTANCE="distance";I.DIFFERENCE="difference";I.DOT="dot";I.CROSS="cross";I.POW="pow";I.TRANSFORM_DIRECTION="transformDirection";I.MIX="mix";I.CLAMP="clamp";I.REFRACT="refract";I.SMOOTHSTEP="smoothstep";I.FACEFORWARD="faceforward";const Dp=j(1e-6),SC=j(Math.PI),bC=Se(I,I.ALL).setParameterLength(1),TC=Se(I,I.ANY).setParameterLength(1),MC=Se(I,I.RADIANS).setParameterLength(1),EC=Se(I,I.DEGREES).setParameterLength(1),C0=Se(I,I.EXP).setParameterLength(1),Zl=Se(I,I.EXP2).setParameterLength(1),N0=Se(I,I.LOG).setParameterLength(1),Hs=Se(I,I.LOG2).setParameterLength(1),Er=Se(I,I.SQRT).setParameterLength(1),AC=Se(I,I.INVERSE_SQRT).setParameterLength(1),to=Se(I,I.FLOOR).setParameterLength(1),Lp=Se(I,I.CEIL).setParameterLength(1),gs=Se(I,I.NORMALIZE).setParameterLength(1),Ss=Se(I,I.FRACT).setParameterLength(1),xi=Se(I,I.SIN).setParameterLength(1),RC=Se(I,I.SINH).setParameterLength(1),cs=Se(I,I.COS).setParameterLength(1),wC=Se(I,I.COSH).setParameterLength(1),CC=Se(I,I.TAN).setParameterLength(1),NC=Se(I,I.TANH).setParameterLength(1),PC=Se(I,I.ASIN).setParameterLength(1),DC=Se(I,I.ASINH).setParameterLength(1),P0=Se(I,I.ACOS).setParameterLength(1),LC=Se(I,I.ACOSH).setParameterLength(1),UC=Se(I,I.ATAN).setParameterLength(1,2),FC=Se(I,I.ATANH).setParameterLength(1),yi=Se(I,I.ABS).setParameterLength(1),D0=Se(I,I.SIGN).setParameterLength(1),Ws=Se(I,I.LENGTH).setParameterLength(1),L0=Se(I,I.NEGATE).setParameterLength(1),IC=Se(I,I.ONE_MINUS).setParameterLength(1),U0=Se(I,I.DFDX).setParameterLength(1),F0=Se(I,I.DFDY).setParameterLength(1),BC=Se(I,I.ROUND).setParameterLength(1),OC=Se(I,I.RECIPROCAL).setParameterLength(1),kC=Se(I,I.TRUNC).setParameterLength(1),I0=Se(I,I.FWIDTH).setParameterLength(1),GC=Se(I,I.TRANSPOSE).setParameterLength(1),VC=Se(I,I.DETERMINANT).setParameterLength(1),zC=Se(I,I.INVERSE).setParameterLength(1),Ua=Se(I,I.MIN).setParameterLength(2,1/0),On=Se(I,I.MAX).setParameterLength(2,1/0),Ql=Se(I,I.STEP).setParameterLength(2),HC=Se(I,I.REFLECT).setParameterLength(2),WC=Se(I,I.DISTANCE).setParameterLength(2),$C=Se(I,I.DIFFERENCE).setParameterLength(2),uo=Se(I,I.DOT).setParameterLength(2),ho=Se(I,I.CROSS).setParameterLength(2),oh=Se(I,I.POW).setParameterLength(2),B0=r=>nt(r,r),XC=r=>nt(r,r,r),O0=r=>nt(r,r,r,r),qC=Se(I,I.TRANSFORM_DIRECTION).setParameterLength(2),jC=r=>nt(D0(r),oh(yi(r),1/3)),k0=r=>uo(r,r),Nt=Se(I,I.MIX).setParameterLength(3),Cr=(r,e=0,t=1)=>new I(I.CLAMP,Be(r),Be(e),Be(t)),Up=r=>Cr(r),G0=Se(I,I.REFRACT).setParameterLength(3),Xs=Se(I,I.SMOOTHSTEP).setParameterLength(3),YC=Se(I,I.FACEFORWARD).setParameterLength(3),KC=Q(([r])=>{const n=43758.5453,i=uo(r.xy,Ie(12.9898,78.233)),s=Pp(i,SC);return Ss(xi(s).mul(n))}),ZC=(r,e,t)=>Nt(e,t,r),QC=(r,e,t)=>Xs(e,t,r),JC=(r,e)=>Ql(e,r);Y("all",bC);Y("any",TC);Y("radians",MC);Y("degrees",EC);Y("exp",C0);Y("exp2",Zl);Y("log",N0);Y("log2",Hs);Y("sqrt",Er);Y("inverseSqrt",AC);Y("floor",to);Y("ceil",Lp);Y("normalize",gs);Y("fract",Ss);Y("sin",xi);Y("sinh",RC);Y("cos",cs);Y("cosh",wC);Y("tan",CC);Y("tanh",NC);Y("asin",PC);Y("asinh",DC);Y("acos",P0);Y("acosh",LC);Y("atan",UC);Y("atanh",FC);Y("abs",yi);Y("sign",D0);Y("length",Ws);Y("lengthSq",k0);Y("negate",L0);Y("oneMinus",IC);Y("dFdx",U0);Y("dFdy",F0);Y("round",BC);Y("reciprocal",OC);Y("trunc",kC);Y("fwidth",I0);Y("min",Ua);Y("max",On);Y("step",JC);Y("reflect",HC);Y("distance",WC);Y("dot",uo);Y("cross",ho);Y("pow",oh);Y("pow2",B0);Y("pow3",XC);Y("pow4",O0);Y("transformDirection",qC);Y("mix",ZC);Y("clamp",Cr);Y("refract",G0);Y("smoothstep",QC);Y("faceForward",YC);Y("difference",$C);Y("saturate",Up);Y("cbrt",jC);Y("transpose",GC);Y("determinant",VC);Y("inverse",zC);Y("rand",KC);class eN extends Oe{static get type(){return"ConditionalNode"}constructor(e,t,n=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=n}generateNodeType(e){const{ifNode:t,elseNode:n}=e.getNodeProperties(this);if(t===void 0)return e.flowBuildStage(this,"setup"),this.getNodeType(e);const i=t.getNodeType(e);if(n!==null){const s=n.getNodeType(e);if(e.getTypeLength(s)>e.getTypeLength(i))return s}return i}setup(e){const t=this.condNode,n=this.ifNode.isolate(),i=this.elseNode?this.elseNode.isolate():null,s=e.context.nodeBlock;e.getDataFromNode(n).parentNodeBlock=s,i!==null&&(e.getDataFromNode(i).parentNodeBlock=s);const o=e.context.uniformFlow,a=e.getNodeProperties(this);a.condNode=t,a.ifNode=o?n:n.context({nodeBlock:n}),a.elseNode=i?o?i:i.context({nodeBlock:i}):null}generate(e,t){const n=this.getNodeType(e),i=e.getDataFromNode(this);if(i.nodeProperty!==void 0)return i.nodeProperty;const{condNode:s,ifNode:o,elseNode:a}=e.getNodeProperties(this),l=e.currentFunctionNode,c=t!=="void",u=c?Mr(n).build(e):"";i.nodeProperty=u;const h=s.build(e,"bool");if(e.context.uniformFlow&&a!==null){const p=o.build(e,n),g=a.build(e,n),m=e.getTernary(h,p,g);return e.format(m,n,t)}e.addFlowCode(` ${e.tab}if ( ${h} ) { `).addFlowTab();let f=o.build(e,n);if(f&&(c?f=u+" = "+f+";":(f="return "+f+";",l===null&&(ee("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.",this.stackTrace),f="// "+f))),e.removeFlowTab().addFlowCode(e.tab+" "+f+` `+e.tab+"}"),a!==null){e.addFlowCode(` else { `).addFlowTab();let p=a.build(e,n);p&&(c?p=u+" = "+p+";":(p="return "+p+";",l===null&&(ee("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values.",this.stackTrace),p="// "+p))),e.removeFlowTab().addFlowCode(e.tab+" "+p+` `+e.tab+`} `)}else e.addFlowCode(` `);return e.format(u,n,t)}}const Si=Ft(eN).setParameterLength(2,3);Y("select",Si);class V0 extends Oe{static get type(){return"ContextNode"}constructor(e=null,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}generateNodeType(e){return this.node.getNodeType(e)}getFlowContextData(){const e=[];return this.traverse(t=>{t.isContextNode===!0&&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),i=this.node.build(e,t);return e.setContext(n),i}}const So=(r=null,e={})=>{let t=r;return(t===null||t.isNode!==!0)&&(e=t||e,t=null),new V0(t,e)},tN=r=>So(r,{uniformFlow:!0}),z0=(r,e)=>So(r,{nodeName:e});function nN(r,e,t=null){return So(t,{getShadow:({light:n,shadowColorNode:i})=>e===n?i.mul(r):i})}function iN(r,e=null){return So(e,{getAO:(t,{material:n})=>n.transparent===!0?t:t!==null?t.mul(r):r})}function sN(r,e){return ee('TSL: "label()" has been deprecated. Use "setName()" instead.'),z0(r,e)}Y("context",So);Y("label",sN);Y("uniformFlow",tN);Y("setName",z0);Y("builtinShadowContext",(r,e,t)=>nN(e,t,r));Y("builtinAOContext",(r,e)=>iN(e,r));class Au extends Oe{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 e.getDataFromNode(this).forceDeclaration===!0?!1:this.intent}getIntent(){return this.intent}getMemberType(e,t){return this.node.getMemberType(e,t)}getElementType(e){return this.node.getElementType(e)}generateNodeType(e){return this.node.getNodeType(e)}getArrayCount(e){return this.node.getArrayCount(e)}isAssign(e){return e.getDataFromNode(this).assign}build(...e){const t=e[0];if(this._hasStack(t)===!1&&t.buildStage==="setup"&&(t.context.nodeLoop||t.context.nodeBlock)){let n=!1;if(this.node.isShaderCallNodeInternal&&this.node.shaderNode.getLayout()===null&&t.fnCall&&t.fnCall.shaderNode&&t.getDataFromNode(this.node.shaderNode).hasLoop){const o=t.getDataFromNode(this);o.forceDeclaration=!0,n=!0}const i=t.getBaseStack();n?i.addToStackBefore(this):i.addToStack(this)}return this.isIntent(t)&&this.isAssign(t)!==!0?this.node.build(...e):super.build(...e)}generate(e){const{node:t,name:n,readOnly:i}=this,{renderer:s}=e,o=s.backend.isWebGPUBackend===!0;let a=!1,l=!1;i&&(a=e.isDeterministic(t),l=o?i:a);const c=this.getNodeType(e);if(c=="void")return this.isIntent(e)!==!0&&ne('TSL: ".toVar()" can not be used with void type.',this.stackTrace),t.build(e);const u=e.getVectorType(c),h=t.build(e,u),d=e.getVarFromNode(this,n,u,void 0,l),f=e.getPropertyName(d);let p=f;if(l)if(o)p=a?`const ${f}`:`let ${f}`;else{const g=t.getArrayCount(e);p=`const ${e.getVar(d.type,f,g)}`}return e.addLineFlowCode(`${p} = ${h}`,this),f}_hasStack(e){return e.getDataFromNode(this).stack!==void 0}}const Fp=Ft(Au),rN=(r,e=null)=>Fp(r,e).toStack(),oN=(r,e=null)=>Fp(r,e,!0).toStack(),aN=r=>Fp(r).setIntent(!0).toStack();Y("toVar",rN);Y("toConst",oN);Y("toVarIntent",aN);class lN extends Oe{static get type(){return"SubBuild"}constructor(e,t,n=null){super(n),this.node=e,this.name=t,this.isSubBuildNode=!0}generateNodeType(e){if(this.nodeType!==null)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 ia=(r,e,t=null)=>new lN(Be(r),e,t);class cN extends Oe{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=ia(e,"VERTEX"),this.name=t,this.isVaryingNode=!0,this.interpolationType=null,this.interpolationSampling=null,this.global=!0}setInterpolation(e,t=null){return this.interpolationType=e,this.interpolationSampling=t,this}getHash(e){return this.name||super.getHash(e)}generateNodeType(e){return this.node.getNodeType(e)}setupVarying(e){const t=e.getNodeProperties(this);let n=t.varying;if(n===void 0){const i=this.name,s=this.getNodeType(e),o=this.interpolationType,a=this.interpolationSampling;t.varying=n=e.getVaryingFromNode(this,i,s,o,a),t.node=ia(this.node,"VERTEX")}return n.needsInterpolation||(n.needsInterpolation=e.shaderStage==="fragment"),n}setup(e){this.setupVarying(e),e.flowNodeFromShaderStage(Xc.VERTEX,this.node)}analyze(e){this.setupVarying(e),e.flowNodeFromShaderStage(Xc.VERTEX,this.node)}generate(e){const t=e.getSubBuildProperty("property",e.currentStack),n=e.getNodeProperties(this),i=this.setupVarying(e);if(n[t]===void 0){const s=this.getNodeType(e),o=e.getPropertyName(i,Xc.VERTEX);e.flowNodeFromShaderStage(Xc.VERTEX,n.node,s,o),n[t]=o}return e.getPropertyName(i)}}const bo=Ft(cN).setParameterLength(1,2),uN=r=>bo(r);Y("toVarying",bo);Y("toVertexStage",uN);const hN=Q(([r])=>{const e=r.mul(.9478672986).add(.0521327014).pow(2.4),t=r.mul(.0773993808),n=r.lessThanEqual(.04045);return Nt(e,t,n)}).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),dN=Q(([r])=>{const e=r.pow(.41666).mul(1.055).sub(.055),t=r.mul(12.92),n=r.lessThanEqual(.0031308);return Nt(e,t,n)}).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),Ip="WorkingColorSpace",fN="OutputColorSpace";class H0 extends _n{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===Ip?Xe.workingColorSpace:t===fN?e.context.outputColorSpace||e.renderer.outputColorSpace:t}setup(e){const{colorNode:t}=this,n=this.resolveColorSpace(e,this.source),i=this.resolveColorSpace(e,this.target);let s=t;return Xe.enabled===!1||n===i||!n||!i||(Xe.getTransfer(n)===Ee&&(s=Ze(hN(s.rgb),s.a)),Xe.getPrimaries(n)!==Xe.getPrimaries(i)&&(s=Ze(Bn(Xe._getMatrix(new Ke,n,i)).mul(s.rgb),s.a)),Xe.getTransfer(i)===Ee&&(s=Ze(dN(s.rgb),s.a))),s}}const pN=(r,e)=>new H0(Be(r),Ip,e),Bp=(r,e)=>new H0(Be(r),e,Ip);Y("workingToColorSpace",pN);Y("colorSpaceToWorking",Bp);let mN=class extends $a{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}generateNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),n=this.referenceNode.getNodeType(),i=this.getNodeType();return e.format(t,n,i)}};class W0 extends Oe{static get type(){return"ReferenceBaseNode"}constructor(e,t,n=null,i=null){super(),this.property=e,this.uniformType=t,this.object=n,this.count=i,this.properties=e.split("."),this.reference=n,this.node=null,this.group=null,this.updateType=je.OBJECT}setGroup(e){return this.group=e,this}element(e){return new mN(this,Be(e))}setNodeType(e){const t=We(null,e);this.group!==null&&t.setGroup(this.group),this.node=t}generateNodeType(e){return this.node===null&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let n=e[t[0]];for(let i=1;inew W0(r,e,t);class _N extends W0{static get type(){return"RendererReferenceNode"}constructor(e,t,n=null){super(e,t,n),this.renderer=n,this.setGroup(qe)}updateReference(e){return this.reference=this.renderer!==null?this.renderer:e.renderer,this.reference}}const xN=(r,e,t=null)=>new _N(r,e,t);class yN extends _n{static get type(){return"ToneMappingNode"}constructor(e,t=SN,n=null){super("vec3"),this._toneMapping=e,this.exposureNode=t,this.colorNode=n}customCacheKey(){return Al(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(n===Un)return t;let i=null;const s=e.renderer.library.getToneMappingFunction(n);return s!==null?i=Ze(s(t.rgb,this.exposureNode),t.a):(ne("ToneMappingNode: Unsupported Tone Mapping configuration.",n),i=t),i}}const vN=(r,e,t)=>new yN(r,Be(e),Be(t)),SN=xN("toneMappingExposure","float");Y("toneMapping",(r,e,t)=>vN(e,t,r));const wg=new WeakMap;function Cg(r,e){let t=wg.get(r);return t===void 0&&(t=new Ax(r,e),wg.set(r,t)),t}class sr extends Tp{static get type(){return"BufferAttributeNode"}constructor(e,t=null,n=0,i=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=n,this.bufferOffset=i,this.usage=Pa,this.instanced=!1,this.attribute=null,this.global=!0,e&&e.isBufferAttribute===!0&&e.itemSize<=4&&(this.attribute=e,this.usage=e.usage,this.instanced=e.isInstancedBufferAttribute)}getHash(e){let t;if(this.bufferStride===0&&this.bufferOffset===0){let n=e.globalCache.getData(this.value);n===void 0&&(n={node:this},e.globalCache.setData(this.value,n)),t=n.node.id}else t=this.id;return String(t)}generateNodeType(e){return this.bufferType===null&&(this.bufferType=e.getTypeFromAttribute(this.attribute)),this.bufferType}setup(e){if(this.attribute!==null)return;const t=this.getNodeType(e),n=e.getTypeLength(t),i=this.value,s=this.bufferStride||n,o=this.bufferOffset;let a;i.isInterleavedBuffer===!0?a=i:i.isBufferAttribute===!0?a=Cg(i.array,s):a=Cg(i,s);const l=new cp(a,n,o);a.setUsage(this.usage),this.attribute=l,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){const t=this.getNodeType(e),n=e.getBufferAttributeFromNode(this,t),i=e.getPropertyName(n);let s=null;return e.shaderStage==="vertex"||e.shaderStage==="compute"?(this.name=i,s=i):s=bo(this).build(e,t),s}getInputType(){return"bufferAttribute"}setUsage(e){return this.usage=e,this.attribute&&this.attribute.isBufferAttribute===!0&&(this.attribute.usage=e),this}setInstanced(e){return this.instanced=e,this}}function Op(r,e=null,t=0,n=0,i=Pa,s=!1){return e==="mat3"||e===null&&r.itemSize===9?Bn(new sr(r,"vec3",9,0).setUsage(i).setInstanced(s),new sr(r,"vec3",9,3).setUsage(i).setInstanced(s),new sr(r,"vec3",9,6).setUsage(i).setInstanced(s)):e==="mat4"||e===null&&r.itemSize===16?eo(new sr(r,"vec4",16,0).setUsage(i).setInstanced(s),new sr(r,"vec4",16,4).setUsage(i).setInstanced(s),new sr(r,"vec4",16,8).setUsage(i).setInstanced(s),new sr(r,"vec4",16,12).setUsage(i).setInstanced(s)):new sr(r,e,t,n).setUsage(i)}const $0=(r,e=null,t=0,n=0)=>Op(r,e,t,n),Ng=(r,e=null,t=0,n=0)=>Op(r,e,t,n,Pa,!0),Pg=(r,e=null,t=0,n=0)=>Op(r,e,t,n,Nu,!0);Y("toAttribute",r=>$0(r.value));class Jt extends Oe{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 i;if(n===Jt.VERTEX)i=e.getVertexIndex();else if(n===Jt.INSTANCE)i=e.getInstanceIndex();else if(n===Jt.DRAW)i=e.getDrawIndex();else if(n===Jt.INVOCATION_LOCAL)i=e.getInvocationLocalIndex();else if(n===Jt.INVOCATION_SUBGROUP)i=e.getInvocationSubgroupIndex();else if(n===Jt.SUBGROUP)i=e.getSubgroupIndex();else throw new Error("THREE.IndexNode: Unknown scope: "+n);let s;return e.shaderStage==="vertex"||e.shaderStage==="compute"?s=i:s=bo(this).build(e,t),s}}Jt.VERTEX="vertex";Jt.INSTANCE="instance";Jt.SUBGROUP="subgroup";Jt.INVOCATION_LOCAL="invocationLocal";Jt.INVOCATION_SUBGROUP="invocationSubgroup";Jt.DRAW="draw";const bN=ge(Jt,Jt.VERTEX),sa=ge(Jt,Jt.INSTANCE);Jt.SUBGROUP;Jt.INVOCATION_SUBGROUP;Jt.INVOCATION_LOCAL;const TN=ge(Jt,Jt.DRAW);class MN extends Oe{static get type(){return"ComputeNode"}constructor(e,t){super("void"),this.isComputeNode=!0,this.computeNode=e,this.workgroupSize=t,this.count=null,this.dispatchSize=null,this.version=1,this.name="",this.updateBeforeType=je.OBJECT,this.onInitFunction=null,this.countNode=null}dispose(){this.dispatchEvent({type:"dispose"})}setName(e){return this.name=e,this}label(e){return ee('TSL: "label()" has been deprecated. Use "setName()" instead.',new jn),this.setName(e)}onInit(e){return this.onInitFunction=e,this}updateBefore({renderer:e}){e.compute(this)}setup(e){this.count!==null&&this.countNode===null&&(this.countNode=We(this.count,"uint").onObjectUpdate(()=>this.count));const t=this.computeNode.build(e);if(t){const n=e.getNodeProperties(this);n.outputComputeNode=t.outputNode,t.outputNode=null}return t}generate(e,t){const{shaderStage:n}=e;if(n==="compute"){const i=this.computeNode.build(e,"void");if(i!==""&&e.addLineFlowCode(i,this),this.count!==null&&e.allowEarlyReturns===!0){const s=this.countNode.build(e,"uint"),o=sa.build(e,"uint");e.flow.code=`${e.tab}if ( ${o} >= ${s} ) { return; } ${e.flow.code}`}}else{const s=e.getNodeProperties(this).outputComputeNode;if(s)return s.build(e,t)}}}const X0=(r,e=[64])=>{(e.length===0||e.length>3)&&ne("TSL: compute() workgroupSize must have 1, 2, or 3 elements",new jn);for(let t=0;t{const n=X0(r,t);return typeof e=="number"?n.count=e:n.dispatchSize=e,n};Y("compute",EN);Y("computeKernel",X0);class AN extends Oe{static get type(){return"IsolateNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isIsolateNode=!0}generateNodeType(e){const t=e.getCache(),n=e.getCacheFromNode(this,this.parent);e.setCache(n);const i=this.node.getNodeType(e);return e.setCache(t),i}build(e,...t){const n=e.getCache(),i=e.getCacheFromNode(this,this.parent);e.setCache(i);const s=this.node.build(e,...t);return e.setCache(n),s}setParent(e){return this.parent=e,this}getParent(){return this.parent}}const Nl=r=>new AN(Be(r));function RN(r,e=!0){return ee('TSL: "cache()" has been deprecated. Use "isolate()" instead.'),Nl(r).setParent(e)}Y("cache",RN);Y("isolate",Nl);class wN extends Oe{static get type(){return"BypassNode"}constructor(e,t){super(),this.isBypassNode=!0,this.outputNode=e,this.callNode=t}generateNodeType(e){return this.outputNode.getNodeType(e)}generate(e){const t=this.callNode.build(e,"void");return t!==""&&e.addLineFlowCode(t,this),this.outputNode.build(e)}}const CN=Ft(wN).setParameterLength(2);Y("bypass",CN);const q0=Q(([r,e,t,n=j(0),i=j(1),s=rh(!1)])=>{let o=r.sub(e).div(t.sub(e));return pf(s)&&(o=o.clamp()),o.mul(i.sub(n)).add(n)});function NN(r,e,t,n=j(0),i=j(1)){return q0(r,e,t,n,i,!0)}Y("remap",q0);Y("remapClamp",NN);class Ru extends Oe{static get type(){return"ExpressionNode"}constructor(e="",t="void"){super(t),this.snippet=e}generate(e,t){const n=this.getNodeType(e),i=this.snippet;if(n==="void")e.addLineFlowCode(i,this);else return e.format(i,n,t)}}const hs=Ft(Ru).setParameterLength(1,2),PN=r=>(r?Si(r,hs("discard")):hs("discard")).toStack();Y("discard",PN);class DN extends _n{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=(this._toneMapping!==null?this._toneMapping:e.toneMapping)||Un,i=(this.outputColorSpace!==null?this.outputColorSpace:e.outputColorSpace)||ri;return n!==Un&&(t=t.toneMapping(n)),i!==ri&&i!==Xe.workingColorSpace&&(t=t.workingToColorSpace(i)),t}}const j0=(r,e=null,t=null)=>new DN(Be(r),e,t);Y("renderOutput",j0);class LN extends _n{static get type(){return"DebugNode"}constructor(e,t=null){super(),this.node=e,this.callback=t}generateNodeType(e){return this.node.getNodeType(e)}setup(e){return this.node.build(e)}analyze(e){return this.node.build(e)}generate(e){const t=this.callback,n=this.node.build(e);if(t!==null)t(e,n);else{const i="--- TSL debug - "+e.shaderStage+" shader ---",s="-".repeat(i.length);let o="";o+="// #"+i+`# `,o+=e.flow.code.replace(/^\t/mg,"")+` `,o+="/* ... */ "+n+` /* ... */ `,o+="// #"+s+`# `,Kl(o)}return n}}const UN=(r,e=null)=>new LN(Be(r),e).toStack();Y("debug",UN);class Y0 extends Ii{constructor(){super(),this._renderer=null,this.currentFrame=null}get nodeFrame(){return this._renderer._nodes.nodeFrame}setRenderer(e){return this._renderer=e,this}getRenderer(){return this._renderer}init(){}begin(){}finish(){}inspect(){}computeAsync(){}beginCompute(){}finishCompute(){}beginRender(){}finishRender(){}copyTextureToTexture(){}copyFramebufferToTexture(){}}class FN extends Oe{static get type(){return"InspectorNode"}constructor(e,t="",n=null){super(),this.node=e,this.name=t,this.callback=n,this.updateType=je.FRAME,this.isInspectorNode=!0}getName(){return this.name||this.node.name}update(e){e.renderer.inspector.inspect(this)}generateNodeType(e){return this.node.getNodeType(e)}setup(e){let t=this.node;return e.context.inspector===!0&&this.callback!==null&&(t=this.callback(t)),e.renderer.backend.isWebGPUBackend!==!0&&e.renderer.inspector.constructor!==Y0&&Yt('TSL: ".toInspector()" is only available with WebGPU.'),t}}function IN(r,e="",t=null){return r=Be(r),r.before(new FN(r,e,t))}Y("toInspector",IN);class K0 extends Oe{static get type(){return"AttributeNode"}constructor(e,t=null){super(t),this.global=!0,this._attributeName=e}getHash(e){return this.getAttributeName(e)}generateNodeType(e){let t=this.nodeType;if(t===null){const n=this.getAttributeName(e);if(e.hasGeometryAttribute(n)){const i=e.geometry.getAttribute(n);t=e.getTypeFromAttribute(i)}else t="float"}return t}setAttributeName(e){return this._attributeName=e,this}getAttributeName(){return this._attributeName}generate(e){const t=this.getAttributeName(e),n=this.getNodeType(e);if(e.hasGeometryAttribute(t)===!0){const s=e.geometry.getAttribute(t),o=e.getTypeFromAttribute(s),a=e.getAttribute(t,o);return e.shaderStage==="vertex"?e.format(a.name,o,n):bo(this).build(e,n)}else return ee(`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 Nr=(r,e=null)=>new K0(r,e),Xa=(r=0)=>Nr("uv"+(r>0?r:""),"vec2");class BN extends Oe{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"),i=this.levelNode===null?"0":this.levelNode.build(e,"int");return e.format(`${e.getMethod("textureDimensions")}( ${n}, ${i} )`,this.getNodeType(e),t)}}const ra=Ft(BN).setParameterLength(1,2);class ON extends fc{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=je.FRAME}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&&n.width!==void 0){const{width:i,height:s}=n;this.value=Math.log2(Math.max(i,s))}}}const kN=Ft(ON).setParameterLength(1);class GN extends Error{constructor(e,t=null){super(e),this.name="NodeError",this.stackTrace=t}}const Z0=new pn;class pc extends fc{static get type(){return"TextureNode"}constructor(e=Z0,t=null,n=null,i=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=n,this.biasNode=i,this.compareNode=null,this.depthNode=null,this.gradNode=null,this.offsetNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=je.NONE,this.referenceNode=null,this._value=e,this._matrixUniform=null,this._flipYUniform=null,this.setUpdateMatrix(t===null)}set value(e){this.referenceNode?this.referenceNode.value=e:this._value=e}get value(){return this.referenceNode?this.referenceNode.value:this._value}getUniformHash(){return this.value.uuid}generateNodeType(){return this.value.isDepthTexture===!0?"float":this.value.type===wt?"uvec4":this.value.type===Sn?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return Xa(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return this._matrixUniform===null&&(this._matrixUniform=We(this.value.matrix)),this._matrixUniform.mul(K(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this}setupUV(e,t){return e.isFlipY()&&(this._flipYUniform===null&&(this._flipYUniform=We(!1)),t=t.toVar(),this.sampler?t=this._flipYUniform.select(t.flipY(),t):t=this._flipYUniform.select(t.setY(Kt(ra(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||n.isTexture!==!0)throw new GN("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().",this.stackTrace);const i=Q(()=>{let l=this.uvNode;return(l===null||e.context.forceUVContext===!0)&&e.context.getUV&&(l=e.context.getUV(this,e)),l||(l=this.getDefaultUV()),this.updateMatrix===!0&&(l=this.getTransformedUV(l)),l=this.setupUV(e,l),this.updateType=this._matrixUniform!==null||this._flipYUniform!==null?je.OBJECT:je.NONE,l})();let s=this.levelNode;s===null&&e.context.getTextureLevel&&(s=e.context.getTextureLevel(this));let o=null,a=null;if(this.compareNode!==null)if(e.renderer.hasCompatibility(_o.TEXTURE_COMPARE))o=this.compareNode;else{const l=n.compareFunction;l===null||l===Ku||l===Dr||l===jl||l===$s?a=this.compareNode:(o=this.compareNode,Yt('TSL: Only "LessCompare", "LessEqualCompare", "GreaterCompare" and "GreaterEqualCompare" are supported for depth texture comparison fallback.'))}t.uvNode=i,t.levelNode=s,t.biasNode=this.biasNode,t.compareNode=o,t.compareStepNode=a,t.gradNode=this.gradNode,t.depthNode=this.depthNode,t.offsetNode=this.offsetNode}generateUV(e,t){return t.build(e,this.sampler===!0?"vec2":"ivec2")}generateOffset(e,t){return t.build(e,"ivec2")}generateSnippet(e,t,n,i,s,o,a,l,c){const u=this.value;let h;return s?h=e.generateTextureBias(u,t,n,s,o,c):l?h=e.generateTextureGrad(u,t,n,l,o,c):a?h=e.generateTextureCompare(u,t,n,a,o,c):this.sampler===!1?h=e.generateTextureLoad(u,t,n,i,o,c):i?h=e.generateTextureLevel(u,t,n,i,o,c):h=e.generateTexture(u,t,n,o,c),h}generate(e,t){const n=this.value,i=e.getNodeProperties(this),s=super.generate(e,"property");if(/^sampler/.test(t))return s+"_sampler";if(e.isReference(t))return s;{const o=e.getDataFromNode(this),a=this.getNodeType(e);let l=o.propertyName;if(l===void 0){const{uvNode:u,levelNode:h,biasNode:d,compareNode:f,compareStepNode:p,depthNode:g,gradNode:m,offsetNode:_}=i,x=this.generateUV(e,u),v=h?h.build(e,"float"):null,S=d?d.build(e,"float"):null,E=g?g.build(e,"int"):null,T=f?f.build(e,"float"):null,A=p?p.build(e,"float"):null,y=m?[m[0].build(e,"vec2"),m[1].build(e,"vec2")]:null,R=_?this.generateOffset(e,_):null;let P=E;P===null&&n.isArrayTexture&&this.isTexture3DNode!==!0&&(P="0");const N=e.getVarFromNode(this);l=e.getPropertyName(N);let U=this.generateSnippet(e,s,x,v,S,P,T,y,R);if(A!==null){const G=n.compareFunction;G===jl||G===$s?U=Ql(hs(U,a),hs(A,"float")).build(e,a):U=Ql(hs(A,"float"),hs(U,a)).build(e,a)}e.addLineFlowCode(`${l} = ${U}`,this),o.snippet=U,o.propertyName=l}let c=l;return e.needsToWorkingColorSpace(n)&&(c=Bp(hs(c,a),n.colorSpace).setup(e).build(e,a)),e.format(c,a,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}sample(e){const t=this.clone();return t.uvNode=Be(e),t.referenceNode=this.getBase(),Be(t)}load(e){return this.sample(e).setSampler(!1)}blur(e){const t=this.clone();t.biasNode=Be(e).mul(kN(t)),t.referenceNode=this.getBase();const n=t.value;return t.generateMipmaps===!1&&(n&&n.generateMipmaps===!1||n.minFilter===bt||n.magFilter===bt)&&(ee("TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture."),t.biasNode=null),Be(t)}level(e){const t=this.clone();return t.levelNode=Be(e),t.referenceNode=this.getBase(),Be(t)}size(e){return ra(this,e)}bias(e){const t=this.clone();return t.biasNode=Be(e),t.referenceNode=this.getBase(),Be(t)}getBase(){return this.referenceNode?this.referenceNode.getBase():this}compare(e){const t=this.clone();return t.compareNode=Be(e),t.referenceNode=this.getBase(),Be(t)}grad(e,t){const n=this.clone();return n.gradNode=[Be(e),Be(t)],n.referenceNode=this.getBase(),Be(n)}depth(e){const t=this.clone();return t.depthNode=Be(e),t.referenceNode=this.getBase(),Be(t)}offset(e){const t=this.clone();return t.offsetNode=Be(e),t.referenceNode=this.getBase(),Be(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;t!==null&&(t.value=e.matrix),e.matrixAutoUpdate===!0&&e.updateMatrix();const n=this._flipYUniform;n!==null&&(n.value=e.image instanceof ImageBitmap&&e.flipY===!0||e.isRenderTargetTexture===!0||e.isFramebufferTexture===!0||e.isDepthTexture===!0)}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 VN=Ft(pc).setParameterLength(1,4).setName("texture"),Gt=(r=Z0,e=null,t=null,n=null)=>{let i;return r&&r.isTextureNode===!0?(i=Be(r.clone()),i.referenceNode=r.getBase(),e!==null&&(i.uvNode=Be(e)),t!==null&&(i.levelNode=Be(t)),n!==null&&(i.biasNode=Be(n))):i=VN(r,e,t,n),i},Ai=(...r)=>Gt(...r).setSampler(!1);class kp extends fc{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 Q0=(r,e,t)=>new kp(r,e,t);class zN extends $a{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),n=this.getNodeType(e),i=this.node.getPaddedType();return e.format(t,i,n)}}class HN extends kp{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=t===null?Bu(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=je.RENDER,this.isArrayBufferNode=!0}generateNodeType(){return this.paddedType}getElementType(){return this.elementType}getPaddedType(){const e=this.elementType;let t="vec4";return e==="mat2"?t="mat2":/mat/.test(e)===!0?t="mat4":e.charAt(0)==="i"?t="ivec4":e.charAt(0)==="u"&&(t="uvec4"),t}update(){const{array:e,value:t}=this,n=this.elementType;if(n==="float"||n==="int"||n==="uint")for(let i=0;inew HN(r,e);class WN extends Oe{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}}const qa=Ft(WN).setParameterLength(1);let ol,al;class Ht extends Oe{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this._output=null,this.isViewportNode=!0}generateNodeType(){return this.scope===Ht.DPR?"float":this.scope===Ht.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=je.NONE;return(this.scope===Ht.SIZE||this.scope===Ht.VIEWPORT||this.scope===Ht.DPR)&&(e=je.RENDER),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===Ht.VIEWPORT?t!==null?al.copy(t.viewport):(e.getViewport(al),al.multiplyScalar(e.getPixelRatio())):this.scope===Ht.DPR?this._output.value=e.getPixelRatio():t!==null?(ol.width=t.width,ol.height=t.height):e.getDrawingBufferSize(ol)}setup(){const e=this.scope;let t=null;return e===Ht.SIZE?t=We(ol||(ol=new de)):e===Ht.VIEWPORT?t=We(al||(al=new tt)):e===Ht.DPR?t=We(1):t=Ie(ja.div(Sf)),this._output=t,t}generate(e){if(this.scope===Ht.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const n=e.getNodeProperties(Sf).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${n}.y - ${t}.y )`}return t}return super.generate(e)}}Ht.COORDINATE="coordinate";Ht.VIEWPORT="viewport";Ht.SIZE="size";Ht.UV="uv";Ht.DPR="dpr";const $N=ge(Ht,Ht.DPR),no=ge(Ht,Ht.UV),Sf=ge(Ht,Ht.SIZE),ja=ge(Ht,Ht.COORDINATE),J0=ge(Ht,Ht.VIEWPORT),XN=J0.zw;J0.xy;let ud=null,Yc=null,hd=null,Kc=null,dd=null,Zc=null,fd=null,Qc=null;const ah=We(0,"uint").setName("u_cameraIndex").setGroup(Np("cameraIndex")).toVarying("v_cameraIndex"),Yr=We("float").setName("cameraNear").setGroup(qe).onRenderUpdate(({camera:r})=>r.near),Kr=We("float").setName("cameraFar").setGroup(qe).onRenderUpdate(({camera:r})=>r.far),Pl=Q(({camera:r})=>{let e;if(r.isArrayCamera&&r.cameras.length>0){const t=[];for(const n of r.cameras)t.push(n.projectionMatrix);Yc===null?Yc=Ri(t).setGroup(qe).setName("cameraProjectionMatrices"):Yc.array=t,e=Yc.element(r.isMultiViewCamera?qa("gl_ViewID_OVR"):ah).toConst("cameraProjectionMatrix")}else ud===null&&(ud=We(r.projectionMatrix).setName("cameraProjectionMatrix").setGroup(qe).onRenderUpdate(({camera:t})=>t.projectionMatrix)),e=ud;return e}).once()(),qN=Q(({camera:r})=>{let e;if(r.isArrayCamera&&r.cameras.length>0){const t=[];for(const n of r.cameras)t.push(n.projectionMatrixInverse);Kc===null?Kc=Ri(t).setGroup(qe).setName("cameraProjectionMatricesInverse"):Kc.array=t,e=Kc.element(r.isMultiViewCamera?qa("gl_ViewID_OVR"):ah).toConst("cameraProjectionMatrixInverse")}else hd===null&&(hd=We(r.projectionMatrixInverse).setName("cameraProjectionMatrixInverse").setGroup(qe).onRenderUpdate(({camera:t})=>t.projectionMatrixInverse)),e=hd;return e}).once()(),js=Q(({camera:r})=>{let e;if(r.isArrayCamera&&r.cameras.length>0){const t=[];for(const n of r.cameras)t.push(n.matrixWorldInverse);Zc===null?Zc=Ri(t).setGroup(qe).setName("cameraViewMatrices"):Zc.array=t,e=Zc.element(r.isMultiViewCamera?qa("gl_ViewID_OVR"):ah).toConst("cameraViewMatrix")}else dd===null&&(dd=We(r.matrixWorldInverse).setName("cameraViewMatrix").setGroup(qe).onRenderUpdate(({camera:t})=>t.matrixWorldInverse)),e=dd;return e}).once()(),jN=Q(({camera:r})=>{let e;if(r.isArrayCamera&&r.cameras.length>0){const t=[];for(let n=0,i=r.cameras.length;n{const s=n.cameras,o=i.array;for(let a=0,l=s.length;an.value.setFromMatrixPosition(t.matrixWorld))),e=fd;return e}).once()(),Dg=new ac;class jt extends Oe{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=je.OBJECT,this.uniformNode=new fc(null)}generateNodeType(){const e=this.scope;if(e===jt.WORLD_MATRIX)return"mat4";if(e===jt.POSITION||e===jt.VIEW_POSITION||e===jt.DIRECTION||e===jt.SCALE)return"vec3";if(e===jt.RADIUS)return"float"}update(e){const t=this.object3d,n=this.uniformNode,i=this.scope;if(i===jt.WORLD_MATRIX)n.value=t.matrixWorld;else if(i===jt.POSITION)n.value=n.value||new C,n.value.setFromMatrixPosition(t.matrixWorld);else if(i===jt.SCALE)n.value=n.value||new C,n.value.setFromMatrixScale(t.matrixWorld);else if(i===jt.DIRECTION)n.value=n.value||new C,t.getWorldDirection(n.value);else if(i===jt.VIEW_POSITION){const s=e.camera;n.value=n.value||new C,n.value.setFromMatrixPosition(t.matrixWorld),n.value.applyMatrix4(s.matrixWorldInverse)}else if(i===jt.RADIUS){const s=e.object.geometry;s.boundingSphere===null&&s.computeBoundingSphere(),Dg.copy(s.boundingSphere).applyMatrix4(t.matrixWorld),n.value=Dg.radius}}generate(e){const t=this.scope;return t===jt.WORLD_MATRIX?this.uniformNode.nodeType="mat4":t===jt.POSITION||t===jt.VIEW_POSITION||t===jt.DIRECTION||t===jt.SCALE?this.uniformNode.nodeType="vec3":t===jt.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}}jt.WORLD_MATRIX="worldMatrix";jt.POSITION="position";jt.SCALE="scale";jt.VIEW_POSITION="viewPosition";jt.DIRECTION="direction";jt.RADIUS="radius";class Fi extends jt{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}Fi.DIRECTION;const fo=ge(Fi,Fi.WORLD_MATRIX);Fi.POSITION;Fi.SCALE;Fi.VIEW_POSITION;Fi.RADIUS;const YN=We(new Ke).onObjectUpdate(({object:r},e)=>e.value.getNormalMatrix(r.matrixWorld)),mc=Q(r=>r.context.modelViewMatrix||KN).once()().toVar("modelViewMatrix"),KN=js.mul(fo),Lg=Q(r=>(r.context.isHighPrecisionModelViewMatrix=!0,We("mat4").onObjectUpdate(({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld)))).once()().toVar("highpModelViewMatrix"),Ug=Q(r=>{const e=r.context.isHighPrecisionModelViewMatrix;return We("mat3").onObjectUpdate(({object:t,camera:n})=>(e!==!0&&t.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse,t.matrixWorld),t.normalMatrix.getNormalMatrix(t.modelViewMatrix)))}).once()().toVar("highpModelNormalViewMatrix"),ZN=Q(r=>r.shaderStage!=="fragment"?(Yt("TSL: `clipSpace` is only available in fragment stage."),Ze()):r.context.clipSpace.toVarying("v_clipSpace")).once()(),lh=Nr("position","vec3"),bn=lh.toVarying("positionLocal"),Gu=lh.toVarying("positionPrevious"),Fa=Q(r=>fo.mul(bn).xyz.toVarying(r.getSubBuildProperty("v_positionWorld")),"vec3").once(["POSITION"])(),ey=Q(()=>bn.transformDirection(fo).toVarying("v_positionWorldDirection").normalize().toVar("positionWorldDirection"),"vec3").once(["POSITION"])(),hn=Q(r=>{if(r.shaderStage==="fragment"&&r.material.vertexNode){const e=qN.mul(ZN);return e.xyz.div(e.w).toVar("positionView")}return r.context.setupPositionView().toVarying("v_positionView")},"vec3").once(["POSITION","VERTEX"])(),Wt=Q(r=>{let e;return r.camera.isOrthographicCamera?e=K(0,0,1):e=hn.negate().toVarying("v_positionViewDirection").normalize(),e.toVar("positionViewDirection")},"vec3").once(["POSITION"])();class QN extends Oe{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){if(e.shaderStage!=="fragment")return"true";const{material:t}=e;return t.side===Pt?"false":e.getFrontFacing()}}const JN=ge(QN),ty=j(JN).mul(2).sub(1),gc=Q(([r],{material:e})=>{const t=e.side;return t===Pt?r=r.mul(-1):t===wn&&(r=r.mul(ty)),r}),ny=Nr("normal","vec3"),bs=Q(r=>r.geometry.hasAttribute("normal")===!1?(ee('TSL: Vertex attribute "normal" not found on geometry.'),K(0,1,0)):ny,"vec3").once()().toVar("normalLocal"),e1=hn.dFdx().cross(hn.dFdy()).normalize().toVar("normalFlat"),Jl=Q(r=>{let e;return r.isFlatShading()?e=e1:e=iy(bs).toVarying("v_normalViewGeometry").normalize(),e},"vec3").once()().toVar("normalViewGeometry"),t1=Q(r=>{let e=Jl.transformDirection(js);return r.isFlatShading()!==!0&&(e=e.toVarying("v_normalWorldGeometry")),e.normalize().toVar("normalWorldGeometry")},"vec3").once()(),_t=Q(r=>{let e;return r.subBuildFn==="NORMAL"||r.subBuildFn==="VERTEX"?(e=Jl,r.isFlatShading()!==!0&&(e=gc(e))):e=r.context.setupNormal().context({getUV:null,getTextureLevel:null}),e},"vec3").once(["NORMAL","VERTEX"])().toVar("normalView"),Ya=_t.transformDirection(js).toVar("normalWorld"),Zr=Q(({subBuildFn:r,context:e})=>{let t;return r==="NORMAL"||r==="VERTEX"?t=_t:t=e.setupClearcoatNormal().context({getUV:null,getTextureLevel:null}),t},"vec3").once(["NORMAL","VERTEX"])().toVar("clearcoatNormalView"),n1=Q(([r,e=fo])=>{const t=Bn(e),n=r.div(K(t[0].dot(t[0]),t[1].dot(t[1]),t[2].dot(t[2])));return t.mul(n).xyz}),iy=Q(([r],e)=>{const t=e.context.modelNormalViewMatrix;if(t)return t.transformDirection(r);const n=YN.mul(r);return js.transformDirection(n)});Q(()=>(ee('TSL: "transformedNormalView" is deprecated. Use "normalView" instead.'),_t)).once(["NORMAL","VERTEX"])();Q(()=>(ee('TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.'),Ya)).once(["NORMAL","VERTEX"])();Q(()=>(ee('TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.'),Zr)).once(["NORMAL","VERTEX"])();const pd=new dt,i1=We(0).onReference(({material:r})=>r).onObjectUpdate(({material:r})=>r.refractionRatio),md=We(1).onReference(({material:r})=>r).onObjectUpdate(function({material:r,scene:e}){return r.envMap?r.envMapIntensity:e.environmentIntensity}),sy=We(new dt).onReference(function(r){return r.material}).onObjectUpdate(function({material:r,scene:e}){const t=e.environment!==null&&r.envMap===null?e.environmentRotation:r.envMapRotation;return t?pd.makeRotationFromEuler(t).transpose():pd.identity(),pd}),s1=Wt.negate().reflect(_t),r1=Wt.negate().refract(_t,i1),o1=s1.transformDirection(js).toVar("reflectVector"),a1=r1.transformDirection(js).toVar("reflectVector"),l1=new Ga;class c1 extends pc{static get type(){return"CubeTextureNode"}constructor(e,t=null,n=null,i=null){super(e,t,n,i),this.isCubeTextureNode=!0}getInputType(){return this.value.isDepthTexture===!0?"cubeDepthTexture":"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===Xi?o1:e.mapping===_s?a1:(ne('CubeTextureNode: Mapping "%s" not supported.',e.mapping),K(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const n=this.value;return n.isDepthTexture===!0?e.renderer.coordinateSystem===xs?K(t.x,t.y.negate(),t.z):t:(t=sy.mul(t),(e.renderer.coordinateSystem===xs||!n.isRenderTargetTexture)&&(t=K(t.x.negate(),t.yz)),t)}generateUV(e,t){return t.build(e,this.sampler===!0?"vec3":"ivec3")}}const u1=Ft(c1).setParameterLength(1,4).setName("cubeTexture"),oi=(r=l1,e=null,t=null,n=null)=>{let i;return r&&r.isCubeTextureNode===!0?(i=Be(r.clone()),i.referenceNode=r,e!==null&&(i.uvNode=Be(e)),t!==null&&(i.levelNode=Be(t)),n!==null&&(i.biasNode=Be(n))):i=u1(r,e,t,n),i};class h1 extends $a{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}generateNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),n=this.referenceNode.getNodeType(e),i=this.getNodeType(e);return e.format(t,n,i)}}class Gp extends Oe{static get type(){return"ReferenceNode"}constructor(e,t,n=null,i=null){super(),this.property=e,this.uniformType=t,this.object=n,this.count=i,this.properties=e.split("."),this.reference=n,this.node=null,this.group=null,this.name=null,this.updateType=je.OBJECT}element(e){return new h1(this,Be(e))}setGroup(e){return this.group=e,this}setName(e){return this.name=e,this}label(e){return ee('TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}setNodeType(e){let t=null;this.count!==null?t=Q0(null,e,this.count):Array.isArray(this.getValueFromReference())?t=Ri(null,e):e==="texture"?t=Gt(null):e==="cubeTexture"?t=oi(null):t=We(null,e),this.group!==null&&t.setGroup(this.group),this.name!==null&&t.setName(this.name),this.node=t}generateNodeType(e){return this.node===null&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let n=e[t[0]];for(let i=1;inew Gp(r,e,t),Fg=(r,e,t,n)=>new Gp(r,e,n,t);class d1 extends Gp{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=this.material!==null?this.material:e.material,this.reference}}const cr=(r,e,t=null)=>new d1(r,e,t),ry=Xa(),f1=hn.dFdx(),p1=hn.dFdy(),oy=ry.dFdx(),ay=ry.dFdy(),ly=_t,cy=p1.cross(ly),uy=ly.cross(f1),bf=cy.mul(oy.x).add(uy.mul(ay.x)),Tf=cy.mul(oy.y).add(uy.mul(ay.y)),Ig=bf.dot(bf).max(Tf.dot(Tf)),hy=Ig.equal(0).select(0,Ig.inverseSqrt()),m1=bf.mul(hy).toVar("tangentViewFrame"),g1=Tf.mul(hy).toVar("bitangentViewFrame"),dy=Nr("tangent","vec4"),Vu=dy.xyz.toVar("tangentLocal"),fy=Q(r=>{let e;return r.subBuildFn==="VERTEX"||r.geometry.hasAttribute("tangent")?e=mc.mul(Ze(Vu,0)).xyz.toVarying("v_tangentView").normalize():e=m1,r.isFlatShading()!==!0&&(e=gc(e)),e},"vec3").once(["NORMAL","VERTEX"])().toVar("tangentView"),_1=Q(([r,e],t)=>{let n=r.mul(dy.w).xyz;return t.subBuildFn==="NORMAL"&&t.isFlatShading()!==!0&&(n=n.toVarying(e)),n}).once(["NORMAL"]),x1=Q(r=>{let e;return r.subBuildFn==="VERTEX"||r.geometry.hasAttribute("tangent")?e=_1(_t.cross(fy),"v_bitangentView").normalize():e=g1,r.isFlatShading()!==!0&&(e=gc(e)),e},"vec3").once(["NORMAL","VERTEX"])().toVar("bitangentView"),yl=Bn(fy,x1,_t).toVar("TBNViewMatrix"),y1=Q(()=>{let r=na.cross(Wt);return r=r.cross(na).normalize(),r=Nt(r,_t,Xr.mul(Os.oneMinus()).oneMinus().pow2().pow2()).normalize(),r}).once()(),v1=r=>Be(r).mul(.5).add(.5),Bg=r=>K(r,Er(Up(j(1).sub(uo(r,r)))));class S1 extends _n{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=Wi,this.unpackNormalMode=vh}setup(e){const{normalMapType:t,scaleNode:n,unpackNormalMode:i}=this;let s=this.node.mul(2).sub(1);if(t===Wi?i===vx?s=Bg(s.xy):i===Zv?s=Bg(s.yw):i!==vh&&ne(`THREE.NodeMaterial: Unexpected unpack normal mode: ${i}`):i!==vh&&ne(`THREE.NodeMaterial: Normal map type '${t}' is not compatible with unpack normal mode '${i}'`),n!==null){let a=n;e.isFlatShading()===!0&&(a=gc(a)),s=K(s.xy.mul(a),s.z)}let o=null;return t===yx?o=iy(s):t===Wi?o=yl.mul(s).normalize():(ne(`NodeMaterial: Unsupported normal map type: ${t}`),o=_t),o}}const Og=Ft(S1).setParameterLength(1,2),b1=Q(({textureNode:r,bumpScale:e})=>{const t=i=>r.isolate().context({getUV:s=>i(s.uvNode||Xa()),forceUVContext:!0}),n=j(t(i=>i));return Ie(j(t(i=>i.add(i.dFdx()))).sub(n),j(t(i=>i.add(i.dFdy()))).sub(n)).mul(e)}),T1=Q(r=>{const{surf_pos:e,surf_norm:t,dHdxy:n}=r,i=e.dFdx().normalize(),s=e.dFdy().normalize(),o=t,a=s.cross(o),l=o.cross(i),c=i.dot(a).mul(ty),u=c.sign().mul(n.x.mul(a).add(n.y.mul(l)));return c.abs().mul(t).sub(u).normalize()});class M1 extends _n{static get type(){return"BumpMapNode"}constructor(e,t=null){super("vec3"),this.textureNode=e,this.scaleNode=t}setup(){const e=this.scaleNode!==null?this.scaleNode:1,t=b1({textureNode:this.textureNode,bumpScale:e});return T1({surf_pos:hn,surf_norm:_t,dHdxy:t})}}const E1=Ft(M1).setParameterLength(1,2),kg=new Map;class Z extends Oe{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let n=kg.get(e);return n===void 0&&(n=cr(e,t),kg.set(e,n)),n}getFloat(e){return this.getCache(e,"float")}getColor(e){return this.getCache(e,"color")}getTexture(e){return this.getCache(e==="map"?"map":e+"Map","texture")}setup(e){const t=e.context.material,n=this.scope;let i=null;if(n===Z.COLOR){const s=t.color!==void 0?this.getColor(n):K();t.map&&t.map.isTexture===!0?i=s.mul(this.getTexture("map")):i=s}else if(n===Z.OPACITY){const s=this.getFloat(n);t.alphaMap&&t.alphaMap.isTexture===!0?i=s.mul(this.getTexture("alpha")):i=s}else if(n===Z.SPECULAR_STRENGTH)t.specularMap&&t.specularMap.isTexture===!0?i=this.getTexture("specular").r:i=j(1);else if(n===Z.SPECULAR_INTENSITY){const s=this.getFloat(n);t.specularIntensityMap&&t.specularIntensityMap.isTexture===!0?i=s.mul(this.getTexture(n).a):i=s}else if(n===Z.SPECULAR_COLOR){const s=this.getColor(n);t.specularColorMap&&t.specularColorMap.isTexture===!0?i=s.mul(this.getTexture(n).rgb):i=s}else if(n===Z.ROUGHNESS){const s=this.getFloat(n);t.roughnessMap&&t.roughnessMap.isTexture===!0?i=s.mul(this.getTexture(n).g):i=s}else if(n===Z.METALNESS){const s=this.getFloat(n);t.metalnessMap&&t.metalnessMap.isTexture===!0?i=s.mul(this.getTexture(n).b):i=s}else if(n===Z.EMISSIVE){const s=this.getFloat("emissiveIntensity"),o=this.getColor(n).mul(s);t.emissiveMap&&t.emissiveMap.isTexture===!0?i=o.mul(this.getTexture(n)):i=o}else if(n===Z.NORMAL)t.normalMap?(i=Og(this.getTexture("normal"),this.getCache("normalScale","vec2")),i.normalMapType=t.normalMapType,(t.normalMap.format==Fn||t.normalMap.format==wr||t.normalMap.format==Rr)&&(i.unpackNormalMode=vx)):t.bumpMap?i=E1(this.getTexture("bump").r,this.getFloat("bumpScale")):i=_t;else if(n===Z.CLEARCOAT){const s=this.getFloat(n);t.clearcoatMap&&t.clearcoatMap.isTexture===!0?i=s.mul(this.getTexture(n).r):i=s}else if(n===Z.CLEARCOAT_ROUGHNESS){const s=this.getFloat(n);t.clearcoatRoughnessMap&&t.clearcoatRoughnessMap.isTexture===!0?i=s.mul(this.getTexture(n).r):i=s}else if(n===Z.CLEARCOAT_NORMAL)t.clearcoatNormalMap?i=Og(this.getTexture(n),this.getCache(n+"Scale","vec2")):i=_t;else if(n===Z.SHEEN){const s=this.getColor("sheenColor").mul(this.getFloat("sheen"));t.sheenColorMap&&t.sheenColorMap.isTexture===!0?i=s.mul(this.getTexture("sheenColor").rgb):i=s}else if(n===Z.SHEEN_ROUGHNESS){const s=this.getFloat(n);t.sheenRoughnessMap&&t.sheenRoughnessMap.isTexture===!0?i=s.mul(this.getTexture(n).a):i=s,i=i.clamp(1e-4,1)}else if(n===Z.ANISOTROPY)if(t.anisotropyMap&&t.anisotropyMap.isTexture===!0){const s=this.getTexture(n);i=wp(ll.x,ll.y,ll.y.negate(),ll.x).mul(s.rg.mul(2).sub(Ie(1)).normalize().mul(s.b))}else i=ll;else if(n===Z.IRIDESCENCE_THICKNESS){const s=Qt("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const o=Qt("0","float",t.iridescenceThicknessRange);i=s.sub(o).mul(this.getTexture(n).g).add(o)}else i=s}else if(n===Z.TRANSMISSION){const s=this.getFloat(n);t.transmissionMap?i=s.mul(this.getTexture(n).r):i=s}else if(n===Z.THICKNESS){const s=this.getFloat(n);t.thicknessMap?i=s.mul(this.getTexture(n).g):i=s}else if(n===Z.IOR)i=this.getFloat(n);else if(n===Z.LIGHT_MAP)i=this.getTexture(n).rgb.mul(this.getFloat("lightMapIntensity"));else if(n===Z.AO)i=this.getTexture(n).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1);else if(n===Z.LINE_DASH_OFFSET)i=t.dashOffset?this.getFloat(n):j(0);else{const s=this.getNodeType(e);i=this.getCache(n,s)}return i}}Z.ALPHA_TEST="alphaTest";Z.COLOR="color";Z.OPACITY="opacity";Z.SHININESS="shininess";Z.SPECULAR="specular";Z.SPECULAR_STRENGTH="specularStrength";Z.SPECULAR_INTENSITY="specularIntensity";Z.SPECULAR_COLOR="specularColor";Z.REFLECTIVITY="reflectivity";Z.ROUGHNESS="roughness";Z.METALNESS="metalness";Z.NORMAL="normal";Z.CLEARCOAT="clearcoat";Z.CLEARCOAT_ROUGHNESS="clearcoatRoughness";Z.CLEARCOAT_NORMAL="clearcoatNormal";Z.EMISSIVE="emissive";Z.ROTATION="rotation";Z.SHEEN="sheen";Z.SHEEN_ROUGHNESS="sheenRoughness";Z.ANISOTROPY="anisotropy";Z.IRIDESCENCE="iridescence";Z.IRIDESCENCE_IOR="iridescenceIOR";Z.IRIDESCENCE_THICKNESS="iridescenceThickness";Z.IOR="ior";Z.TRANSMISSION="transmission";Z.THICKNESS="thickness";Z.ATTENUATION_DISTANCE="attenuationDistance";Z.ATTENUATION_COLOR="attenuationColor";Z.LINE_SCALE="scale";Z.LINE_DASH_SIZE="dashSize";Z.LINE_GAP_SIZE="gapSize";Z.LINE_WIDTH="linewidth";Z.LINE_DASH_OFFSET="dashOffset";Z.POINT_SIZE="size";Z.DISPERSION="dispersion";Z.LIGHT_MAP="light";Z.AO="ao";const A1=ge(Z,Z.ALPHA_TEST),R1=ge(Z,Z.COLOR),w1=ge(Z,Z.SHININESS),C1=ge(Z,Z.EMISSIVE),py=ge(Z,Z.OPACITY),N1=ge(Z,Z.SPECULAR),Gg=ge(Z,Z.SPECULAR_INTENSITY),P1=ge(Z,Z.SPECULAR_COLOR),wu=ge(Z,Z.SPECULAR_STRENGTH),gd=ge(Z,Z.REFLECTIVITY),D1=ge(Z,Z.ROUGHNESS),L1=ge(Z,Z.METALNESS),U1=ge(Z,Z.NORMAL),F1=ge(Z,Z.CLEARCOAT),I1=ge(Z,Z.CLEARCOAT_ROUGHNESS),B1=ge(Z,Z.CLEARCOAT_NORMAL),O1=ge(Z,Z.ROTATION),k1=ge(Z,Z.SHEEN),G1=ge(Z,Z.SHEEN_ROUGHNESS),V1=ge(Z,Z.ANISOTROPY),z1=ge(Z,Z.IRIDESCENCE),H1=ge(Z,Z.IRIDESCENCE_IOR),W1=ge(Z,Z.IRIDESCENCE_THICKNESS),$1=ge(Z,Z.TRANSMISSION),X1=ge(Z,Z.THICKNESS),q1=ge(Z,Z.IOR),j1=ge(Z,Z.ATTENUATION_DISTANCE),Y1=ge(Z,Z.ATTENUATION_COLOR),K1=ge(Z,Z.LINE_SCALE),Z1=ge(Z,Z.LINE_DASH_SIZE),Q1=ge(Z,Z.LINE_GAP_SIZE);Z.LINE_WIDTH;const J1=ge(Z,Z.LINE_DASH_OFFSET),eP=ge(Z,Z.POINT_SIZE),tP=ge(Z,Z.DISPERSION),my=ge(Z,Z.LIGHT_MAP),nP=ge(Z,Z.AO),ll=We(new de).onReference(function(r){return r.material}).onRenderUpdate(function({material:r}){this.value.set(r.anisotropy*Math.cos(r.anisotropyRotation),r.anisotropy*Math.sin(r.anisotropyRotation))}),iP=Q(r=>r.context.setupModelViewProjection(),"vec4").once()().toVarying("v_modelViewProjection");class sP extends $a{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 e.isAvailable("storageBuffer")===!1&&this.node.isPBO===!0&&e.setupPBO(this.node),super.setup(e)}generate(e,t){let n;const i=e.context.assign;if(e.isAvailable("storageBuffer")===!1?this.node.isPBO===!0&&i!==!0&&(this.node.value.isInstancedBufferAttribute||e.shaderStage!=="compute")?n=e.generatePBO(this):n=this.node.build(e):n=super.generate(e),i!==!0){const s=this.getNodeType(e);n=e.format(n,s,t)}return n}}const rP=Ft(sP).setParameterLength(2);class oP extends kp{static get type(){return"StorageBufferNode"}constructor(e,t=null,n=0){let i,s=null;t&&t.isStruct?(i="struct",s=t.layout,(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(n=e.count)):t===null&&(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)?(i=d0(e.itemSize),n=e.count):i=t,super(e,i,n),this.isStorageBufferNode=!0,this.structTypeNode=s,this.access=Ni.READ_WRITE,this.isAtomic=!1,this.isPBO=!1,this._attribute=null,this._varying=null,this.global=!0,e.isStorageBufferAttribute!==!0&&e.isStorageInstancedBufferAttribute!==!0&&(e.isInstancedBufferAttribute?e.isStorageInstancedBufferAttribute=!0:e.isStorageBufferAttribute=!0)}getHash(e){let t;if(this.bufferCount===0){let n=e.globalCache.getData(this.value);n===void 0&&(n={node:this},e.globalCache.setData(this.value,n)),t=n.node.id}else t=this.id;return String(t)}getInputType(){return this.value.isIndirectStorageBufferAttribute?"indirectStorageBuffer":"storageBuffer"}element(e){return rP(this,e)}setPBO(e){return this.isPBO=e,this}getPBO(){return this.isPBO}setAccess(e){return this.access=e,this}toReadOnly(){return this.setAccess(Ni.READ_ONLY)}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getAttributeData(){return this._attribute===null&&(this._attribute=$0(this.value),this._varying=bo(this._attribute)),{attribute:this._attribute,varying:this._varying}}generateNodeType(e){if(this.structTypeNode!==null)return this.structTypeNode.getNodeType(e);if(e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.generateNodeType(e);const{attribute:t}=this.getAttributeData();return t.getNodeType(e)}getMemberType(e,t){return this.structTypeNode!==null?this.structTypeNode.getMemberType(e,t):"void"}generate(e){if(this.structTypeNode!==null&&this.structTypeNode.build(e),e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.generate(e);const{attribute:t,varying:n}=this.getAttributeData(),i=n.build(e);return e.registerTransform(i,t),i}}const Vg=(r,e=null,t=0)=>new oP(r,e,t);class aP extends Oe{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=je.FRAME,this.buffer=null,this.bufferColor=null,this.previousInstanceMatrixNode=null}get isStorageMatrix(){const{instanceMatrix:e}=this;return e&&e.isStorageInstancedBufferAttribute===!0}get isStorageColor(){const{instanceColor:e}=this;return e&&e.isStorageInstancedBufferAttribute===!0}setup(e){let{instanceMatrixNode:t,instanceColorNode:n}=this;t===null&&(t=this._createInstanceMatrixNode(!0,e),this.instanceMatrixNode=t);const{instanceColor:i,isStorageColor:s}=this;if(i&&n===null){if(s)n=Vg(i,"vec3",Math.max(i.count,1)).element(sa);else{const a=new YS(i.array,3),l=i.usage===Nu?Pg:Ng;this.bufferColor=a,n=K(l(a,"vec3",3,0))}this.instanceColorNode=n}const o=t.mul(bn).xyz;if(bn.assign(o),e.needsPreviousData()&&Gu.assign(this.getPreviousInstancedPosition(e)),e.hasGeometryAttribute("normal")){const a=n1(bs,t);bs.assign(a)}this.instanceColorNode!==null&&ku("vec3","vInstanceColor").assign(this.instanceColorNode)}update(e){this.buffer!==null&&this.isStorageMatrix!==!0&&(this.buffer.clearUpdateRanges(),this.buffer.updateRanges.push(...this.instanceMatrix.updateRanges),this.instanceMatrix.version!==this.buffer.version&&(this.buffer.version=this.instanceMatrix.version)),this.instanceColor&&this.bufferColor!==null&&this.isStorageColor!==!0&&(this.bufferColor.clearUpdateRanges(),this.bufferColor.updateRanges.push(...this.instanceColor.updateRanges),this.instanceColor.version!==this.bufferColor.version&&(this.bufferColor.version=this.instanceColor.version)),this.previousInstanceMatrixNode!==null&&e.object.previousInstanceMatrix.array.set(this.instanceMatrix.array)}getPreviousInstancedPosition(e){const t=e.object;return this.previousInstanceMatrixNode===null&&(t.previousInstanceMatrix=this.instanceMatrix.clone(),this.previousInstanceMatrixNode=this._createInstanceMatrixNode(!1,e)),this.previousInstanceMatrixNode.mul(Gu).xyz}_createInstanceMatrixNode(e,t){let n;const{instanceMatrix:i}=this,{count:s}=i;if(this.isStorageMatrix)n=Vg(i,"mat4",Math.max(s,1)).element(sa);else if(s*16*4<=t.getUniformBufferLimit())n=Q0(i.array,"mat4",Math.max(s,1)).element(sa);else{const a=new zb(i.array,16,1);e===!0&&(this.buffer=a);const l=i.usage===Nu?Pg:Ng,c=[l(a,"vec4",16,0),l(a,"vec4",16,4),l(a,"vec4",16,8),l(a,"vec4",16,12)];n=eo(...c)}return n}}class lP extends aP{static get type(){return"InstancedMeshNode"}constructor(e){const{count:t,instanceMatrix:n,instanceColor:i}=e;super(t,n,i),this.instancedMesh=e}}const cP=Ft(lP).setParameterLength(1);class uP extends Oe{static get type(){return"BatchNode"}constructor(e){super("void"),this.batchMesh=e,this.batchingIdNode=null}setup(e){this.batchingIdNode===null&&(e.getDrawIndex()===null?this.batchingIdNode=sa:this.batchingIdNode=TN);const n=Q(([p])=>{const g=Kt(ra(Ai(this.batchMesh._indirectTexture),0).x).toConst(),m=Kt(p).mod(g).toConst(),_=Kt(p).div(g).toConst();return Ai(this.batchMesh._indirectTexture,ls(m,_)).x}).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]})(Kt(this.batchingIdNode)),i=this.batchMesh._matricesTexture,s=Kt(ra(Ai(i),0).x).toConst(),o=j(n).mul(4).toInt().toConst(),a=o.mod(s).toConst(),l=o.div(s).toConst(),c=eo(Ai(i,ls(a,l)),Ai(i,ls(a.add(1),l)),Ai(i,ls(a.add(2),l)),Ai(i,ls(a.add(3),l))),u=this.batchMesh._colorsTexture;if(u!==null){const g=Q(([m])=>{const _=Kt(ra(Ai(u),0).x).toConst(),x=m,v=x.mod(_).toConst(),S=x.div(_).toConst();return Ai(u,ls(v,S)).rgb}).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]})(n);ku("vec3","vBatchColor").assign(g)}const h=Bn(c);bn.assign(c.mul(bn));const d=bs.div(K(h[0].dot(h[0]),h[1].dot(h[1]),h[2].dot(h[2]))),f=h.mul(d).xyz;bs.assign(f),e.hasGeometryAttribute("tangent")&&Vu.mulAssign(h)}}const hP=Ft(uP).setParameterLength(1),zg=new WeakMap;class dP extends Oe{static get type(){return"SkinningNode"}constructor(e){super("void"),this.skinnedMesh=e,this.updateType=je.OBJECT,this.skinIndexNode=Nr("skinIndex","uvec4"),this.skinWeightNode=Nr("skinWeight","vec4"),this.bindMatrixNode=Qt("bindMatrix","mat4"),this.bindMatrixInverseNode=Qt("bindMatrixInverse","mat4"),this.boneMatricesNode=Fg("skeleton.boneMatrices","mat4",e.skeleton.bones.length),this.positionNode=bn,this.toPositionNode=bn,this.previousBoneMatricesNode=null}getSkinnedPosition(e=this.boneMatricesNode,t=this.positionNode){const{skinIndexNode:n,skinWeightNode:i,bindMatrixNode:s,bindMatrixInverseNode:o}=this,a=e.element(n.x),l=e.element(n.y),c=e.element(n.z),u=e.element(n.w),h=s.mul(t),d=hi(a.mul(i.x).mul(h),l.mul(i.y).mul(h),c.mul(i.z).mul(h),u.mul(i.w).mul(h));return o.mul(d).xyz}getSkinnedNormalAndTangent(e=this.boneMatricesNode,t=bs,n=Vu){const{skinIndexNode:i,skinWeightNode:s,bindMatrixNode:o,bindMatrixInverseNode:a}=this,l=e.element(i.x),c=e.element(i.y),u=e.element(i.z),h=e.element(i.w);let d=hi(s.x.mul(l),s.y.mul(c),s.z.mul(u),s.w.mul(h));d=a.mul(d).mul(o);const f=d.transformDirection(t).xyz,p=d.transformDirection(n).xyz;return{skinNormal:f,skinTangent:p}}getPreviousSkinnedPosition(e){const t=e.object;return this.previousBoneMatricesNode===null&&(t.skeleton.previousBoneMatrices=new Float32Array(t.skeleton.boneMatrices),this.previousBoneMatricesNode=Fg("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,Gu)}setup(e){e.needsPreviousData()&&Gu.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(this.toPositionNode&&this.toPositionNode.assign(t),e.hasGeometryAttribute("normal")){const{skinNormal:n,skinTangent:i}=this.getSkinnedNormalAndTangent();bs.assign(n),e.hasGeometryAttribute("tangent")&&Vu.assign(i)}return t}generate(e,t){if(t!=="void")return super.generate(e,t)}update(e){const t=e.object&&e.object.skeleton?e.object.skeleton:this.skinnedMesh.skeleton;zg.get(t)!==e.frameId&&(zg.set(t,e.frameId),this.previousBoneMatricesNode!==null&&(t.previousBoneMatrices===null&&(t.previousBoneMatrices=new Float32Array(t.boneMatrices)),t.previousBoneMatrices.set(t.boneMatrices)),t.update())}}const fP=r=>new dP(r);class pP extends Oe{static get type(){return"LoopNode"}constructor(e=[]){super("void"),this.params=e}getVarName(e){return String.fromCharCode(105+e)}getProperties(e){const t=e.getNodeProperties(this);if(t.stackNode!==void 0)return t;const n={};for(let a=0,l=this.params.length-1;aNumber(h)?p=">=":p="<"));let m;if(c)m=`while ( ${h} )`;else{const _={start:u,end:h},x=_.start,v=_.end;let S;const E=()=>p.includes("<")?"+=":"-=";if(g!=null)switch(typeof g){case"function":S=e.flowStagesNode(t.updateNode,"void").code.replace(/\t|;/g,"");break;case"number":S=d+" "+E()+" "+e.generateConst(f,g);break;case"string":S=d+" "+g;break;default:g.isNode?S=d+" "+E()+" "+g.build(e):(ne("TSL: 'Loop( { update: ... } )' is not a function, string or number.",this.stackTrace),S="break /* invalid update */")}else f==="int"||f==="uint"?g=p.includes("<")?"++":"--":g=E()+" 1.",S=d+" "+g;const T=e.getVar(f,d)+" = "+x,A=d+" "+p+" "+v;m=`for ( ${T}; ${A}; ${S} )`}e.addFlowCode((o===0?` `:"")+e.tab+m+` { `).addFlowTab()}const s=i.build(e,"void");t.returnsNode.build(e,"void"),e.removeFlowTab().addFlowCode(` `+e.tab+s);for(let o=0,a=this.params.length-1;onew pP(ta(r,"int")).toStack(),mP=()=>hs("break").toStack(),_d=new WeakMap,_i=new tt,Hg=Q(({bufferMap:r,influence:e,stride:t,width:n,depth:i,offset:s})=>{const o=Kt(bN).mul(t).add(s),a=o.div(n),l=o.sub(a.mul(n));return Ai(r,ls(l,a)).depth(i).xyz.mul(e)});function gP(r){const e=r.morphAttributes.position!==void 0,t=r.morphAttributes.normal!==void 0,n=r.morphAttributes.color!==void 0,i=r.morphAttributes.position||r.morphAttributes.normal||r.morphAttributes.color,s=i!==void 0?i.length:0;let o=_d.get(r);if(o===void 0||o.count!==s){let _=function(){g.dispose(),_d.delete(r),r.removeEventListener("dispose",_)};o!==void 0&&o.texture.dispose();const a=r.morphAttributes.position||[],l=r.morphAttributes.normal||[],c=r.morphAttributes.color||[];let u=0;e===!0&&(u=1),t===!0&&(u=2),n===!0&&(u=3);let h=r.attributes.position.count*u,d=1;const f=4096;h>f&&(d=Math.ceil(h/f),h=f);const p=new Float32Array(h*d*4*s),g=new sp(p,h,d,s);g.type=Zt,g.needsUpdate=!0;const m=u*4;for(let x=0;x{const d=j(0).toVar();this.mesh.count>1&&this.mesh.morphTexture!==null&&this.mesh.morphTexture!==void 0?d.assign(Ai(this.mesh.morphTexture,ls(Kt(h).add(1),Kt(sa))).r):d.assign(Qt("morphTargetInfluences","float").element(h).toVar()),Lt(d.notEqual(0),()=>{n===!0&&bn.addAssign(Hg({bufferMap:a,influence:d,stride:l,width:u,depth:h,offset:Kt(0)})),i===!0&&bs.addAssign(Hg({bufferMap:a,influence:d,stride:l,width:u,depth:h,offset:Kt(1)}))})})}update(){const e=this.morphBaseInfluence;this.mesh.geometry.morphTargetsRelative?e.value=1:e.value=1-this.mesh.morphTargetInfluences.reduce((t,n)=>t+n,0)}}const xP=Ft(_P).setParameterLength(1);class Ka extends Oe{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class yP extends Ka{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class vP extends V0{static get type(){return"LightingContextNode"}constructor(e,t=null,n=null,i=null){super(e),this.lightingModel=t,this.backdropNode=n,this.backdropAlphaNode=i,this._value=null}getContext(){const{backdropNode:e,backdropAlphaNode:t}=this,n=K().toVar("directDiffuse"),i=K().toVar("directSpecular"),s=K().toVar("indirectDiffuse"),o=K().toVar("indirectSpecular"),a={directDiffuse:n,directSpecular:i,indirectDiffuse:s,indirectSpecular:o};return{radiance:K().toVar("radiance"),irradiance:K().toVar("irradiance"),iblIrradiance:K().toVar("iblIrradiance"),ambientOcclusion:j(1).toVar("ambientOcclusion"),reflectedLight:a,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 SP=Ft(vP);class bP extends Ka{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}const Vr=new de;class gy extends pc{static get type(){return"ViewportTextureNode"}constructor(e=no,t=null,n=null){let i=null;n===null?(i=new Rx,i.minFilter=li,n=i):i=n,super(n,e,t),this.generateMipmaps=!1,this.defaultFramebuffer=i,this.isOutputTextureNode=!0,this.updateBeforeType=je.RENDER,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),e===null)return t;if(n.has(e)===!1){const i=t.clone();n.set(e,i)}return n.get(e)}updateReference(e){const t=e.renderer,n=t.getRenderTarget(),i=t.getCanvasTarget(),s=n||i;return this.value=this.getTextureForReference(s),this.value}updateBefore(e){const t=e.renderer,n=t.getRenderTarget(),i=t.getCanvasTarget(),s=n||i;s===null?t.getDrawingBufferSize(Vr):s.getDrawingBufferSize?s.getDrawingBufferSize(Vr):Vr.set(s.width,s.height);const o=this.getTextureForReference(s);(o.image.width!==Vr.width||o.image.height!==Vr.height)&&(o.image.width=Vr.width,o.image.height=Vr.height,o.needsUpdate=!0);const a=o.generateMipmaps;o.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(o),o.generateMipmaps=a}clone(){const e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}}const _y=Ft(gy,null,null,{generateMipmaps:!0}).setParameterLength(0,3),TP=_y(),MP=(r=no,e=null)=>TP.sample(r,e);let xd=null;class EP extends gy{static get type(){return"ViewportDepthTextureNode"}constructor(e=no,t=null,n=null){n===null&&(xd===null&&(xd=new Xn),n=xd),super(e,t,n)}}const AP=Ft(EP).setParameterLength(0,3);class ci extends Oe{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===ci.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,n=this.valueNode;let i=null;if(t===ci.DEPTH_BASE)n!==null&&(i=Sy().assign(n));else if(t===ci.DEPTH)e.isPerspectiveCamera?i=xy(hn.z,Yr,Kr):i=Dl(hn.z,Yr,Kr);else if(t===ci.LINEAR_DEPTH)if(n!==null)if(e.isPerspectiveCamera){const s=yy(n,Yr,Kr);i=Dl(s,Yr,Kr)}else i=n;else i=Dl(hn.z,Yr,Kr);return i}}ci.DEPTH_BASE="depthBase";ci.DEPTH="depth";ci.LINEAR_DEPTH="linearDepth";const Dl=(r,e,t)=>r.add(e).div(e.sub(t)),xy=(r,e,t)=>e.add(r).mul(t).div(t.sub(e).mul(r)),RP=(r,e,t)=>e.mul(r.add(t)).div(r.mul(e.sub(t))),yy=Q(([r,e,t],n)=>n.renderer.reversedDepthBuffer===!0?e.mul(t).div(e.sub(t).mul(r).sub(e)):e.mul(t).div(t.sub(e).mul(r).sub(t))),vy=(r,e,t)=>{e=e.max(1e-6).toVar();const n=Hs(r.negate().div(e)),i=Hs(t.div(e));return n.div(i)},Sy=Ft(ci,ci.DEPTH_BASE),by=ge(ci,ci.DEPTH),wP=Ft(ci,ci.LINEAR_DEPTH).setParameterLength(0,1);AP();by.assign=r=>Sy(r);class Di extends Oe{static get type(){return"ClippingNode"}constructor(e=Di.DEFAULT){super(),this.scope=e}setup(e){super.setup(e);const t=e.clippingContext,{intersectionPlanes:n,unionPlanes:i}=t;return this.hardwareClipping=e.material.hardwareClipping,this.scope===Di.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(n,i):this.scope===Di.HARDWARE?this.setupHardwareClipping(i,e):this.setupDefault(n,i)}setupAlphaToCoverage(e,t){return Q(()=>{const n=j().toVar("distanceToPlane"),i=j().toVar("distanceToGradient"),s=j(1).toVar("clipOpacity"),o=t.length;if(this.hardwareClipping===!1&&o>0){const l=Ri(t).setGroup(qe);wi(o,({i:c})=>{const u=l.element(c);n.assign(hn.dot(u.xyz).negate().add(u.w)),i.assign(n.fwidth().div(2)),s.mulAssign(Xs(i.negate(),i,n))})}const a=e.length;if(a>0){const l=Ri(e).setGroup(qe),c=j(1).toVar("intersectionClipOpacity");wi(a,({i:u})=>{const h=l.element(u);n.assign(hn.dot(h.xyz).negate().add(h.w)),i.assign(n.fwidth().div(2)),c.mulAssign(Xs(i.negate(),i,n).oneMinus())}),s.mulAssign(c.oneMinus())}Ct.a.mulAssign(s),Ct.a.equal(0).discard()})()}setupDefault(e,t){return Q(()=>{const n=t.length;if(this.hardwareClipping===!1&&n>0){const s=Ri(t).setGroup(qe);wi(n,({i:o})=>{const a=s.element(o);hn.dot(a.xyz).greaterThan(a.w).discard()})}const i=e.length;if(i>0){const s=Ri(e).setGroup(qe),o=rh(!0).toVar("clipped");wi(i,({i:a})=>{const l=s.element(a);o.assign(hn.dot(l.xyz).greaterThan(l.w).and(o))}),o.discard()}})()}setupHardwareClipping(e,t){const n=e.length;return t.enableHardwareClipping(n),Q(()=>{const i=Ri(e).setGroup(qe),s=qa(t.getClipDistance());wi(n,({i:o})=>{const a=i.element(o),l=hn.dot(a.xyz).sub(a.w).negate();s.element(o).assign(l)})})()}}Di.ALPHA_TO_COVERAGE="alphaToCoverage";Di.DEFAULT="default";Di.HARDWARE="hardware";const CP=()=>new Di,NP=()=>new Di(Di.ALPHA_TO_COVERAGE),PP=()=>new Di(Di.HARDWARE),DP=.05,Wg=Q(([r])=>Ss(nt(1e4,xi(nt(17,r.x).add(nt(.1,r.y)))).mul(hi(.1,yi(xi(nt(13,r.y).add(r.x))))))),$g=Q(([r])=>Wg(Ie(Wg(r.xy),r.z))),LP=Q(([r])=>{const e=On(Ws(U0(r.xyz)),Ws(F0(r.xyz))),t=j(1).div(j(DP).mul(e)).toVar("pixScale"),n=Ie(Zl(to(Hs(t))),Zl(Lp(Hs(t)))),i=Ie($g(to(n.x.mul(r.xyz))),$g(to(n.y.mul(r.xyz)))),s=Ss(Hs(t)),o=hi(nt(s.oneMinus(),i.x),nt(s,i.y)),a=Ua(s,s.oneMinus()),l=K(o.mul(o).div(nt(2,a).mul(si(1,a))),o.sub(nt(.5,a)).div(si(1,a)),si(1,si(1,o).mul(si(1,o)).div(nt(2,a).mul(si(1,a))))),c=o.lessThan(a.oneMinus()).select(o.lessThan(a).select(l.x,l.y),l.z);return Cr(c,1e-6,1)}).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class UP extends K0{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),n=e.hasGeometryAttribute(t);let i;return n===!0?i=super.generate(e):i=e.generateConst(this.nodeType,new tt(1,1,1,1)),i}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const FP=(r=0)=>new UP(r),IP=Q(([r])=>Ze(r.rgb.mul(r.a),r.a),{color:"vec4",return:"vec4"});class dn extends qn{static get type(){return"NodeMaterial"}get type(){return this.constructor.type}set type(e){}constructor(){super(),this.isNodeMaterial=!0,this.fog=!0,this.lights=!1,this.hardwareClipping=!1,this.lightsNode=null,this.envNode=null,this.aoNode=null,this.colorNode=null,this.normalNode=null,this.opacityNode=null,this.backdropNode=null,this.backdropAlphaNode=null,this.alphaTestNode=null,this.maskNode=null,this.maskShadowNode=null,this.positionNode=null,this.geometryNode=null,this.depthNode=null,this.receivedShadowPositionNode=null,this.castShadowPositionNode=null,this.receivedShadowNode=null,this.castShadowNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null,this.contextNode=null}_getNodeChildren(){const e=[];for(const t of Object.getOwnPropertyNames(this)){if(t.startsWith("_")===!0)continue;const n=this[t];n&&n.isNode===!0&&e.push({property:t,childNode:n})}return e}customProgramCacheKey(){const e=[];for(const{property:t,childNode:n}of this._getNodeChildren())e.push(Ha(t.slice(0,-4)),n.getCacheKey());return this.type+dc(e)}build(e){this.setup(e)}setupObserver(e){return new uw(e)}setup(e){e.context.setupNormal=()=>ia(this.setupNormal(e),"NORMAL","vec3"),e.context.setupPositionView=()=>this.setupPositionView(e),e.context.setupModelViewProjection=()=>this.setupModelViewProjection(e);const t=e.renderer,n=t.getRenderTarget();e.addStack();const i=this.setupVertex(e),s=ia(this.vertexNode||i,"VERTEX");e.context.clipSpace=s,e.stack.outputNode=s,this.setupHardwareClipping(e),this.geometryNode!==null&&(e.stack.outputNode=e.stack.outputNode.bypass(this.geometryNode)),e.addFlow("vertex",e.removeStack()),e.addStack();let o;const a=this.setupClipping(e);if((this.depthWrite===!0||this.depthTest===!0)&&(n!==null?n.depthBuffer===!0&&this.setupDepth(e):t.depth===!0&&this.setupDepth(e)),this.fragmentNode===null){this.setupDiffuseColor(e),this.setupVariants(e);const l=this.setupLighting(e);a!==null&&e.stack.addToStack(a);const c=Ze(l,Ct.a).max(0);o=this.setupOutput(e,c),Cl.assign(o);const u=this.outputNode!==null;if(u&&(o=this.outputNode),e.context.getOutput&&(o=e.context.getOutput(o,e)),n!==null){const h=t.getMRT(),d=this.mrtNode;h!==null?(u&&Cl.assign(o),o=h,d!==null&&(o=h.merge(d))):d!==null&&(o=d)}}else{let l=this.fragmentNode;l.isOutputStructNode!==!0&&(l=Ze(l)),o=this.setupOutput(e,l)}e.stack.outputNode=o,e.addFlow("fragment",e.removeStack()),e.observer=this.setupObserver(e)}setupClipping(e){if(e.clippingContext===null)return null;const{unionPlanes:t,intersectionPlanes:n}=e.clippingContext;let i=null;if(t.length>0||n.length>0){const s=e.renderer.currentSamples;this.alphaToCoverage&&s>1?i=NP():e.stack.addToStack(CP())}return i}setupHardwareClipping(e){if(this.hardwareClipping=!1,e.clippingContext===null)return;const t=e.clippingContext.unionPlanes.length;t>0&&t<=8&&e.isAvailable("clipDistance")&&(e.stack.addToStack(PP()),this.hardwareClipping=!0)}setupDepth(e){const{renderer:t,camera:n}=e;let i=this.depthNode;if(i===null){const s=t.getMRT();s&&s.has("depth")?i=s.get("depth"):t.logarithmicDepthBuffer===!0&&(n.isPerspectiveCamera?i=vy(hn.z,Yr,Kr):i=Dl(hn.z,Yr,Kr))}i!==null&&by.assign(i).toStack()}setupPositionView(){return mc.mul(bn).xyz}setupModelViewProjection(){return Pl.mul(hn)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.position=e.removeStack(),iP}setupPosition(e){const{object:t,geometry:n}=e;if((n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color)&&xP(t).toStack(),t.isSkinnedMesh===!0&&fP(t).toStack(),this.displacementMap){const i=cr("displacementMap","texture"),s=cr("displacementScale","float"),o=cr("displacementBias","float");bn.addAssign(bs.normalize().mul(i.x.mul(s).add(o)))}return t.isBatchedMesh&&hP(t).toStack(),t.isInstancedMesh&&t.instanceMatrix&&t.instanceMatrix.isInstancedBufferAttribute===!0&&cP(t).toStack(),this.positionNode!==null&&bn.assign(ia(this.positionNode,"POSITION","vec3")),bn}setupDiffuseColor(e){const{object:t,geometry:n}=e;this.maskNode!==null&&rh(this.maskNode).not().discard();let i=this.colorNode?Ze(this.colorNode):R1;this.vertexColors===!0&&n.hasAttribute("color")&&(i=i.mul(FP())),t.instanceColor&&(i=ku("vec3","vInstanceColor").mul(i)),t.isBatchedMesh&&t._colorsTexture&&(i=ku("vec3","vBatchColor").mul(i)),Ct.assign(i);const s=this.opacityNode?j(this.opacityNode):py;Ct.a.assign(Ct.a.mul(s));let o=null;(this.alphaTestNode!==null||this.alphaTest>0)&&(o=this.alphaTestNode!==null?j(this.alphaTestNode):A1,this.alphaToCoverage===!0?(Ct.a=Xs(o,o.add(I0(Ct.a)),Ct.a),Ct.a.lessThanEqual(0).discard()):Ct.a.lessThanEqual(o).discard()),this.alphaHash===!0&&Ct.a.lessThan(LP(bn)).discard(),e.isOpaque()&&Ct.a.assign(1)}setupVariants(){}setupOutgoingLight(){return this.lights===!0?K(0):Ct.rgb}setupNormal(){return this.normalNode?K(this.normalNode):U1}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?cr("envMap","cubeTexture"):cr("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new bP(my)),t}setupLights(e){const t=[],n=this.setupEnvironment(e);n&&n.isLightingNode&&t.push(n);const i=this.setupLightMap(e);i&&i.isLightingNode&&t.push(i);let s=this.aoNode;s===null&&e.material.aoMap&&(s=nP),e.context.getAO&&(s=e.context.getAO(s,e)),s&&t.push(new yP(s));let o=this.lightsNode||e.lightsNode;return t.length>0&&(o=e.renderer.lighting.createNode([...o.getLights(),...t])),o}setupLightingModel(){}setupLighting(e){const{material:t}=e,{backdropNode:n,backdropAlphaNode:i,emissiveNode:s}=this,a=this.lights===!0||this.lightsNode!==null?this.setupLights(e):null;let l=this.setupOutgoingLight(e);if(a&&a.getScope().hasLights){const c=this.setupLightingModel(e)||null;l=SP(a,c,n,i)}else n!==null&&(l=K(i!==null?Nt(l,n,i):n));return(s&&s.isNode===!0||t.emissive&&t.emissive.isColor===!0)&&(Eg.assign(K(s||C1)),l=l.add(Eg)),l}setupFog(e,t){const n=e.fogNode;return n&&(Cl.assign(t),t=Ze(n.toVar())),t}setupPremultipliedAlpha(e,t){return IP(t)}setupOutput(e,t){return this.fog===!0&&(t=this.setupFog(e,t)),this.premultipliedAlpha===!0&&(t=this.setupPremultipliedAlpha(e,t)),t}setDefaultValues(e){for(const n in e){const i=e[n];this[n]===void 0&&(this[n]=i,i&&i.clone&&(this[n]=i.clone()))}const t=Object.getOwnPropertyDescriptors(e.constructor.prototype);for(const n in t)Object.getOwnPropertyDescriptor(this.constructor.prototype,n)===void 0&&t[n].get!==void 0&&Object.defineProperty(this.constructor.prototype,n,t[n])}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{},nodes:{}});const n=qn.prototype.toJSON.call(this,e);n.inputNodes={};for(const{property:s,childNode:o}of this._getNodeChildren())n.inputNodes[s]=o.toJSON(e).uuid;function i(s){const o=[];for(const a in s){const l=s[a];delete l.metadata,o.push(l)}return o}if(t){const s=i(e.textures),o=i(e.images),a=i(e.nodes);s.length>0&&(n.textures=s),o.length>0&&(n.images=o),a.length>0&&(n.nodes=a)}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.maskShadowNode=e.maskShadowNode,this.positionNode=e.positionNode,this.geometryNode=e.geometryNode,this.depthNode=e.depthNode,this.receivedShadowPositionNode=e.receivedShadowPositionNode,this.castShadowPositionNode=e.castShadowPositionNode,this.receivedShadowNode=e.receivedShadowNode,this.castShadowNode=e.castShadowNode,this.outputNode=e.outputNode,this.mrtNode=e.mrtNode,this.fragmentNode=e.fragmentNode,this.vertexNode=e.vertexNode,this.contextNode=e.contextNode,super.copy(e)}}const BP=new Qu;class OP extends dn{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(BP),this.setValues(e)}}const kP=new wb;class GP extends dn{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(kP),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?j(this.offsetNode):J1,t=this.dashScaleNode?j(this.dashScaleNode):K1,n=this.dashSizeNode?j(this.dashSizeNode):Z1,i=this.gapSizeNode?j(this.gapSizeNode):Q1;cd.assign(n),Ag.assign(i);const s=bo(Nr("lineDistance").mul(t));(e?s.add(e):s).mod(cd.add(Ag)).greaterThan(cd).discard()}}const VP=new Mb;class zP extends dn{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(VP),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?j(this.opacityNode):py;Ct.assign(Bp(Ze(v1(_t),e),Qn))}}const Ty=Q(([r=ey])=>{const e=r.z.atan(r.x).mul(1/(Math.PI*2)).add(.5),t=r.y.clamp(-1,1).asin().mul(1/Math.PI).add(.5);return Ie(e,t)});class My extends Lr{constructor(e=1,t={}){super(e,e,t),this.isCubeRenderTarget=!0;const n={width:e,height:e,depth:1},i=[n,n,n,n,n,n];this.texture=new Ga(i),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){const n=t.minFilter,i=t.generateMipmaps;t.generateMipmaps=!0,this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const s=new yo(5,5,5),o=Ty(ey),a=new dn;a.colorNode=Gt(t,o,0),a.side=Pt,a.blending=Cn;const l=new gn(s,a),c=new op;c.add(l),t.minFilter===li&&(t.minFilter=Ut);const u=new kx(1,10,this),h=e.getMRT();return e.setMRT(null),u.update(e,c),e.setMRT(h),t.minFilter=n,t.generateMipmaps=i,l.geometry.dispose(),l.material.dispose(),this}clear(e,t=!0,n=!0,i=!0){const s=e.getRenderTarget();for(let o=0;o<6;o++)e.setRenderTarget(this,o),e.clear(t,n,i);e.setRenderTarget(s)}}const Ll=new WeakMap;class HP extends _n{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=oi(null);const t=new Ga;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=je.RENDER}updateBefore(e){const{renderer:t,material:n}=e,i=this.envNode;if(i.isTextureNode||i.isMaterialReferenceNode){const s=i.isTextureNode?i.value:n[i.property];if(s&&s.isTexture){const o=s.mapping;if(o===Ko||o===Zo){if(Ll.has(s)){const a=Ll.get(s);Xg(a,s.mapping),this._cubeTexture=a}else{const a=s.image;if(WP(a)){const l=new My(a.height);l.fromEquirectangularTexture(t,s),Xg(l.texture,s.mapping),this._cubeTexture=l.texture,Ll.set(s,l.texture),s.addEventListener("dispose",Ey)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function WP(r){return r==null?!1:r.height>0}function Ey(r){const e=r.target;e.removeEventListener("dispose",Ey);const t=Ll.get(e);t!==void 0&&(Ll.delete(e),t.dispose())}function Xg(r,e){e===Ko?r.mapping=Xi:e===Zo&&(r.mapping=_s)}const Ay=Ft(HP).setParameterLength(1);class Vp extends Ka{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=Ay(this.envNode)}}class $P extends Ka{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=j(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class ch{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class Ry extends ch{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,n=e.reflectedLight,i=e.irradianceLightMap;n.indirectDiffuse.assign(Ze(0)),i?n.indirectDiffuse.addAssign(i):n.indirectDiffuse.addAssign(Ze(1,1,1,0)),n.indirectDiffuse.mulAssign(t),n.indirectDiffuse.mulAssign(Ct.rgb)}finish(e){const{material:t,context:n}=e,i=n.outgoingLight,s=e.context.environment;if(s)switch(t.combine){case nc:i.rgb.assign(Nt(i.rgb,i.rgb.mul(s.rgb),wu.mul(gd)));break;case mx:i.rgb.assign(Nt(i.rgb,s.rgb,wu.mul(gd)));break;case gx:i.rgb.addAssign(s.rgb.mul(wu.mul(gd)));break;default:ee("BasicLightingModel: Unsupported .combine value:",t.combine);break}}}const XP=new us;class qP extends dn{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(XP),this.setValues(e)}setupNormal(){return gc(Jl)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Vp(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new $P(my)),t}setupOutgoingLight(){return Ct.rgb}setupLightingModel(){return new Ry}}const ec=Q(({f0:r,f90:e,dotVH:t})=>{const n=t.mul(-5.55473).sub(6.98316).mul(t).exp2();return r.mul(n.oneMinus()).add(e.mul(n))}),Ia=Q(r=>r.diffuseColor.mul(1/Math.PI)),jP=()=>j(.25),YP=Q(({dotNH:r})=>yf.mul(j(.5)).add(1).mul(j(1/Math.PI)).mul(r.pow(yf))),KP=Q(({lightDirection:r})=>{const e=r.add(Wt).normalize(),t=_t.dot(e).clamp(),n=Wt.dot(e).clamp(),i=ec({f0:co,f90:1,dotVH:n}),s=jP(),o=YP({dotNH:t});return i.mul(s).mul(o)});class wy extends Ry{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:n}){const s=_t.dot(e).clamp().mul(t);n.directDiffuse.addAssign(s.mul(Ia({diffuseColor:Ct.rgb}))),this.specular===!0&&n.directSpecular.addAssign(s.mul(KP({lightDirection:e})).mul(wu))}indirect(e){const{ambientOcclusion:t,irradiance:n,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(n.mul(Ia({diffuseColor:Ct}))),i.indirectDiffuse.mulAssign(t)}}const ZP=new Fx;class QP extends dn{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(ZP),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Vp(t):null}setupLightingModel(){return new wy(!1)}}const JP=new bb;class eD extends dn{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(JP),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Vp(t):null}setupLightingModel(){return new wy}setupVariants(){const e=(this.shininessNode?j(this.shininessNode):w1).max(1e-4);yf.assign(e);const t=this.specularNode||N1;co.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}const tD=Q(r=>{if(r.geometry.hasAttribute("normal")===!1)return j(0);const e=Jl.dFdx().abs().max(Jl.dFdy().abs());return e.x.max(e.y).max(e.z)}),Cy=Q(r=>{const{roughness:e}=r,t=tD();let n=e.max(.0525);return n=n.add(t),n=n.min(1),n}),nD=Q(({alpha:r,dotNL:e,dotNV:t})=>{const n=r.pow2(),i=e.mul(n.add(n.oneMinus().mul(t.pow2())).sqrt()),s=t.mul(n.add(n.oneMinus().mul(e.pow2())).sqrt());return vs(.5,i.add(s).max(Dp))}).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),iD=Q(({alphaT:r,alphaB:e,dotTV:t,dotBV:n,dotTL:i,dotBL:s,dotNV:o,dotNL:a})=>{const l=a.mul(K(r.mul(t),e.mul(n),o).length()),c=o.mul(K(r.mul(i),e.mul(s),a).length());return vs(.5,l.add(c).max(Dp))}).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"}]}),sD=Q(({alpha:r,dotNH:e})=>{const t=r.pow2(),n=e.pow2().mul(t.oneMinus()).oneMinus();return t.div(n.pow2()).mul(1/Math.PI)}).setLayout({name:"D_GGX",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNH",type:"float"}]}),rD=j(1/Math.PI),oD=Q(({alphaT:r,alphaB:e,dotNH:t,dotTH:n,dotBH:i})=>{const s=r.mul(e),o=K(e.mul(n),r.mul(i),s.mul(t)),a=o.dot(o),l=s.div(a);return rD.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"}]}),Ny=Q(({lightDirection:r,f0:e,f90:t,roughness:n,f:i,normalView:s=_t,USE_IRIDESCENCE:o,USE_ANISOTROPY:a})=>{const l=n.pow2(),c=r.add(Wt).normalize(),u=s.dot(r).clamp(),h=s.dot(Wt).clamp(),d=s.dot(c).clamp(),f=Wt.dot(c).clamp();let p=ec({f0:e,f90:t,dotVH:f}),g,m;if(pf(o)&&(p=Cp.mix(p,i)),pf(a)){const _=Mu.dot(r),x=Mu.dot(Wt),v=Mu.dot(c),S=na.dot(r),E=na.dot(Wt),T=na.dot(c);g=iD({alphaT:xf,alphaB:l,dotTV:x,dotBV:E,dotTL:_,dotBL:S,dotNV:h,dotNL:u}),m=oD({alphaT:xf,alphaB:l,dotNH:d,dotTH:v,dotBH:T})}else g=nD({alpha:l,dotNL:u,dotNV:h}),m=sD({alpha:l,dotNH:d});return p.mul(g).mul(m)}),aD=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 ns=null;const zu=Q(({roughness:r,dotNV:e})=>{ns===null&&(ns=new up(aD,16,16,Fn,en),ns.name="DFG_LUT",ns.minFilter=Ut,ns.magFilter=Ut,ns.wrapS=ai,ns.wrapT=ai,ns.generateMipmaps=!1,ns.needsUpdate=!0);const t=Ie(r,e);return Gt(ns,t).rg}),lD=Q(({lightDirection:r,f0:e,f90:t,roughness:n,f:i,USE_IRIDESCENCE:s,USE_ANISOTROPY:o})=>{const a=Ny({lightDirection:r,f0:e,f90:t,roughness:n,f:i,USE_IRIDESCENCE:s,USE_ANISOTROPY:o}),l=_t.dot(r).clamp(),c=_t.dot(Wt).clamp(),u=zu({roughness:n,dotNV:c}),h=zu({roughness:n,dotNV:l}),d=e.mul(u.x).add(t.mul(u.y)),f=e.mul(h.x).add(t.mul(h.y)),p=u.x.add(u.y),g=h.x.add(h.y),m=j(1).sub(p),_=j(1).sub(g),x=e.add(e.oneMinus().mul(.047619)),v=d.mul(f).mul(x).div(j(1).sub(m.mul(_).mul(x).mul(x)).add(Dp)),S=m.mul(_),E=v.mul(S);return a.add(E)}),Py=Q(r=>{const{dotNV:e,specularColor:t,specularF90:n,roughness:i}=r,s=zu({dotNV:e,roughness:i});return t.mul(s.x).add(n.mul(s.y))}),qg=Q(({f:r,f90:e,dotVH:t})=>{const n=t.oneMinus().saturate(),i=n.mul(n),s=n.mul(i,i).clamp(0,.9999);return r.sub(K(e).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"}]}),cD=Q(({roughness:r,dotNH:e})=>{const t=r.pow2(),n=j(1).div(t),s=e.pow2().oneMinus().max(.0078125);return j(2).add(n).mul(s.pow(n.mul(.5))).div(2*Math.PI)}).setLayout({name:"D_Charlie",type:"float",inputs:[{name:"roughness",type:"float"},{name:"dotNH",type:"float"}]}),uD=Q(({dotNV:r,dotNL:e})=>j(1).div(j(4).mul(e.add(r).sub(e.mul(r))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),hD=Q(({lightDirection:r})=>{const e=r.add(Wt).normalize(),t=_t.dot(r).clamp(),n=_t.dot(Wt).clamp(),i=_t.dot(e).clamp(),s=cD({roughness:jr,dotNH:i}),o=uD({dotNV:n,dotNL:t});return Ei.mul(s).mul(o)}),jg=Q(({N:r,V:e,roughness:t})=>{const s=.0078125,o=r.dot(e).saturate(),a=Ie(t,o.oneMinus().sqrt());return a.assign(a.mul(.984375).add(s)),a}).setLayout({name:"LTC_Uv",type:"vec2",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"roughness",type:"float"}]}),dD=Q(({f:r})=>{const e=r.length();return On(e.mul(e).add(r.z).div(e.add(1)),0)}).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),Jc=Q(({v1:r,v2:e})=>{const t=r.dot(e),n=t.abs().toVar(),i=n.mul(.0145206).add(.4965155).mul(n).add(.8543985).toVar(),s=n.add(4.1616724).mul(n).add(3.417594).toVar(),o=i.div(s),a=t.greaterThan(0).select(o,On(t.mul(t).oneMinus(),1e-7).inverseSqrt().mul(.5).sub(o));return r.cross(e).mul(a)}).setLayout({name:"LTC_EdgeVectorFormFactor",type:"vec3",inputs:[{name:"v1",type:"vec3"},{name:"v2",type:"vec3"}]}),yd=Q(({N:r,V:e,P:t,mInv:n,p0:i,p1:s,p2:o,p3:a})=>{const l=s.sub(i).toVar(),c=a.sub(i).toVar(),u=l.cross(c),h=K().toVar();return Lt(u.dot(t.sub(i)).greaterThanEqual(0),()=>{const d=e.sub(r.mul(e.dot(r))).normalize(),f=r.cross(d).negate(),p=n.mul(Bn(d,f,r).transpose()).toVar(),g=p.mul(i.sub(t)).normalize().toVar(),m=p.mul(s.sub(t)).normalize().toVar(),_=p.mul(o.sub(t)).normalize().toVar(),x=p.mul(a.sub(t)).normalize().toVar(),v=K(0).toVar();v.addAssign(Jc({v1:g,v2:m})),v.addAssign(Jc({v1:m,v2:_})),v.addAssign(Jc({v1:_,v2:x})),v.addAssign(Jc({v1:x,v2:g})),h.assign(K(dD({f:v})))}),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"}]}),uh=1/6,Dy=r=>nt(uh,nt(r,nt(r,r.negate().add(3)).sub(3)).add(1)),Mf=r=>nt(uh,nt(r,nt(r,nt(3,r).sub(6))).add(4)),Ly=r=>nt(uh,nt(r,nt(r,nt(-3,r).add(3)).add(3)).add(1)),Ef=r=>nt(uh,oh(r,3)),Yg=r=>Dy(r).add(Mf(r)),Kg=r=>Ly(r).add(Ef(r)),Zg=r=>hi(-1,Mf(r).div(Dy(r).add(Mf(r)))),Qg=r=>hi(1,Ef(r).div(Ly(r).add(Ef(r)))),Jg=(r,e,t)=>{const n=r.uvNode,i=nt(n,e.zw).add(.5),s=to(i),o=Ss(i),a=Yg(o.x),l=Kg(o.x),c=Zg(o.x),u=Qg(o.x),h=Zg(o.y),d=Qg(o.y),f=Ie(s.x.add(c),s.y.add(h)).sub(.5).mul(e.xy),p=Ie(s.x.add(u),s.y.add(h)).sub(.5).mul(e.xy),g=Ie(s.x.add(c),s.y.add(d)).sub(.5).mul(e.xy),m=Ie(s.x.add(u),s.y.add(d)).sub(.5).mul(e.xy),_=Yg(o.y).mul(hi(a.mul(r.sample(f).level(t)),l.mul(r.sample(p).level(t)))),x=Kg(o.y).mul(hi(a.mul(r.sample(g).level(t)),l.mul(r.sample(m).level(t))));return _.add(x)},fD=Q(([r,e])=>{const t=Ie(r.size(Kt(e))),n=Ie(r.size(Kt(e.add(1)))),i=vs(1,t),s=vs(1,n),o=Jg(r,Ze(i,t),to(e)),a=Jg(r,Ze(s,n),Lp(e));return Ss(e).mix(o,a)}),e_=Q(([r,e,t,n,i])=>{const s=K(G0(e.negate(),gs(r),vs(1,n))),o=K(Ws(i[0].xyz),Ws(i[1].xyz),Ws(i[2].xyz));return gs(s).mul(t.mul(o))}).setLayout({name:"getVolumeTransmissionRay",type:"vec3",inputs:[{name:"n",type:"vec3"},{name:"v",type:"vec3"},{name:"thickness",type:"float"},{name:"ior",type:"float"},{name:"modelMatrix",type:"mat4"}]}),pD=Q(([r,e])=>r.mul(Cr(e.mul(2).sub(2),0,1))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),mD=_y(),gD=MP(),t_=Q(([r,e,t],{material:n})=>{const s=(n.side===Pt?mD:gD).sample(r),o=Hs(Sf.x).mul(pD(e,t));return fD(s,o)}),n_=Q(([r,e,t])=>(Lt(t.notEqual(0),()=>{const n=N0(e).negate().div(t);return C0(n.negate().mul(r))}),K(1))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),_D=Q(([r,e,t,n,i,s,o,a,l,c,u,h,d,f,p])=>{let g,m;if(p){g=Ze().toVar(),m=K().toVar();const E=u.sub(1).mul(p.mul(.025)),T=K(u.sub(E),u,u.add(E));wi({start:0,end:3},({i:A})=>{const y=T.element(A),R=e_(r,e,h,y,a),P=o.add(R),N=c.mul(l.mul(Ze(P,1))),U=Ie(N.xy.div(N.w)).toVar();U.addAssign(1),U.divAssign(2),U.assign(Ie(U.x,U.y.oneMinus()));const G=t_(U,t,y);g.element(A).assign(G.element(A)),g.a.addAssign(G.a),m.element(A).assign(n.element(A).mul(n_(Ws(R),d,f).element(A)))}),g.a.divAssign(3)}else{const E=e_(r,e,h,u,a),T=o.add(E),A=c.mul(l.mul(Ze(T,1))),y=Ie(A.xy.div(A.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(Ie(y.x,y.y.oneMinus())),g=t_(y,t,u),m=n.mul(n_(Ws(E),d,f))}const _=m.rgb.mul(g.rgb),x=r.dot(e).clamp(),v=K(Py({dotNV:x,specularColor:i,specularF90:s,roughness:t})),S=m.r.add(m.g,m.b).div(3);return Ze(v.oneMinus().mul(_),g.a.oneMinus().mul(S).oneMinus())}),xD=Bn(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),yD=r=>{const e=r.sqrt();return K(1).add(e).div(K(1).sub(e))},i_=(r,e)=>r.sub(e).div(r.add(e)).pow2(),vD=(r,e)=>{const t=r.mul(2*Math.PI*1e-9),n=K(54856e-17,44201e-17,52481e-17),i=K(1681e3,1795300,2208400),s=K(43278e5,93046e5,66121e5),o=j(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(t.mul(2239900).add(e.x).cos()).mul(t.pow2().mul(-45282e5).exp());let a=n.mul(s.mul(2*Math.PI).sqrt()).mul(i.mul(t).add(e).cos()).mul(t.pow2().negate().mul(s).exp());return a=K(a.x.add(o),a.y,a.z).div(10685e-11),xD.mul(a)},s_=Q(({outsideIOR:r,eta2:e,cosTheta1:t,thinFilmThickness:n,baseF0:i})=>{const s=Nt(r,e,Xs(0,.03,n)),a=r.div(s).pow2().mul(t.pow2().oneMinus()).oneMinus();Lt(a.lessThan(0),()=>K(1));const l=a.sqrt(),c=i_(s,r),u=ec({f0:c,f90:1,dotVH:t}),h=u.oneMinus(),d=s.lessThan(r).select(Math.PI,0),f=j(Math.PI).sub(d),p=yD(i.clamp(0,.9999)),g=i_(p,s.toVec3()),m=ec({f0:g,f90:1,dotVH:l}),_=K(p.x.lessThan(s).select(Math.PI,0),p.y.lessThan(s).select(Math.PI,0),p.z.lessThan(s).select(Math.PI,0)),x=s.mul(n,l,2),v=K(f).add(_),S=u.mul(m).clamp(1e-5,.9999),E=S.sqrt(),T=h.pow2().mul(m).div(K(1).sub(S)),y=u.add(T).toVar(),R=T.sub(h).toVar();return wi({start:1,end:2,condition:"<=",name:"m"},({m:P})=>{R.mulAssign(E);const N=vD(j(P).mul(x),j(P).mul(v)).mul(2);y.addAssign(R.mul(N))}),y.max(K(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"}]}),cl=Q(({normal:r,viewDir:e,roughness:t})=>{const n=r.dot(e).saturate(),i=t.mul(t),s=t.add(.1).reciprocal(),o=j(-1.9362).add(t.mul(1.0678)).add(i.mul(.4573)).sub(s.mul(.8469)),a=j(-.6014).add(t.mul(.5538)).sub(i.mul(.467)).sub(s.mul(.1255));return o.mul(n).add(a).exp().saturate()}),ul=K(.04),eu=j(1);class Uy extends ch{constructor(e=!1,t=!1,n=!1,i=!1,s=!1,o=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=n,this.anisotropy=i,this.transmission=s,this.dispersion=o,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(this.clearcoat===!0&&(this.clearcoatRadiance=K().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=K().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=K().toVar("clearcoatSpecularIndirect")),this.sheen===!0&&(this.sheenSpecularDirect=K().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=K().toVar("sheenSpecularIndirect")),this.iridescence===!0){const t=_t.dot(Wt).clamp(),n=s_({outsideIOR:j(1),eta2:gf,cosTheta1:t,thinFilmThickness:_f,baseF0:co}),i=s_({outsideIOR:j(1),eta2:gf,cosTheta1:t,thinFilmThickness:_f,baseF0:Ct.rgb});this.iridescenceFresnel=Nt(n,i,mr),this.iridescenceF0Dielectric=qg({f:n,f90:1,dotVH:t}),this.iridescenceF0Metallic=qg({f:i,f90:1,dotVH:t}),this.iridescenceF0=Nt(this.iridescenceF0Dielectric,this.iridescenceF0Metallic,mr)}if(this.transmission===!0){const t=Fa,n=jN.sub(Fa).normalize(),i=Ya,s=e.context;s.backdrop=_D(i,n,Os,$o,qo,jo,t,fo,js,Pl,Eu,M0,A0,E0,this.dispersion?R0:null),s.backdropAlpha=vf,Ct.a.mulAssign(Nt(1,s.backdrop.a,vf))}super.start(e)}computeMultiscattering(e,t,n,i,s=null){const o=_t.dot(Wt).clamp(),a=zu({roughness:Os,dotNV:o}),l=s?Cp.mix(i,s):i,c=l.mul(a.x).add(n.mul(a.y)),h=a.x.add(a.y).oneMinus(),d=l.add(l.oneMinus().mul(.047619)),f=c.mul(d).div(h.mul(d).oneMinus());e.addAssign(c),t.addAssign(f.mul(h))}direct({lightDirection:e,lightColor:t,reflectedLight:n}){const s=_t.dot(e).clamp().mul(t).toVar();if(this.sheen===!0){this.sheenSpecularDirect.addAssign(s.mul(hD({lightDirection:e})));const o=cl({normal:_t,viewDir:Wt,roughness:jr}),a=cl({normal:_t,viewDir:e,roughness:jr}),l=Ei.r.max(Ei.g).max(Ei.b).mul(o.max(a)).oneMinus();s.mulAssign(l)}if(this.clearcoat===!0){const a=Zr.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(a.mul(Ny({lightDirection:e,f0:ul,f90:eu,roughness:wl,normalView:Zr})))}n.directDiffuse.addAssign(s.mul(Ia({diffuseColor:$o}))),n.directSpecular.addAssign(s.mul(lD({lightDirection:e,f0:qo,f90:1,roughness:Os,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy})))}directRectArea({lightColor:e,lightPosition:t,halfWidth:n,halfHeight:i,reflectedLight:s,ltc_1:o,ltc_2:a}){const l=t.add(n).sub(i),c=t.sub(n).sub(i),u=t.sub(n).add(i),h=t.add(n).add(i),d=_t,f=Wt,p=hn.toVar(),g=jg({N:d,V:f,roughness:Os}),m=o.sample(g).toVar(),_=a.sample(g).toVar(),x=Bn(K(m.x,0,m.y),K(0,1,0),K(m.z,0,m.w)).toVar(),v=qo.mul(_.x).add(jo.sub(qo).mul(_.y)).toVar();if(s.directSpecular.addAssign(e.mul(v).mul(yd({N:d,V:f,P:p,mInv:x,p0:l,p1:c,p2:u,p3:h}))),s.directDiffuse.addAssign(e.mul($o).mul(yd({N:d,V:f,P:p,mInv:Bn(1,0,0,0,1,0,0,0,1),p0:l,p1:c,p2:u,p3:h}))),this.clearcoat===!0){const S=Zr,E=jg({N:S,V:f,roughness:wl}),T=o.sample(E),A=a.sample(E),y=Bn(K(T.x,0,T.y),K(0,1,0),K(T.z,0,T.w)),R=ul.mul(A.x).add(eu.sub(ul).mul(A.y));this.clearcoatSpecularDirect.addAssign(e.mul(R).mul(yd({N:S,V:f,P:p,mInv:y,p0:l,p1:c,p2:u,p3:h})))}}indirect(e){this.indirectDiffuse(e),this.indirectSpecular(e),this.ambientOcclusion(e)}indirectDiffuse(e){const{irradiance:t,reflectedLight:n}=e.context,i=t.mul(Ia({diffuseColor:$o})).toVar();if(this.sheen===!0){const s=cl({normal:_t,viewDir:Wt,roughness:jr}),o=Ei.r.max(Ei.g).max(Ei.b).mul(s).oneMinus();i.mulAssign(o)}n.indirectDiffuse.addAssign(i)}indirectSpecular(e){const{radiance:t,iblIrradiance:n,reflectedLight:i}=e.context;if(this.sheen===!0&&this.sheenSpecularIndirect.addAssign(n.mul(Ei,cl({normal:_t,viewDir:Wt,roughness:jr}))),this.clearcoat===!0){const m=Zr.dot(Wt).clamp(),_=Py({dotNV:m,specularColor:ul,specularF90:eu,roughness:wl});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(_))}const s=K().toVar("singleScatteringDielectric"),o=K().toVar("multiScatteringDielectric"),a=K().toVar("singleScatteringMetallic"),l=K().toVar("multiScatteringMetallic");this.computeMultiscattering(s,o,jo,co,this.iridescenceF0Dielectric),this.computeMultiscattering(a,l,jo,Ct.rgb,this.iridescenceF0Metallic);const c=Nt(s,a,mr),u=Nt(o,l,mr),h=s.add(o),d=$o.mul(h.oneMinus()),f=n.mul(1/Math.PI),p=t.mul(c).add(u.mul(f)).toVar(),g=d.mul(f).toVar();if(this.sheen===!0){const m=cl({normal:_t,viewDir:Wt,roughness:jr}),_=Ei.r.max(Ei.g).max(Ei.b).mul(m).oneMinus();p.mulAssign(_),g.mulAssign(_)}i.indirectSpecular.addAssign(p),i.indirectDiffuse.addAssign(g)}ambientOcclusion(e){const{ambientOcclusion:t,reflectedLight:n}=e.context,s=_t.dot(Wt).clamp().add(t),o=Os.mul(-16).oneMinus().negate().exp2(),a=t.sub(s.pow(o).oneMinus()).clamp();this.clearcoat===!0&&this.clearcoatSpecularIndirect.mulAssign(t),this.sheen===!0&&this.sheenSpecularIndirect.mulAssign(t),n.indirectDiffuse.mulAssign(t),n.indirectSpecular.mulAssign(a)}finish({context:e}){const{outgoingLight:t}=e;if(this.clearcoat===!0){const n=Zr.dot(Wt).clamp(),i=ec({dotVH:n,f0:ul,f90:eu}),s=t.mul(mf.mul(i).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(mf));t.assign(s)}if(this.sheen===!0){const n=t.add(this.sheenSpecularDirect,this.sheenSpecularIndirect.mul(1/Math.PI));t.assign(n)}}}const r_=j(1),Af=j(-2),tu=j(.8),vd=j(-1),nu=j(.4),Sd=j(2),iu=j(.305),bd=j(3),o_=j(.21),SD=j(4),a_=j(4),bD=j(16),TD=Q(([r])=>{const e=K(yi(r)).toVar(),t=j(-1).toVar();return Lt(e.x.greaterThan(e.z),()=>{Lt(e.x.greaterThan(e.y),()=>{t.assign(Si(r.x.greaterThan(0),0,3))}).Else(()=>{t.assign(Si(r.y.greaterThan(0),1,4))})}).Else(()=>{Lt(e.z.greaterThan(e.y),()=>{t.assign(Si(r.z.greaterThan(0),2,5))}).Else(()=>{t.assign(Si(r.y.greaterThan(0),1,4))})}),t}).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),MD=Q(([r,e])=>{const t=Ie().toVar();return Lt(e.equal(0),()=>{t.assign(Ie(r.z,r.y).div(yi(r.x)))}).ElseIf(e.equal(1),()=>{t.assign(Ie(r.x.negate(),r.z.negate()).div(yi(r.y)))}).ElseIf(e.equal(2),()=>{t.assign(Ie(r.x.negate(),r.y).div(yi(r.z)))}).ElseIf(e.equal(3),()=>{t.assign(Ie(r.z.negate(),r.y).div(yi(r.x)))}).ElseIf(e.equal(4),()=>{t.assign(Ie(r.x.negate(),r.z).div(yi(r.y)))}).Else(()=>{t.assign(Ie(r.x,r.y).div(yi(r.z)))}),nt(.5,t.add(1))}).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),ED=Q(([r])=>{const e=j(0).toVar();return Lt(r.greaterThanEqual(tu),()=>{e.assign(r_.sub(r).mul(vd.sub(Af)).div(r_.sub(tu)).add(Af))}).ElseIf(r.greaterThanEqual(nu),()=>{e.assign(tu.sub(r).mul(Sd.sub(vd)).div(tu.sub(nu)).add(vd))}).ElseIf(r.greaterThanEqual(iu),()=>{e.assign(nu.sub(r).mul(bd.sub(Sd)).div(nu.sub(iu)).add(Sd))}).ElseIf(r.greaterThanEqual(o_),()=>{e.assign(iu.sub(r).mul(SD.sub(bd)).div(iu.sub(o_)).add(bd))}).Else(()=>{e.assign(j(-2).mul(Hs(nt(1.16,r))))}),e}).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),AD=Q(([r,e])=>{const t=r.toVar();t.assign(nt(2,t).sub(1));const n=K(t,1).toVar();return Lt(e.equal(0),()=>{n.assign(n.zyx)}).ElseIf(e.equal(1),()=>{n.assign(n.xzy),n.xz.mulAssign(-1)}).ElseIf(e.equal(2),()=>{n.x.mulAssign(-1)}).ElseIf(e.equal(3),()=>{n.assign(n.zyx),n.xz.mulAssign(-1)}).ElseIf(e.equal(4),()=>{n.assign(n.xzy),n.xy.mulAssign(-1)}).ElseIf(e.equal(5),()=>{n.z.mulAssign(-1)}),n}).setLayout({name:"getDirection",type:"vec3",inputs:[{name:"uv",type:"vec2"},{name:"face",type:"float"}]}),RD=Q(([r,e,t,n,i,s])=>{const o=j(t),a=K(e),l=Cr(ED(o),Af,s),c=Ss(l),u=to(l),h=K(tc(r,a,u,n,i,s)).toVar();return Lt(c.notEqual(0),()=>{const d=K(tc(r,a,u.add(1),n,i,s)).toVar();h.assign(Nt(h,d,c))}),h}),tc=Q(([r,e,t,n,i,s])=>{const o=j(t).toVar(),a=K(e),l=j(TD(a)).toVar(),c=j(On(a_.sub(o),0)).toVar();o.assign(On(o,a_));const u=j(Zl(o)).toVar(),h=Ie(MD(a,l).mul(u.sub(2)).add(1)).toVar();return Lt(l.greaterThan(2),()=>{h.y.addAssign(u),l.subAssign(3)}),h.x.addAssign(l.mul(u)),h.x.addAssign(c.mul(nt(3,bD))),h.y.addAssign(nt(4,Zl(s).sub(u))),h.x.mulAssign(n),h.y.mulAssign(i),r.sample(h).grad(Ie(),Ie())}),Td=Q(({envMap:r,mipInt:e,outputDirection:t,theta:n,axis:i,CUBEUV_TEXEL_WIDTH:s,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:a})=>{const l=cs(n),c=t.mul(l).add(i.cross(t).mul(xi(n))).add(i.mul(i.dot(t).mul(l.oneMinus())));return tc(r,c,e,s,o,a)}),wD=Q(({n:r,latitudinal:e,poleAxis:t,outputDirection:n,weights:i,samples:s,dTheta:o,mipInt:a,envMap:l,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:h})=>{const d=K(Si(e,t,ho(t,n))).toVar();Lt(d.equal(K(0)),()=>{d.assign(K(n.z,0,n.x.negate()))}),d.assign(gs(d));const f=K().toVar();return f.addAssign(i.element(0).mul(Td({theta:0,axis:d,outputDirection:n,mipInt:a,envMap:l,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:h}))),wi({start:Kt(1),end:r},({i:p})=>{Lt(p.greaterThanEqual(s),()=>{mP()});const g=j(o.mul(j(p))).toVar();f.addAssign(i.element(p).mul(Td({theta:g.mul(-1),axis:d,outputDirection:n,mipInt:a,envMap:l,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:h}))),f.addAssign(i.element(p).mul(Td({theta:g,axis:d,outputDirection:n,mipInt:a,envMap:l,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:h})))}),Ze(f,1)}),CD=Q(([r])=>{const e=ht(r).toVar();return e.assign(e.shiftLeft(ht(16)).bitOr(e.shiftRight(ht(16)))),e.assign(e.bitAnd(ht(1431655765)).shiftLeft(ht(1)).bitOr(e.bitAnd(ht(2863311530)).shiftRight(ht(1)))),e.assign(e.bitAnd(ht(858993459)).shiftLeft(ht(2)).bitOr(e.bitAnd(ht(3435973836)).shiftRight(ht(2)))),e.assign(e.bitAnd(ht(252645135)).shiftLeft(ht(4)).bitOr(e.bitAnd(ht(4042322160)).shiftRight(ht(4)))),e.assign(e.bitAnd(ht(16711935)).shiftLeft(ht(8)).bitOr(e.bitAnd(ht(4278255360)).shiftRight(ht(8)))),j(e).mul(23283064365386963e-26)}),ND=Q(([r,e])=>Ie(j(r).div(j(e)),CD(r))),PD=Q(([r,e,t])=>{const n=t.mul(t).toConst(),i=K(1,0,0).toConst(),s=ho(e,i).toConst(),o=Er(r.x).toConst(),a=nt(2,3.14159265359).mul(r.y).toConst(),l=o.mul(cs(a)).toConst(),c=o.mul(xi(a)).toVar(),u=nt(.5,e.z.add(1)).toConst();c.assign(u.oneMinus().mul(Er(l.mul(l).oneMinus())).add(u.mul(c)));const h=i.mul(l).add(s.mul(c)).add(e.mul(Er(On(0,l.mul(l).add(c.mul(c)).oneMinus()))));return gs(K(n.mul(h.x),n.mul(h.y),On(0,h.z)))}),DD=Q(({roughness:r,mipInt:e,envMap:t,N_immutable:n,GGX_SAMPLES:i,CUBEUV_TEXEL_WIDTH:s,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:a})=>{const l=K(n).toVar(),c=K(0).toVar(),u=j(0).toVar();return Lt(r.lessThan(.001),()=>{c.assign(tc(t,l,e,s,o,a))}).Else(()=>{const h=Si(yi(l.z).lessThan(.999),K(0,0,1),K(1,0,0)),d=gs(ho(h,l)).toVar(),f=ho(l,d).toVar();wi({start:ht(0),end:i},({i:p})=>{const g=ND(p,i),m=PD(g,K(0,0,1),r),_=gs(d.mul(m.x).add(f.mul(m.y)).add(l.mul(m.z))),x=gs(_.mul(uo(l,_).mul(2)).sub(l)),v=On(uo(l,x),0);Lt(v.greaterThan(0),()=>{const S=tc(t,x,e,s,o,a);c.addAssign(S.mul(v)),u.addAssign(v)})}),Lt(u.greaterThan(0),()=>{c.assign(c.div(u))})}),Ze(c,1)}),gr=4,l_=[.125,.215,.35,.446,.526,.582],Qr=20,LD=512,hl=new Va(-1,1,1,-1,0,1),UD=new Rn(90,1),c_=new Ve;let Md=null,Ed=0,Ad=0;const FD=new C,Hu=new WeakMap,ID=[3,1,5,0,4,2],Rd=AD(Xa(),Nr("faceIndex")).normalize(),hh=K(Rd.x,Rd.y,Rd.z);class BD{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,i=100,s={}){const{size:o=256,position:a=FD,renderTarget:l=null}=s;if(this._setSize(o),this._hasInitialized===!1){ee('PMREMGenerator: ".fromScene()" called before the backend is initialized. Try using "await renderer.init()" instead.');const u=l||this._allocateTarget();return s.renderTarget=u,this.fromSceneAsync(e,t,n,i,s),u}Md=this._renderer.getRenderTarget(),Ed=this._renderer.getActiveCubeFace(),Ad=this._renderer.getActiveMipmapLevel();const c=l||this._allocateTarget();return c.depthBuffer=!0,this._init(c),this._sceneToCubeUV(e,n,i,c,a),t>0&&this._blur(c,0,0,t),this._applyPMREM(c),this._cleanup(c),c}async fromSceneAsync(e,t=0,n=.1,i=100,s={}){return Yt('PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this.fromScene(e,t,n,i,s)}fromEquirectangular(e,t=null){if(this._hasInitialized===!1){ee('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 Yt('PMREMGenerator: ".fromEquirectangularAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}fromCubemap(e,t=null){if(this._hasInitialized===!1){ee("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 Yt('PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=h_(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=d_(),await this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._backgroundBox!==null&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSizeFromTexture(e){e.mapping===Xi||e.mapping===_s?this._setSize(e.image.length===0?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(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e2?_:0,_,_),c.render(e,o)}c.autoClear=u,e.background=p}_textureToCubeUV(e,t){const n=this._renderer,i=e.mapping===Xi||e.mapping===_s;i?this._cubemapMaterial===null&&(this._cubemapMaterial=h_(e)):this._equirectMaterial===null&&(this._equirectMaterial=d_(e));const s=i?this._cubemapMaterial:this._equirectMaterial;s.fragmentNode.value=e;const o=this._lodMeshes[0];o.material=s;const a=this._cubeSize;this._setViewport(t,0,0,3*a,2*a),n.setRenderTarget(t),n.render(o,hl)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;const i=this._lodMeshes.length;for(let s=1;sp-gr?n-p+gr:0),_=4*(this._cubeSize-g);e.texture.frame=(e.texture.frame||0)+1,l.envMap.value=e.texture,l.roughness.value=f,l.mipInt.value=p-t,this._setViewport(s,m,_,3*g,2*g),i.setRenderTarget(s),i.render(a,hl),s.texture.frame=(s.texture.frame||0)+1,l.envMap.value=s.texture,l.roughness.value=0,l.mipInt.value=p-n,this._setViewport(e,m,_,3*g,2*g),i.setRenderTarget(e),i.render(a,hl)}_blur(e,t,n,i,s){const o=this._pingPongRenderTarget;this._halfBlur(e,o,t,n,i,"latitudinal",s),this._halfBlur(o,e,n,n,i,"longitudinal",s)}_halfBlur(e,t,n,i,s,o,a){const l=this._renderer,c=this._blurMaterial;o!=="latitudinal"&&o!=="longitudinal"&&ne("blur direction must be either latitudinal or longitudinal!");const u=3,h=this._lodMeshes[i];h.material=c;const d=Hu.get(c),f=this._sizeLods[n]-1,p=isFinite(s)?Math.PI/(2*f):2*Math.PI/(2*Qr-1),g=s/p,m=isFinite(s)?1+Math.floor(u*g):Qr;m>Qr&&ee(`sigmaRadians, ${s}, is too large and will clip, as it requested ${m} samples when the maximum is set to ${Qr}`);const _=[];let x=0;for(let A=0;Av-gr?i-v+gr:0),T=4*(this._cubeSize-S);this._setViewport(t,E,T,3*S,2*S),l.setRenderTarget(t),l.render(h,hl)}_setViewport(e,t,n,i,s){this._renderer.isWebGLRenderer?(e.viewport.set(t,e.height-s-n,i,s),e.scissor.set(t,e.height-s-n,i,s)):(e.viewport.set(t,n,i,s),e.scissor.set(t,n,i,s))}}function OD(r){const e=[],t=[],n=[];let i=r;const s=r-gr+1+l_.length;for(let o=0;or-gr?l=l_[o-r+gr-1]:o===0&&(l=0),t.push(l);const c=1/(a-2),u=-c,h=1+c,d=[u,u,h,u,h,h,u,u,h,h,u,h],f=6,p=6,g=3,m=2,_=1,x=new Float32Array(g*p*f),v=new Float32Array(m*p*f),S=new Float32Array(_*p*f);for(let T=0;T2?0:-1,R=[A,y,0,A+2/3,y,0,A+2/3,y+1,0,A,y,0,A+2/3,y+1,0,A,y+1,0],P=ID[T];x.set(R,g*p*P),v.set(d,m*p*P);const N=[P,P,P,P,P,P];S.set(N,_*p*P)}const E=new Pn;E.setAttribute("position",new In(x,g)),E.setAttribute("uv",new In(v,m)),E.setAttribute("faceIndex",new In(S,_)),n.push(new gn(E,null)),i>gr&&i--}return{lodMeshes:n,sizeLods:e,sigmas:t}}function u_(r,e){const t={magFilter:Ut,minFilter:Ut,generateMipmaps:!1,type:en,format:an,colorSpace:ql},n=new Lr(r,e,t);return n.texture.mapping=so,n.texture.name="PMREM.cubeUv",n.texture.isPMREMTexture=!0,n.scissorTest=!0,n}function dh(r){const e=new dn;return e.depthTest=!1,e.depthWrite=!1,e.blending=Cn,e.name=`PMREM_${r}`,e}function kD(r,e,t){const n=Ri(new Array(Qr).fill(0)),i=We(new C(0,1,0)),s=We(0),o=j(Qr),a=We(0),l=We(1),c=Gt(),u=We(0),h=j(1/e),d=j(1/t),f=j(r),p={n:o,latitudinal:a,weights:n,poleAxis:i,outputDirection:hh,dTheta:s,samples:l,envMap:c,mipInt:u,CUBEUV_TEXEL_WIDTH:h,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:f},g=dh("blur");return g.fragmentNode=wD({...p,latitudinal:a.equal(1)}),Hu.set(g,p),g}function GD(r,e,t){const n=Gt(),i=We(0),s=We(0),o=j(1/e),a=j(1/t),l=j(r),c={envMap:n,roughness:i,mipInt:s,CUBEUV_TEXEL_WIDTH:o,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:l},u=dh("ggx");return u.fragmentNode=DD({...c,N_immutable:hh,GGX_SAMPLES:ht(LD)}),Hu.set(u,c),u}function h_(r){const e=dh("cubemap");return e.fragmentNode=oi(r,hh),e}function d_(r){const e=dh("equirect");return e.fragmentNode=Gt(r,Ty(hh),0),e}const f_=new WeakMap;function VD(r){const e=Math.log2(r)-2,t=1/r;return{texelWidth:1/(3*Math.max(Math.pow(2,e),7*16)),texelHeight:t,maxMip:e}}function zD(r,e,t){const n=HD(e);let i=n.get(r);if((i!==void 0?i.pmremVersion:-1)!==r.pmremVersion){const o=r.image;if(r.isCubeTexture)if($D(o))i=t.fromCubemap(r,i);else return null;else if(XD(o))i=t.fromEquirectangular(r,i);else return null;i.pmremVersion=r.pmremVersion,n.set(r,i)}return i.texture}function HD(r){let e=f_.get(r);return e===void 0&&(e=new WeakMap,f_.set(r,e)),e}class WD extends _n{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 i=new pn;i.isRenderTargetTexture=!0,this._texture=Gt(i),this._width=We(0),this._height=We(0),this._maxMip=We(0),this.updateBeforeType=je.RENDER}set value(e){this._value=e,this._pmrem=null}get value(){return this._value}updateFromTexture(e){const t=VD(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,i=this._value;n!==i.pmremVersion&&(i.isPMREMTexture===!0?t=i:t=zD(i,e.renderer,this._generator),t!==null&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){this._generator===null&&(this._generator=new BD(e.renderer)),this.updateBefore(e);let t=this.uvNode;t===null&&e.context.getUV&&(t=e.context.getUV(this,e)),t=sy.mul(K(t.x,t.y.negate(),t.z));let n=this.levelNode;return n===null&&e.context.getTextureLevel&&(n=e.context.getTextureLevel(this)),RD(this._texture,t,n,this._width,this._height,this._maxMip)}dispose(){super.dispose(),this._generator!==null&&this._generator.dispose()}}function $D(r){if(r==null)return!1;let e=0;const t=6;for(let n=0;n0}const Fy=Ft(WD).setParameterLength(1,3),p_=new WeakMap;class qD extends Ka{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 h=n.isTextureNode?n.value:t[n.property],d=this._getPMREMNodeCache(e.renderer);let f=d.get(h);f===void 0&&(f=Fy(h),d.set(h,f)),n=f}const s=t.useAnisotropy===!0||t.anisotropy>0?y1:_t,o=n.context(m_(Os,s)).mul(md),a=n.context(jD(Ya)).mul(Math.PI).mul(md),l=Nl(o),c=Nl(a);e.context.radiance.addAssign(l),e.context.iblIrradiance.addAssign(c);const u=e.context.lightingModel.clearcoatRadiance;if(u){const h=n.context(m_(wl,Zr)).mul(md),d=Nl(h);u.addAssign(d)}}_getPMREMNodeCache(e){let t=p_.get(e);return t===void 0&&(t=new WeakMap,p_.set(e,t)),t}}const m_=(r,e)=>{let t=null;return{getUV:()=>(t===null&&(t=Wt.negate().reflect(e),t=O0(r).mix(t,e).normalize(),t=t.transformDirection(js)),t),getTextureLevel:()=>r}},jD=r=>({getUV:()=>r,getTextureLevel:()=>j(1)}),YD=new Ux;class Iy extends dn{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(YD),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return t===null&&e.environmentNode&&(t=e.environmentNode),t?new qD(t):null}setupLightingModel(){return new Uy}setupSpecular(){const e=Nt(K(.04),Ct.rgb,mr);co.assign(K(.04)),qo.assign(e),jo.assign(1)}setupVariants(){const e=this.metalnessNode?j(this.metalnessNode):L1;mr.assign(e);let t=this.roughnessNode?j(this.roughnessNode):D1;t=Cy({roughness:t}),Os.assign(t),this.setupSpecular(),$o.assign(Ct.rgb.mul(e.oneMinus()))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}const KD=new Sb;class ZD extends Iy{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(KD),this.setValues(e)}get useClearcoat(){return this.clearcoat>0||this.clearcoatNode!==null}get useIridescence(){return this.iridescence>0||this.iridescenceNode!==null}get useSheen(){return this.sheen>0||this.sheenNode!==null}get useAnisotropy(){return this.anisotropy>0||this.anisotropyNode!==null}get useTransmission(){return this.transmission>0||this.transmissionNode!==null}get useDispersion(){return this.dispersion>0||this.dispersionNode!==null}setupSpecular(){const e=this.iorNode?j(this.iorNode):q1;Eu.assign(e),co.assign(Ua(B0(Eu.sub(1).div(Eu.add(1))).mul(P1),K(1)).mul(Gg)),qo.assign(Nt(co,Ct.rgb,mr)),jo.assign(Nt(Gg,1,mr))}setupLightingModel(){return new Uy(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const t=this.clearcoatNode?j(this.clearcoatNode):F1,n=this.clearcoatRoughnessNode?j(this.clearcoatRoughnessNode):I1;mf.assign(t),wl.assign(Cy({roughness:n}))}if(this.useSheen){const t=this.sheenNode?K(this.sheenNode):k1,n=this.sheenRoughnessNode?j(this.sheenRoughnessNode):G1;Ei.assign(t),jr.assign(n)}if(this.useIridescence){const t=this.iridescenceNode?j(this.iridescenceNode):z1,n=this.iridescenceIORNode?j(this.iridescenceIORNode):H1,i=this.iridescenceThicknessNode?j(this.iridescenceThicknessNode):W1;Cp.assign(t),gf.assign(n),_f.assign(i)}if(this.useAnisotropy){const t=(this.anisotropyNode?Ie(this.anisotropyNode):V1).toVar();Xr.assign(t.length()),Lt(Xr.equal(0),()=>{t.assign(Ie(1,0))}).Else(()=>{t.divAssign(Ie(Xr)),Xr.assign(Xr.saturate())}),xf.assign(Xr.pow2().mix(Os.pow2(),1)),Mu.assign(yl[0].mul(t.x).add(yl[1].mul(t.y))),na.assign(yl[1].mul(t.x).sub(yl[0].mul(t.y)))}if(this.useTransmission){const t=this.transmissionNode?j(this.transmissionNode):$1,n=this.thicknessNode?j(this.thicknessNode):X1,i=this.attenuationDistanceNode?j(this.attenuationDistanceNode):j1,s=this.attenuationColorNode?K(this.attenuationColorNode):Y1;if(vf.assign(t),M0.assign(n),E0.assign(i),A0.assign(s),this.useDispersion){const o=this.dispersionNode?j(this.dispersionNode):tP;R0.assign(o)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?K(this.clearcoatNormalNode):B1}setup(e){e.context.setupClearcoatNormal=()=>ia(this.setupClearcoatNormal(e),"NORMAL","vec3"),super.setup(e)}copy(e){return this.clearcoatNode=e.clearcoatNode,this.clearcoatRoughnessNode=e.clearcoatRoughnessNode,this.clearcoatNormalNode=e.clearcoatNormalNode,this.sheenNode=e.sheenNode,this.sheenRoughnessNode=e.sheenRoughnessNode,this.iridescenceNode=e.iridescenceNode,this.iridescenceIORNode=e.iridescenceIORNode,this.iridescenceThicknessNode=e.iridescenceThicknessNode,this.specularIntensityNode=e.specularIntensityNode,this.specularColorNode=e.specularColorNode,this.iorNode=e.iorNode,this.transmissionNode=e.transmissionNode,this.thicknessNode=e.thicknessNode,this.attenuationDistanceNode=e.attenuationDistanceNode,this.attenuationColorNode=e.attenuationColorNode,this.dispersionNode=e.dispersionNode,this.anisotropyNode=e.anisotropyNode,super.copy(e)}}const QD=Q(({normal:r,lightDirection:e,builder:t})=>{const n=r.dot(e),i=Ie(n.mul(.5).add(.5),0);if(t.material.gradientMap){const s=cr("gradientMap","texture").context({getUV:()=>i});return K(s.r)}else{const s=i.fwidth().mul(.5);return Nt(K(.7),K(1),Xs(j(.7).sub(s.x),j(.7).add(s.x),i.x))}});class JD extends ch{direct({lightDirection:e,lightColor:t,reflectedLight:n},i){const s=QD({normal:ny,lightDirection:e,builder:i}).mul(t);n.directDiffuse.addAssign(s.mul(Ia({diffuseColor:Ct.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:n,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(n.mul(Ia({diffuseColor:Ct}))),i.indirectDiffuse.mulAssign(t)}}const eL=new Tb;class tL extends dn{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(eL),this.setValues(e)}setupLightingModel(){return new JD}}const nL=Q(()=>{const r=K(Wt.z,0,Wt.x.negate()).normalize(),e=Wt.cross(r);return Ie(r.dot(_t),e.dot(_t)).mul(.495).add(.5)}).once(["NORMAL","VERTEX"])().toVar("matcapUV"),iL=new Rb;class sL extends dn{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(iL),this.setValues(e)}setupVariants(e){const t=nL;let n;e.material.matcap?n=cr("matcap","texture").context({getUV:()=>t}):n=K(Nt(.2,.8,t.y)),Ct.rgb.mulAssign(n.rgb)}}class rL extends _n{static get type(){return"RotateNode"}constructor(e,t){super(),this.positionNode=e,this.rotationNode=t}generateNodeType(e){return this.positionNode.getNodeType(e)}setup(e){const{rotationNode:t,positionNode:n}=this;if(this.getNodeType(e)==="vec2"){const s=t.cos(),o=t.sin();return wp(s,o,o.negate(),s).mul(n)}else{const s=t,o=eo(Ze(1,0,0,0),Ze(0,cs(s.x),xi(s.x).negate(),0),Ze(0,xi(s.x),cs(s.x),0),Ze(0,0,0,1)),a=eo(Ze(cs(s.y),0,xi(s.y),0),Ze(0,1,0,0),Ze(xi(s.y).negate(),0,cs(s.y),0),Ze(0,0,0,1)),l=eo(Ze(cs(s.z),xi(s.z).negate(),0,0),Ze(xi(s.z),cs(s.z),0,0),Ze(0,0,1,0),Ze(0,0,0,1));return o.mul(a).mul(l).mul(Ze(n,1)).xyz}}}const By=Ft(rL).setParameterLength(2),oL=new qS;class Oy extends dn{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(oL),this.setValues(e)}setupPositionView(e){const{object:t,camera:n}=e,{positionNode:i,rotationNode:s,scaleNode:o,sizeAttenuation:a}=this,l=mc.mul(K(i||0));let c=Ie(fo[0].xyz.length(),fo[1].xyz.length());o!==null&&(c=c.mul(Ie(o))),n.isPerspectiveCamera&&a===!1&&(c=c.mul(l.z.negate()));let u=lh.xy;if(t.center&&t.center.isVector2===!0){const f=gN("center","vec2",t);u=u.sub(f.sub(.5))}u=u.mul(c);const h=j(s||O1),d=By(u,h);return Ze(l.xy.add(d),l.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 aL=new eb,lL=new de;class cL extends Oy{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(aL),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return mc.mul(K(e||bn)).xyz}setupVertexSprite(e){const{material:t,camera:n}=e,{rotationNode:i,scaleNode:s,sizeNode:o,sizeAttenuation:a}=this;let l=super.setupVertex(e);if(t.isNodeMaterial!==!0)return l;let c=o!==null?Ie(o):eP;c=c.mul($N),n.isPerspectiveCamera&&a===!0&&(c=c.mul(uL.div(hn.z.negate()))),s&&s.isNode&&(c=c.mul(Ie(s)));let u=lh.xy;if(i&&i.isNode){const h=j(i);u=By(u,h)}return u=u.mul(c),u=u.div(XN.div(2)),u=u.mul(l.w),l=l.add(Ze(u,0,0)),l}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 uL=We(1).onFrameUpdate(function({renderer:r}){const e=r.getSize(lL);this.value=.5*e.y});class hL extends ch{constructor(){super(),this.shadowNode=j(1).toVar("shadowMask")}direct({lightNode:e}){e.shadowNode!==null&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){Ct.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(Ct.rgb)}}const dL=new gb;class fL extends dn{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(dL),this.setValues(e)}setupLightingModel(){return new hL}}Mr("vec3");Mr("vec3");Mr("vec3");class pL{constructor(e,t,n){this.renderer=e,this.nodes=t,this.info=n,this._context=typeof self<"u"?self:null,this._animationLoop=null,this._requestId=null}start(){const e=(t,n)=>{this._requestId=this._context.requestAnimationFrame(e),this.info.autoReset===!0&&this.info.reset(),this.nodes.nodeFrame.update(),this.info.frame=this.nodes.nodeFrame.frameId,this.renderer._inspector.begin(),this._animationLoop!==null&&this._animationLoop(t,n),this.renderer._inspector.finish()};e()}stop(){this._context!==null&&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 Pr{constructor(){this.weakMaps={}}_getWeakMap(e){const t=e.length;let n=this.weakMaps[t];return n===void 0&&(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 this.clippingContext===null||this.clippingContext.cacheKey===this.clippingContextCacheKey?!1:(this.clippingContextCacheKey=this.clippingContext.cacheKey,!0)}get hardwareClippingPlanes(){return this.material.hardwareClipping===!0?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(this.attributes!==null)return this.attributes;const e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,n=[],i=new Set,s={};for(const o of e){let a;if(o.node&&o.node.attribute?a=o.node.attribute:(a=t.getAttribute(o.name),s[o.name]=a.id),a===void 0)continue;n.push(a);const l=a.isInterleavedBufferAttribute?a.data:a;i.add(l)}return this.attributes=n,this.attributesId=s,this.vertexBuffers=Array.from(i.values()),n}getVertexBuffers(){return this.vertexBuffers===null&&this.getAttributes(),this.vertexBuffers}getDrawParameters(){const{object:e,material:t,geometry:n,group:i,drawRange:s}=this,o=this.drawParams||(this.drawParams={vertexCount:0,firstVertex:0,instanceCount:0,firstInstance:0}),a=this.getIndex(),l=a!==null;let c=1;if(n.isInstancedBufferGeometry===!0?c=n.instanceCount:e.count!==void 0&&(c=Math.max(0,e.count)),c===0)return null;if(o.instanceCount=c,e.isBatchedMesh===!0)return o;let u=1;t.wireframe===!0&&!e.isPoints&&!e.isLineSegments&&!e.isLine&&!e.isLineLoop&&(u=2);let h=s.start*u,d=(s.start+s.count)*u;i!==null&&(h=Math.max(h,i.start*u),d=Math.min(d,(i.start+i.count)*u));const f=n.attributes.position;let p=1/0;l?p=a.count:f!=null&&(p=f.count),h=Math.max(h,0),d=Math.min(d,p);const g=d-h;return g<0||g===1/0?null:(o.vertexCount=g,o.firstVertex=h,o)}getGeometryCacheKey(){const{geometry:e}=this;let t="";for(const n of Object.keys(e.attributes).sort()){const i=e.attributes[n];t+=n+",",i.data&&(t+=i.data.stride+","),i.offset&&(t+=i.offset+","),i.itemSize&&(t+=i.itemSize+","),i.normalized&&(t+="n,")}for(const n of Object.keys(e.morphAttributes).sort()){const i=e.morphAttributes[n];t+="morph-"+n+",";for(let s=0,o=i.length;s1||Array.isArray(e.morphTargetInfluences))&&(i+=e.uuid+","),i+=this.context.id+",",i+=e.receiveShadow+",",Ha(i)}get needsGeometryUpdate(){if(this.geometry.id!==this.object.geometry.id)return!0;if(this.attributes!==null){const e=this.attributesId;for(const t in e){const n=this.geometry.getAttribute(t);if(n===void 0||e[t]!==n.id)return!0}}return!1}get needsUpdate(){return this.initialNodesCacheKey!==this.getDynamicCacheKey()||this.clippingNeedsUpdate}getDynamicCacheKey(){let e=0;return this.material.isShadowPassMaterial!==!0&&(e=this._nodes.getCacheKey(this.scene,this.lightsNode)),this.camera.isArrayCamera&&(e=Al(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=Al(e,1)),e=Al(e,this.renderer.contextNode.id,this.renderer.contextNode.version),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.geometry.removeEventListener("dispose",this.onGeometryDispose),this.onDispose()}}const is=[];class xL{constructor(e,t,n,i,s,o){this.renderer=e,this.nodes=t,this.geometries=n,this.pipelines=i,this.bindings=s,this.info=o,this.chainMaps={}}get(e,t,n,i,s,o,a,l){const c=this.getChainMap(l);is[0]=e,is[1]=t,is[2]=o,is[3]=s;let u=c.get(is);return u===void 0?(u=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,n,i,s,o,a,l),c.set(is,u)):(u.camera=i,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,i,s,o,a,l)):u.version=t.version)),is[0]=null,is[1]=null,is[2]=null,is[3]=null,u}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new Pr)}dispose(){this.chainMaps={}}createRenderObject(e,t,n,i,s,o,a,l,c,u,h){const d=this.getChainMap(h),f=new _L(e,t,n,i,s,o,a,l,c,u);return f.onDispose=()=>{this.pipelines.delete(f),this.bindings.deleteForRender(f),this.nodes.delete(f),d.delete(f.getChainArray())},f}}class Ur{constructor(){this.data=new WeakMap}get(e){let t=this.data.get(e);return t===void 0&&(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 Pi={VERTEX:1,INDEX:2,STORAGE:3,INDIRECT:4},ur=16,yL=211,vL=212;class SL extends Ur{constructor(e,t){super(),this.backend=e,this.info=t}delete(e){const t=super.delete(e);return t!==null&&(this.backend.destroyAttribute(e),this.info.destroyAttribute(e)),t}update(e,t){const n=this.get(e);if(n.version===void 0)t===Pi.VERTEX?(this.backend.createAttribute(e),this.info.createAttribute(e)):t===Pi.INDEX?(this.backend.createIndexAttribute(e),this.info.createIndexAttribute(e)):t===Pi.STORAGE?(this.backend.createStorageAttribute(e),this.info.createStorageAttribute(e)):t===Pi.INDIRECT&&(this.backend.createIndirectStorageAttribute(e),this.info.createIndirectStorageAttribute(e)),n.version=this._getBufferAttribute(e).version;else{const i=this._getBufferAttribute(e);(n.version=65535?lp:ap)(e,1);return i.version=ky(r),i.__id=Gy(r),i}class bL extends Ur{constructor(e,t){super(),this.attributes=e,this.info=t,this.wireframes=new WeakMap,this.attributeCall=new WeakMap,this._geometryDisposeListeners=new Map}has(e){const t=e.geometry;return super.has(t)&&this.get(t).initialized===!0}updateForRender(e){this.has(e)===!1&&this.initGeometry(e),this.updateAttributes(e)}initGeometry(e){const t=e.geometry,n=this.get(t);n.initialized=!0,this.info.memory.geometries++;const i=()=>{this.info.memory.geometries--;const s=t.index,o=e.getAttributes();s!==null&&this.attributes.delete(s);for(const l of o)this.attributes.delete(l);const a=this.wireframes.get(t);a!==void 0&&this.attributes.delete(a),t.removeEventListener("dispose",i),this._geometryDisposeListeners.delete(t)};t.addEventListener("dispose",i),this._geometryDisposeListeners.set(t,i)}updateAttributes(e){const t=e.getAttributes();for(const s of t)s.isStorageBufferAttribute||s.isStorageInstancedBufferAttribute?this.updateAttribute(s,Pi.STORAGE):this.updateAttribute(s,Pi.VERTEX);const n=this.getIndex(e);n!==null&&this.updateAttribute(n,Pi.INDEX);const i=e.geometry.indirect;i!==null&&this.updateAttribute(i,Pi.INDIRECT)}updateAttribute(e,t){const n=this.info.render.calls;e.isInterleavedBufferAttribute?this.attributeCall.get(e)===void 0?(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 i=t.index;if(n.wireframe===!0){const s=this.wireframes;let o=s.get(t);o===void 0?(o=g_(t),s.set(t,o)):(o.version!==ky(t)||o.__id!==Gy(t))&&(this.attributes.delete(o),o=g_(t),s.set(t,o)),i=o}return i}dispose(){for(const[e,t]of this._geometryDisposeListeners.entries())e.removeEventListener("dispose",t);this._geometryDisposeListeners.clear()}}class TL{constructor(){this.autoReset=!0,this.frame=0,this.calls=0,this.render={calls:0,frameCalls:0,drawCalls:0,triangles:0,points:0,lines:0,timestamp:0},this.compute={calls:0,frameCalls:0,timestamp:0},this.memory={geometries:0,textures:0,attributes:0,indexAttributes:0,storageAttributes:0,indirectStorageAttributes:0,readbackBuffers:0,programs:0,renderTargets:0,total:0,texturesSize:0,attributesSize:0,indexAttributesSize:0,storageAttributesSize:0,indirectStorageAttributesSize:0,readbackBuffersSize:0,programsSize:0},this.memoryMap=new Map}update(e,t,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):ne("WebGPUInfo: Unknown object type.")}reset(){this.render.drawCalls=0,this.render.frameCalls=0,this.compute.frameCalls=0,this.render.triangles=0,this.render.points=0,this.render.lines=0}dispose(){this.reset(),this.calls=0,this.render.calls=0,this.compute.calls=0,this.render.timestamp=0,this.compute.timestamp=0;for(const e in this.memory)this.memory[e]=0;this.memoryMap.clear()}createTexture(e){const t=this._getTextureMemorySize(e);this.memoryMap.set(e,t),this.memory.textures++,this.memory.total+=t,this.memory.texturesSize+=t}destroyTexture(e){const t=this.memoryMap.get(e)||0;this.memoryMap.delete(e),this.memory.textures--,this.memory.total-=t,this.memory.texturesSize-=t}_createAttribute(e,t){const n=this._getAttributeMemorySize(e);this.memoryMap.set(e,{size:n,type:t}),this.memory[t]++,this.memory.total+=n,this.memory[t+"Size"]+=n}createAttribute(e){this._createAttribute(e,"attributes")}createIndexAttribute(e){this._createAttribute(e,"indexAttributes")}createStorageAttribute(e){this._createAttribute(e,"storageAttributes")}createIndirectStorageAttribute(e){this._createAttribute(e,"indirectStorageAttributes")}destroyAttribute(e){const t=this.memoryMap.get(e);t&&(this.memoryMap.delete(e),this.memory[t.type]--,this.memory.total-=t.size,this.memory[t.type+"Size"]-=t.size)}createReadbackBuffer(e){const t=e.maxByteLength;this.memoryMap.set(e,{size:t,type:"readbackBuffers"}),this.memory.readbackBuffers++,this.memory.total+=t,this.memory.readbackBuffersSize+=t}destroyReadbackBuffer(e){const{size:t}=this.memoryMap.get(e);this.memoryMap.delete(e),this.memory.readbackBuffers--,this.memory.total-=t,this.memory.readbackBuffersSize-=t}createProgram(e){const t=e.code.length;this.memoryMap.set(e,t),this.memory.programs++,this.memory.total+=t,this.memory.programsSize+=t}destroyProgram(e){const t=this.memoryMap.get(e)||0;this.memoryMap.delete(e),this.memory.programs--,this.memory.total-=t,this.memory.programsSize-=t}_getTextureMemorySize(e){if(e.isCompressedTexture)return 1;let t=1;e.type===_r||e.type===$t?t=1:e.type===xr||e.type===Ci||e.type===en?t=2:(e.type===Sn||e.type===wt||e.type===Zt)&&(t=4);let n=4;e.format===Yu||e.format===Oa||e.format===mo||e.format===Nn||e.format===$n?n=1:e.format===Fn||e.format===go?n=2:(e.format===Ba||e.format===xx)&&(n=3);let i=t*n;e.type===ic||e.type===sc?i=2:(e.type===ui||e.type===rc||e.type===oc)&&(i=4);const s=e.width||1,o=e.height||1,a=e.isCubeTexture?6:e.depth||1;let l=s*o*a*i;const c=e.mipmaps;if(c&&c.length>0){let u=0;for(let h=0;h>h),p=d.height||Math.max(1,o>>h);u+=f*p*a*i}}l+=u}else e.generateMipmaps&&(l=l*1.333);return Math.round(l)}_getAttributeMemorySize(e){return e.isInterleavedBufferAttribute&&(e=e.data),e.array?e.array.byteLength:e.count&&e.itemSize?e.count*e.itemSize*4:0}}class Vy{constructor(e){this.cacheKey=e,this.usedTimes=0}}class ML extends Vy{constructor(e,t,n){super(e),this.vertexProgram=t,this.fragmentProgram=n}}class EL extends Vy{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let AL=0;class wd{constructor(e,t,n,i=null,s=null){this.id=AL++,this.code=e,this.stage=t,this.name=n,this.transforms=i,this.attributes=s,this.usedTimes=0}}class RL extends Ur{constructor(e,t,n){super(),this.backend=e,this.nodes=t,this.info=n,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,i=this.get(e);if(this._needsComputeUpdate(e)){const s=i.pipeline;s&&(s.usedTimes--,s.computeProgram.usedTimes--);const o=this.nodes.getForCompute(e);let a=this.programs.compute.get(o.computeShader);a===void 0&&(s&&s.computeProgram.usedTimes===0&&this._releaseProgram(s.computeProgram),a=new wd(o.computeShader,"compute",e.name,o.transforms,o.nodeAttributes),this.programs.compute.set(o.computeShader,a),n.createProgram(a),this.info.createProgram(a));const l=this._getComputeCacheKey(e,a);let c=this.caches.get(l);c===void 0&&(s&&s.usedTimes===0&&this._releasePipeline(s),c=this._getComputePipeline(e,a,l,t)),c.usedTimes++,a.usedTimes++,i.version=e.version,i.pipeline=c}return i.pipeline}getForRender(e,t=null){const{backend:n}=this,i=this.get(e);if(this._needsRenderUpdate(e)){const s=i.pipeline;s&&(s.usedTimes--,s.vertexProgram.usedTimes--,s.fragmentProgram.usedTimes--);const o=e.getNodeBuilderState(),a=e.material?e.material.name:"";let l=this.programs.vertex.get(o.vertexShader);l===void 0&&(s&&s.vertexProgram.usedTimes===0&&this._releaseProgram(s.vertexProgram),l=new wd(o.vertexShader,"vertex",a),this.programs.vertex.set(o.vertexShader,l),n.createProgram(l),this.info.createProgram(l));let c=this.programs.fragment.get(o.fragmentShader);c===void 0&&(s&&s.fragmentProgram.usedTimes===0&&this._releaseProgram(s.fragmentProgram),c=new wd(o.fragmentShader,"fragment",a),this.programs.fragment.set(o.fragmentShader,c),n.createProgram(c),this.info.createProgram(c));const u=this._getRenderCacheKey(e,l,c);let h=this.caches.get(u);h===void 0?(s&&s.usedTimes===0&&this._releasePipeline(s),h=this._getRenderPipeline(e,l,c,u,t)):e.pipeline=h,h.usedTimes++,l.usedTimes++,c.usedTimes++,i.pipeline=h}return i.pipeline}isReady(e){const n=this.get(e).pipeline;if(n===void 0)return!1;const i=this.backend.get(n);return i.pipeline!==void 0&&i.pipeline!==null}delete(e){const t=this.get(e).pipeline;return t&&(t.usedTimes--,t.usedTimes===0&&this._releasePipeline(t),t.isComputePipeline?(t.computeProgram.usedTimes--,t.computeProgram.usedTimes===0&&this._releaseProgram(t.computeProgram)):(t.fragmentProgram.usedTimes--,t.vertexProgram.usedTimes--,t.vertexProgram.usedTimes===0&&this._releaseProgram(t.vertexProgram),t.fragmentProgram.usedTimes===0&&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,i){n=n||this._getComputeCacheKey(e,t);let s=this.caches.get(n);return s===void 0&&(s=new EL(n,t),this.caches.set(n,s),this.backend.createComputePipeline(s,i)),s}_getRenderPipeline(e,t,n,i,s){i=i||this._getRenderCacheKey(e,t,n);let o=this.caches.get(i);return o===void 0&&(o=new ML(i,t,n),this.caches.set(i,o),e.pipeline=o,this.backend.createRenderPipeline(e,s)),o}_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),this.info.destroyProgram(e)}_needsComputeUpdate(e){const t=this.get(e);return t.pipeline===void 0||t.version!==e.version}_needsRenderUpdate(e){return this.get(e).pipeline===void 0||this.backend.needsRenderUpdate(e)}}class wL extends Ur{constructor(e,t,n,i,s,o){super(),this.backend=e,this.textures=n,this.pipelines=s,this.attributes=i,this.nodes=t,this.info=o,this.pipelines.bindings=this}getForRender(e){const t=e.getBindings();for(const n of t){const i=this.get(n);i.bindGroup===void 0&&(this._init(n),this.backend.createBindings(n,t,0),i.bindGroup=n)}return t}getForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const n of t){const i=this.get(n);i.bindGroup===void 0&&(this._init(n),this.backend.createBindings(n,t,0),i.bindGroup=n)}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 n of t)this.backend.deleteBindGroupData(n),this.delete(n)}deleteForRender(e){const t=e.getBindings();for(const n of t)this.backend.deleteBindGroupData(n),this.delete(n)}_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 n=t.attribute,i=n.isIndirectStorageBufferAttribute?Pi.INDIRECT:Pi.STORAGE;this.attributes.update(n,i)}}_update(e,t){const{backend:n}=this;let i=!1,s=!0,o=0,a=0;for(const l of e.bindings)if(this.nodes.updateGroup(l)!==!1){if(l.isStorageBuffer){const u=l.attribute,h=u.isIndirectStorageBufferAttribute?Pi.INDIRECT:Pi.STORAGE,d=n.get(l);this.attributes.update(u,h),d.attribute!==u&&(d.attribute=u,i=!0)}if(l.isUniformBuffer)l.update()&&n.updateBinding(l);else if(l.isSampledTexture){const u=l.update(),h=l.texture,d=this.textures.get(h);if(u&&(this.textures.updateTexture(h),l.generation!==d.generation&&(l.generation=d.generation,i=!0),d.bindGroups.add(e)),n.get(h).externalTexture!==void 0||d.isDefaultTexture?s=!1:(o=o*10+h.id,a+=h.version),h.isStorageTexture===!0&&h.mipmapsAutoUpdate===!0){const p=this.get(h);l.store===!0?p.needsMipmap=!0:this.textures.needsMipmaps(h)&&p.needsMipmap===!0&&(this.backend.generateMipmaps(h),p.needsMipmap=!1)}}else if(l.isSampler&&l.update()){const h=this.textures.updateSampler(l.texture);l.samplerKey!==h&&(l.samplerKey=h,i=!0)}l.isBuffer&&l.updateRanges.length>0&&l.clearUpdateRanges()}i===!0&&this.backend.updateBindings(e,t,s?o:0,a)}}function CL(r,e){return r.groupOrder!==e.groupOrder?r.groupOrder-e.groupOrder:r.renderOrder!==e.renderOrder?r.renderOrder-e.renderOrder:r.z!==e.z?r.z-e.z:r.id-e.id}function __(r,e){return r.groupOrder!==e.groupOrder?r.groupOrder-e.groupOrder:r.renderOrder!==e.renderOrder?r.renderOrder-e.renderOrder:r.z!==e.z?e.z-r.z:r.id-e.id}function x_(r){return(r.transmission>0||r.transmissionNode&&r.transmissionNode.isNode)&&r.side===wn&&r.forceSinglePass===!1}class NL{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,i,s,o,a){let l=this.renderItems[this.renderItemsIndex];return l===void 0?(l={id:e.id,object:e,geometry:t,material:n,groupOrder:i,renderOrder:e.renderOrder,z:s,group:o,clippingContext:a},this.renderItems[this.renderItemsIndex]=l):(l.id=e.id,l.object=e,l.geometry=t,l.material=n,l.groupOrder=i,l.renderOrder=e.renderOrder,l.z=s,l.group=o,l.clippingContext=a),this.renderItemsIndex++,l}push(e,t,n,i,s,o,a){const l=this.getNextRenderItem(e,t,n,i,s,o,a);e.occlusionTest===!0&&this.occlusionQueryCount++,n.transparent===!0||n.transmission>0||n.transmissionNode&&n.transmissionNode.isNode||n.backdropNode&&n.backdropNode.isNode?(x_(n)&&this.transparentDoublePass.push(l),this.transparent.push(l)):this.opaque.push(l)}unshift(e,t,n,i,s,o,a){const l=this.getNextRenderItem(e,t,n,i,s,o,a);n.transparent===!0||n.transmission>0||n.transmissionNode&&n.transmissionNode.isNode||n.backdropNode&&n.backdropNode.isNode?(x_(n)&&this.transparentDoublePass.unshift(l),this.transparent.unshift(l)):this.opaque.unshift(l)}pushBundle(e){this.bundles.push(e)}pushLight(e){this.lightsArray.push(e)}sort(e,t){this.opaque.length>1&&this.opaque.sort(e||CL),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||__),this.transparent.length>1&&this.transparent.sort(t||__)}finish(){this.lightsNode.setLights(this.lightsArray);for(let e=this.renderItemsIndex,t=this.renderItems.length;e>t,c=a.height>>t;let u=e.depthTexture||s[t];const h=e.depthBuffer===!0||e.stencilBuffer===!0;let d=!1;u===void 0&&h&&(u=new Xn,u.format=e.stencilBuffer?$n:Nn,u.type=e.stencilBuffer?ui:wt,u.image.width=l,u.image.height=c,u.image.depth=a.depth,u.renderTarget=e,u.isArrayTexture=e.multiview===!0&&a.depth>1,s[t]=u),(n.width!==a.width||a.height!==n.height)&&(d=!0,u&&(u.needsUpdate=!0,u.image.width=l,u.image.height=c,u.image.depth=u.isArrayTexture?u.image.depth:1)),n.width=a.width,n.height=a.height,n.textures=o,n.depthTexture=u||null,n.depth=e.depthBuffer,n.stencil=e.stencilBuffer,n.renderTarget=e,n.sampleCount!==i&&(d=!0,u&&(u.needsUpdate=!0),n.sampleCount=i);const f={sampleCount:i};if(e.isXRRenderTarget!==!0){for(let p=0;p{this._destroyRenderTarget(e)},e.addEventListener("dispose",n.onDispose))}updateTexture(e,t={}){const n=this.get(e);if(n.initialized===!0&&n.version===e.version)return;const i=e.isRenderTargetTexture||e.isDepthTexture||e.isFramebufferTexture,s=this.backend;if(i&&n.initialized===!0&&s.destroyTexture(e),e.isFramebufferTexture){const c=this.renderer.getRenderTarget();c?e.type=c.texture.type:e.type=$t}if(e.isHTMLTexture&&e.image){const c=this.renderer.domElement;if("requestPaint"in c){if(c.hasAttribute("layoutsubtree")||c.setAttribute("layoutsubtree","true"),e.image.parentNode!==c&&c.appendChild(e.image),this._htmlTextures.size===0){const u=this._htmlTextures;c.onpaint=h=>{const d=h&&h.changedElements;for(const f of u)(!d||d.includes(f.image))&&(f.needsUpdate=!0)}}this._htmlTextures.add(e)}}const{width:o,height:a,depth:l}=this.getSize(e);if(t.width=o,t.height=a,t.depth=l,t.needsMipmaps=this.needsMipmaps(e),t.levels=t.needsMipmaps?this.getMipLevels(e,o,a):1,e.isCubeTexture&&e.mipmaps.length>0&&t.levels++,i||e.isStorageTexture===!0||e.isExternalTexture===!0)s.createTexture(e,t),n.generation=e.version;else if(e.version>0){const c=e.image;if(c===void 0)ee("Renderer: Texture marked for update but image is undefined.");else if(c.complete===!1)ee("Renderer: Texture marked for update but image is incomplete.");else{if(e.images){const h=[];for(const d of e.images)h.push(d);t.images=h}else t.image=c;(n.isDefaultTexture===void 0||n.isDefaultTexture===!0)&&(s.createTexture(e,t),n.isDefaultTexture=!1,n.generation=e.version),e.source.dataReady===!0&&s.updateTexture(e,t);const u=e.isStorageTexture===!0&&e.mipmapsAutoUpdate===!1;t.needsMipmaps&&e.mipmaps.length===0&&!u&&s.generateMipmaps(e),e.onUpdate&&e.onUpdate(e)}}else s.createDefaultTexture(e),n.isDefaultTexture=!0,n.generation=e.version;n.initialized!==!0&&(n.initialized=!0,n.generation=e.version,n.bindGroups=new Set,this.info.createTexture(e),e.isVideoTexture&&Xe.enabled===!0&&Xe.getTransfer(e.colorSpace)!==Ee&&ee("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=FL){let n=e.images?e.images[0]:e.image;return n?(n.image!==void 0&&(n=n.image),e.isHTMLTexture?(t.width=n.offsetWidth||1,t.height=n.offsetHeight||1,t.depth=1):typeof HTMLVideoElement<"u"&&n instanceof HTMLVideoElement?(t.width=n.videoWidth||1,t.height=n.videoHeight||1,t.depth=1):typeof VideoFrame<"u"&&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 i;return e.mipmaps.length>0?i=e.mipmaps.length:e.isCompressedTexture===!0?i=1:i=Math.floor(Math.log2(Math.max(t,n)))+1,i}needsMipmaps(e){return e.generateMipmaps===!0||e.mipmaps.length>0}_destroyRenderTarget(e){if(this.has(e)===!0){const t=this.get(e),n=t.textures,i=t.depthTexture;e.removeEventListener("dispose",t.onDispose);for(let s=0;s=2)for(let a=0;a{if(this._currentNode=c,!(c.isVarNode&&c.isIntent(e)&&c.isAssign(e)!==!0)){if(i==="setup")c.build(e);else if(i==="analyze")c.build(e,this);else if(i==="generate"){const u=e.getDataFromNode(c,"any").stages,h=u&&u[e.shaderStage];if(c.isVarNode&&h&&h.length===1&&h[0]&&h[0].isStackNode)return;c.build(e,"void")}}},o=[...this.nodes];for(const c of o)s(c);this._currentNode=null;const a=this.nodes.filter(c=>o.indexOf(c)===-1);for(const c of a)s(c);let l;return this.hasOutput(e)?l=this.outputNode.build(e,...t):l=super.build(e,...t),Ou(n),e.removeActiveStack(this),l}}const Cd=Ft(OL).setParameterLength(0,1);class Hy extends _n{static get type(){return"BitcastNode"}constructor(e,t,n=null){super(),this.valueNode=e,this.conversionType=t,this.inputType=n,this.isBitcastNode=!0}generateNodeType(e){if(this.inputType!==null){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(this.inputType!==null){const i=this.valueNode.getNodeType(e);n=e.getTypeLength(i)===1?this.inputType:e.changeComponentType(i,this.inputType)}else n=this.valueNode.getNodeType(e);return`${e.getBitcastMethod(t,n)}( ${this.valueNode.build(e,n)} )`}}const kL=Se(Hy).setParameterLength(2),GL=r=>new Hy(r,"uint","float"),su={};class io extends I{static get type(){return"BitcountNode"}constructor(e,t){super(e,t),this.isBitcountNode=!0}_resolveElementType(e,t,n){n==="int"?t.assign(kL(e,"uint")):t.assign(e)}_returnDataNode(e){switch(e){case"uint":return ht;case"int":return Kt;case"uvec2":return y0;case"uvec3":return S0;case"uvec4":return T0;case"ivec2":return ls;case"ivec3":return v0;case"ivec4":return b0}}_createTrailingZerosBaseLayout(e,t){const n=this._returnDataNode(t);return Q(([s])=>{const o=ht(0);this._resolveElementType(s,o,t);const a=j(o.bitAnd(L0(o))),c=GL(a).shiftRight(23).sub(127);return n(c)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}_createLeadingZerosBaseLayout(e,t){const n=this._returnDataNode(t);return Q(([s])=>{Lt(s.equal(ht(0)),()=>ht(32));const o=ht(0),a=ht(0);return this._resolveElementType(s,o,t),Lt(o.shiftRight(16).equal(0),()=>{a.addAssign(16),o.shiftLeftAssign(16)}),Lt(o.shiftRight(24).equal(0),()=>{a.addAssign(8),o.shiftLeftAssign(8)}),Lt(o.shiftRight(28).equal(0),()=>{a.addAssign(4),o.shiftLeftAssign(4)}),Lt(o.shiftRight(30).equal(0),()=>{a.addAssign(2),o.shiftLeftAssign(2)}),Lt(o.shiftRight(31).equal(0),()=>{a.addAssign(1)}),n(a)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}_createOneBitsBaseLayout(e,t){const n=this._returnDataNode(t);return Q(([s])=>{const o=ht(0);this._resolveElementType(s,o,t),o.assign(o.sub(o.shiftRight(ht(1)).bitAnd(ht(1431655765)))),o.assign(o.bitAnd(ht(858993459)).add(o.shiftRight(ht(2)).bitAnd(ht(858993459))));const a=o.add(o.shiftRight(ht(4))).bitAnd(ht(252645135)).mul(ht(16843009)).shiftRight(ht(24));return n(a)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}_createMainLayout(e,t,n,i){const s=this._returnDataNode(t);return Q(([a])=>{if(n===1)return s(i(a));{const l=s(0),c=["x","y","z","w"];for(let u=0;uh(n))()}}io.COUNT_TRAILING_ZEROS="countTrailingZeros";io.COUNT_LEADING_ZEROS="countLeadingZeros";io.COUNT_ONE_BITS="countOneBits";new dt;const VL=new Lr;no.flipX();VL.depthTexture=new Xn(1,1);const Nd=new Va(-1,1,1,-1,0,1);class zL extends Pn{constructor(e=!1){super();const t=e===!1?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new sn([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new sn(t,2))}}const HL=new zL;class Wy extends gn{constructor(e=null){super(HL,e),this.camera=Nd,this.isQuadMesh=!0}async renderAsync(e){Yt('QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await e.init(),e.render(this,Nd)}render(e){e.render(this,Nd)}}const $y=Q(([r])=>Ss(j(52.9829189).mul(Ss(uo(r,Ie(.06711056,.00583715)))))).setLayout({name:"interleavedGradientNoise",type:"float",inputs:[{name:"position",type:"vec2"}]}),ds=Q(([r,e,t])=>{const n=j(2.399963229728653),i=Er(j(r).add(.5).div(j(e))),s=j(r).mul(n).add(t);return Ie(cs(s),xi(s)).mul(i)}).setLayout({name:"vogelDiskSample",type:"vec2",inputs:[{name:"sampleIndex",type:"int"},{name:"samplesCount",type:"int"},{name:"phi",type:"float"}]});class vi extends Oe{static get type(){return"EventNode"}constructor(e,t){super("void"),this.eventType=e,this.callback=t,e===vi.OBJECT?this.updateType=je.OBJECT:e===vi.MATERIAL?this.updateType=je.RENDER:e===vi.FRAME?this.updateType=je.FRAME:e===vi.BEFORE_OBJECT?this.updateBeforeType=je.OBJECT:e===vi.BEFORE_MATERIAL?this.updateBeforeType=je.RENDER:e===vi.BEFORE_FRAME&&(this.updateBeforeType=je.FRAME)}update(e){this.callback(e)}updateBefore(e){this.callback(e)}}vi.OBJECT="object";vi.MATERIAL="material";vi.FRAME="frame";vi.BEFORE_OBJECT="beforeObject";vi.BEFORE_MATERIAL="beforeMaterial";vi.BEFORE_FRAME="beforeFrame";const Pd=new dt,WL=We(0).setGroup(qe).onRenderUpdate(({scene:r})=>r.backgroundBlurriness),y_=We(1).setGroup(qe).onRenderUpdate(({scene:r})=>r.backgroundIntensity),$L=We(new dt).setGroup(qe).onRenderUpdate(({scene:r})=>{const e=r.background;return e!==null&&e.isTexture&&e.mapping!==Yf?Pd.makeRotationFromEuler(r.backgroundRotation).transpose():Pd.identity(),Pd});Q(({texture:r,uv:e})=>{const n=K().toVar();return Lt(e.x.lessThan(1e-4),()=>{n.assign(K(1,0,0))}).ElseIf(e.y.lessThan(1e-4),()=>{n.assign(K(0,1,0))}).ElseIf(e.z.lessThan(1e-4),()=>{n.assign(K(0,0,1))}).ElseIf(e.x.greaterThan(1-1e-4),()=>{n.assign(K(-1,0,0))}).ElseIf(e.y.greaterThan(1-1e-4),()=>{n.assign(K(0,-1,0))}).ElseIf(e.z.greaterThan(1-1e-4),()=>{n.assign(K(0,0,-1))}).Else(()=>{const s=r.sample(e.add(K(-.01,0,0))).r.sub(r.sample(e.add(K(.01,0,0))).r),o=r.sample(e.add(K(0,-.01,0))).r.sub(r.sample(e.add(K(0,.01,0))).r),a=r.sample(e.add(K(0,0,-.01))).r.sub(r.sample(e.add(K(0,0,.01))).r);n.assign(K(s,o,a))}),n.normalize()});Q(([r,e])=>r.mul(e).floor().div(e));const ru=new de;class XL extends pc{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.isPassTextureNode=!0,this.setUpdateMatrix(!1)}setup(e){const t=e.getNodeProperties(this);return t.passNode=this.passNode,super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class v_ extends XL{static get type(){return"PassMultipleTextureNode"}constructor(e,t,n=!1){super(e,null),this.textureName=t,this.previousTexture=n,this.isPassMultipleTextureNode=!0}updateTexture(){this.value=this.previousTexture?this.passNode.getPreviousTexture(this.textureName):this.passNode.getTexture(this.textureName)}setup(e){return this.updateTexture(),super.setup(e)}clone(){const e=new this.constructor(this.passNode,this.textureName,this.previousTexture);return e.uvNode=this.uvNode,e.levelNode=this.levelNode,e.biasNode=this.biasNode,e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e}}class fh extends _n{static get type(){return"PassNode"}constructor(e,t,n,i={}){super("vec4"),this.scope=e,this.scene=t,this.camera=n,this.options=i,this._pixelRatio=1,this._width=1,this._height=1;const s=new Xn;s.isRenderTargetTexture=!0,s.name="depth";const o=new Lr(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:en,...i});o.texture.name="output",o.depthTexture=s,this.renderTarget=o,this.overrideMaterial=null,this.transparent=!0,this.opaque=!0,this.contextNode=null,this._contextNodeCache=null,this._textures={output:o.texture,depth:s},this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=We(0),this._cameraFar=We(0),this._mrt=null,this._layers=null,this._resolutionScale=1,this._viewport=null,this._scissor=null,this.isPassNode=!0,this.updateBeforeType=je.FRAME,this.global=!0}setResolutionScale(e){return this._resolutionScale=e,this}getResolutionScale(){return this._resolutionScale}setResolution(e){return ee("PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead."),this.setResolutionScale(e)}getResolution(){return ee("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];return t===void 0&&(t=this.renderTarget.texture.clone(),t.name=e,this._textures[e]=t,this.renderTarget.textures.push(t)),t}getPreviousTexture(e){let t=this._previousTextures[e];return t===void 0&&(t=this.getTexture(e).clone(),this._previousTextures[e]=t),t}toggleTexture(e){const t=this._previousTextures[e];if(t!==void 0){const n=this._textures[e],i=this.renderTarget.textures.indexOf(n);this.renderTarget.textures[i]=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 t===void 0&&(t=new v_(this,e),t.updateTexture(),this._textureNodes[e]=t),t}getPreviousTextureNode(e="output"){let t=this._previousTextureNodes[e];return t===void 0&&(this._textureNodes[e]===void 0&&this.getTextureNode(e),t=new v_(this,e,!0),t.updateTexture(),this._previousTextureNodes[e]=t),t}getViewZNode(e="depth"){let t=this._viewZNodes[e];if(t===void 0){const n=this._cameraNear,i=this._cameraFar;this._viewZNodes[e]=t=yy(this.getTextureNode(e),n,i)}return t}getLinearDepthNode(e="depth"){let t=this._linearDepthNodes[e];if(t===void 0){const n=this._cameraNear,i=this._cameraFar,s=this.getViewZNode(e);this._linearDepthNodes[e]=t=Dl(s,n,i)}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=this.options.samples===void 0?e.samples:this.options.samples,this.renderTarget.texture.type=e.getOutputBufferType(),e.reversedDepthBuffer===!0&&(this.renderTarget.depthTexture.type=Zt),this.scope===fh.COLOR?this.getTextureNode():this.getLinearDepthNode()}updateBefore(e){const{renderer:t}=e,{scene:n}=this;let i,s;const o=t.getOutputRenderTarget();o&&o.isXRRenderTarget===!0?(s=1,i=t.xr.getCamera(),t.xr.updateCamera(i),ru.set(o.width,o.height)):(i=this.camera,s=t.getPixelRatio(),t.getSize(ru)),this._pixelRatio=s,this.setSize(ru.width,ru.height);const a=t.getRenderTarget(),l=t.getMRT(),c=t.autoClear,u=t.transparent,h=t.opaque,d=i.layers.mask,f=t.contextNode,p=n.overrideMaterial;this._cameraNear.value=i.near,this._cameraFar.value=i.far,this._layers!==null&&(i.layers.mask=this._layers.mask);for(const m in this._previousTextures)this.toggleTexture(m);this.overrideMaterial!==null&&(n.overrideMaterial=this.overrideMaterial),t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.autoClear=!0,t.transparent=this.transparent,t.opaque=this.opaque,this.contextNode!==null&&((this._contextNodeCache===null||this._contextNodeCache.version!==this.version)&&(this._contextNodeCache={version:this.version,context:So({...t.contextNode.getFlowContextData(),...this.contextNode.getFlowContextData()})}),t.contextNode=this._contextNodeCache.context);const g=n.name;n.name=this.name?this.name:n.name,t.render(n,i),n.name=g,n.overrideMaterial=p,t.setRenderTarget(a),t.setMRT(l),t.autoClear=c,t.transparent=u,t.opaque=h,t.contextNode=f,i.layers.mask=d}setSize(e,t){this._width=e,this._height=t;const n=Math.floor(this._width*this._pixelRatio*this._resolutionScale),i=Math.floor(this._height*this._pixelRatio*this._resolutionScale);this.renderTarget.setSize(n,i),this._scissor!==null?(this.renderTarget.scissor.copy(this._scissor).multiplyScalar(this._pixelRatio*this._resolutionScale).floor(),this.renderTarget.scissorTest=!0):this.renderTarget.scissorTest=!1,this._viewport!==null&&this.renderTarget.viewport.copy(this._viewport).multiplyScalar(this._pixelRatio*this._resolutionScale).floor()}setScissor(e,t,n,i){e===null?this._scissor=null:(this._scissor===null&&(this._scissor=new tt),e.isVector4?this._scissor.copy(e):this._scissor.set(e,t,n,i))}setViewport(e,t,n,i){e===null?this._viewport=null:(this._viewport===null&&(this._viewport=new tt),e.isVector4?this._viewport.copy(e):this._viewport.set(e,t,n,i))}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}fh.COLOR="color";fh.DEPTH="depth";const qL=Q(([r,e])=>r.mul(e).clamp()).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),jL=Q(([r,e])=>(r=r.mul(e),r.div(r.add(1)).clamp())).setLayout({name:"reinhardToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),YL=Q(([r,e])=>{r=r.mul(e),r=r.sub(.004).max(0);const t=r.mul(r.mul(6.2).add(.5)),n=r.mul(r.mul(6.2).add(1.7)).add(.06);return t.div(n).pow(2.2)}).setLayout({name:"cineonToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),KL=Q(([r])=>{const e=r.mul(r.add(.0245786)).sub(90537e-9),t=r.mul(r.add(.432951).mul(.983729)).add(.238081);return e.div(t)}),ZL=Q(([r,e])=>{const t=Bn(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),n=Bn(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return r=r.mul(e).div(.6),r=t.mul(r),r=KL(r),r=n.mul(r),r.clamp()}).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),QL=Bn(K(1.6605,-.1246,-.0182),K(-.5876,1.1329,-.1006),K(-.0728,-.0083,1.1187)),JL=Bn(K(.6274,.0691,.0164),K(.3293,.9195,.088),K(.0433,.0113,.8956)),eU=Q(([r])=>{const e=K(r).toVar(),t=K(e.mul(e)).toVar(),n=K(t.mul(t)).toVar();return j(15.5).mul(n.mul(t)).sub(nt(40.14,n.mul(e))).add(nt(31.96,n).sub(nt(6.868,t.mul(e))).add(nt(.4298,t).add(nt(.1191,e).sub(.00232))))}),tU=Q(([r,e])=>{const t=K(r).toVar(),n=Bn(K(.856627153315983,.137318972929847,.11189821299995),K(.0951212405381588,.761241990602591,.0767994186031903),K(.0482516061458583,.101439036467562,.811302368396859)),i=Bn(K(1.1271005818144368,-.1413297634984383,-.14132976349843826),K(-.11060664309660323,1.157823702216272,-.11060664309660294),K(-.016493938717834573,-.016493938717834257,1.2519364065950405)),s=j(-12.47393),o=j(4.026069);return t.mulAssign(e),t.assign(JL.mul(t)),t.assign(n.mul(t)),t.assign(On(t,1e-10)),t.assign(Hs(t)),t.assign(t.sub(s).div(o.sub(s))),t.assign(Cr(t,0,1)),t.assign(eU(t)),t.assign(i.mul(t)),t.assign(oh(On(K(0),t),K(2.2))),t.assign(QL.mul(t)),t.assign(Cr(t,0,1)),t}).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),nU=Q(([r,e])=>{const t=j(.76),n=j(.15);r=r.mul(e);const i=Ua(r.r,Ua(r.g,r.b)),s=Si(i.lessThan(.08),i.sub(nt(6.25,i.mul(i))),.04);r.subAssign(s);const o=On(r.r,On(r.g,r.b));Lt(o.lessThan(t),()=>r);const a=si(1,t),l=si(1,a.mul(a).div(o.add(a.sub(t))));r.mulAssign(l.div(o));const c=si(1,vs(1,n.mul(o.sub(l)).add(1)));return Nt(r,K(l),c)}).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class An extends Oe{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 i of t)i.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 iU extends An{static get type(){return"FunctionNode"}constructor(e="",t=[],n=""){super(e,t,n)}generateNodeType(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 n===void 0&&(n=e.parser.parseFunction(this.code),t.nodeFunction=n),n}generate(e,t){super.generate(e);const n=this.getNodeFunction(e),i=n.name,s=n.type,o=e.getCodeFromNode(this,s);i!==""&&(o.name=i);const a=e.getPropertyName(o),l=this.getNodeFunction(e).getCode(a);return o.code=l+` `,t==="property"?a:e.format(`${a}()`,s,t)}}function Hp(r){let e;const t=r.context.getViewZ;return t!==void 0&&(e=t(this)),(e||hn.z).negate()}const sU=Q(([r,e],t)=>{const n=Hp(t);return Xs(r,e,n)}),rU=Q(([r],e)=>{const t=Hp(e);return r.mul(r,t,t).negate().exp().oneMinus()});Q(([r,e],t)=>{const n=Hp(t),s=e.sub(Fa.y).max(0).toConst().mul(n).toConst();return r.mul(r,s,s).negate().exp().oneMinus()});const S_=Q(([r,e])=>Ze(e.toFloat().mix(Cl.rgb,r.toVec3()),Cl.a));class oU extends Oe{constructor(e){super(),this.scope=e,this.isBarrierNode=!0}setup(e){e.allowEarlyReturns=!1,e.allowGlobalVariables=!1}generate(e){const{scope:t}=this,{renderer:n}=e;n.backend.isWebGLBackend===!0?e.addFlowCode(` // ${t}Barrier `):e.addLineFlowCode(`${t}Barrier()`,this)}}Ft(oU);class Ms extends Oe{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)}generateNodeType(e){return this.getInputType(e)}generate(e){const t=e.getNodeProperties(this),n=t.parents,i=this.method,s=this.getNodeType(e),o=this.getInputType(e),a=this.pointerNode,l=this.valueNode,c=[];c.push(`&${a.build(e,o)}`),l!==null&&c.push(l.build(e,o));const u=`${e.getMethod(i,s)}( ${c.join(", ")} )`;if(n?n.length===1&&n[0].isStackNode===!0:!1)e.addLineFlowCode(u,this);else return t.constNode===void 0&&(t.constNode=hs(u,s).toConst()),t.constNode.build(e)}}Ms.ATOMIC_LOAD="atomicLoad";Ms.ATOMIC_STORE="atomicStore";Ms.ATOMIC_ADD="atomicAdd";Ms.ATOMIC_SUB="atomicSub";Ms.ATOMIC_MAX="atomicMax";Ms.ATOMIC_MIN="atomicMin";Ms.ATOMIC_AND="atomicAnd";Ms.ATOMIC_OR="atomicOr";Ms.ATOMIC_XOR="atomicXor";Ft(Ms);class yt extends _n{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,i=e.isMatrix(t)?0:e.getTypeLength(t),s=e.isMatrix(n)?0:e.getTypeLength(n);return i>s?t:n}generateNodeType(e){const t=this.method;return t===yt.SUBGROUP_ELECT?"bool":t===yt.SUBGROUP_BALLOT?"uvec4":this.getInputType(e)}generate(e,t){const n=this.method,i=this.getNodeType(e),s=this.getInputType(e),o=this.aNode,a=this.bNode,l=[];if(n===yt.SUBGROUP_BROADCAST||n===yt.SUBGROUP_SHUFFLE||n===yt.QUAD_BROADCAST){const u=a.getNodeType(e);l.push(o.build(e,i),a.build(e,u==="float"?"int":i))}else n===yt.SUBGROUP_SHUFFLE_XOR||n===yt.SUBGROUP_SHUFFLE_DOWN||n===yt.SUBGROUP_SHUFFLE_UP?l.push(o.build(e,i),a.build(e,"uint")):(o!==null&&l.push(o.build(e,s)),a!==null&&l.push(a.build(e,s)));const c=l.length===0?"()":`( ${l.join(", ")} )`;return e.format(`${e.getMethod(n,i)}${c}`,i,t)}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}yt.SUBGROUP_ELECT="subgroupElect";yt.SUBGROUP_BALLOT="subgroupBallot";yt.SUBGROUP_ADD="subgroupAdd";yt.SUBGROUP_INCLUSIVE_ADD="subgroupInclusiveAdd";yt.SUBGROUP_EXCLUSIVE_AND="subgroupExclusiveAdd";yt.SUBGROUP_MUL="subgroupMul";yt.SUBGROUP_INCLUSIVE_MUL="subgroupInclusiveMul";yt.SUBGROUP_EXCLUSIVE_MUL="subgroupExclusiveMul";yt.SUBGROUP_AND="subgroupAnd";yt.SUBGROUP_OR="subgroupOr";yt.SUBGROUP_XOR="subgroupXor";yt.SUBGROUP_MIN="subgroupMin";yt.SUBGROUP_MAX="subgroupMax";yt.SUBGROUP_ALL="subgroupAll";yt.SUBGROUP_ANY="subgroupAny";yt.SUBGROUP_BROADCAST_FIRST="subgroupBroadcastFirst";yt.QUAD_SWAP_X="quadSwapX";yt.QUAD_SWAP_Y="quadSwapY";yt.QUAD_SWAP_DIAGONAL="quadSwapDiagonal";yt.SUBGROUP_BROADCAST="subgroupBroadcast";yt.SUBGROUP_SHUFFLE="subgroupShuffle";yt.SUBGROUP_SHUFFLE_XOR="subgroupShuffleXor";yt.SUBGROUP_SHUFFLE_UP="subgroupShuffleUp";yt.SUBGROUP_SHUFFLE_DOWN="subgroupShuffleDown";yt.QUAD_BROADCAST="quadBroadcast";let ou;function ph(r){ou=ou||new WeakMap;let e=ou.get(r);return e===void 0&&ou.set(r,e={}),e}function Wp(r){const e=ph(r);return e.shadowMatrix||(e.shadowMatrix=We("mat4").setGroup(qe).onRenderUpdate(t=>((r.castShadow!==!0||t.renderer.shadowMap.enabled===!1)&&(r.shadow.camera.coordinateSystem!==t.camera.coordinateSystem&&(r.shadow.camera.coordinateSystem=t.camera.coordinateSystem,r.shadow.camera.updateProjectionMatrix()),r.shadow.updateMatrices(r)),r.shadow.matrix)))}function aU(r,e=Fa){const t=Wp(r).mul(e);return t.xyz.div(t.w)}function Xy(r){const e=ph(r);return e.position||(e.position=We(new C).setGroup(qe).onRenderUpdate((t,n)=>n.value.setFromMatrixPosition(r.matrixWorld)))}function lU(r){const e=ph(r);return e.targetPosition||(e.targetPosition=We(new C).setGroup(qe).onRenderUpdate((t,n)=>n.value.setFromMatrixPosition(r.target.matrixWorld)))}function qy(r){const e=ph(r);return e.viewPosition||(e.viewPosition=We(new C).setGroup(qe).onRenderUpdate(({camera:t},n)=>{n.value=n.value||new C,n.value.setFromMatrixPosition(r.matrixWorld),n.value.applyMatrix4(t.matrixWorldInverse)}))}const jy=r=>js.transformDirection(Xy(r).sub(lU(r))),cU=r=>r.sort((e,t)=>e.id-t.id),uU=(r,e)=>{for(const t of e)if(t.isAnalyticLightNode&&t.light.id===r)return t;return null},Dd=new WeakMap,dl=[];class Yy extends Oe{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=Mr("vec3","totalDiffuse"),this.totalSpecularNode=Mr("vec3","totalSpecular"),this.outgoingLightNode=Mr("vec3","outgoingLight"),this._lights=[],this._lightNodes=null,this._lightNodesHash=null,this.global=!0}customCacheKey(){const e=this._lights;for(let n=0;n0}}class hU extends Oe{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=je.RENDER,this.isShadowBaseNode=!0}setupShadowPosition({context:e,material:t}){Ky.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||Fa)}}const Ky=Mr("vec3","shadowPositionWorld");function dU(r,e={}){return e.toneMapping=r.toneMapping,e.toneMappingExposure=r.toneMappingExposure,e.outputColorSpace=r.outputColorSpace,e.renderTarget=r.getRenderTarget(),e.activeCubeFace=r.getActiveCubeFace(),e.activeMipmapLevel=r.getActiveMipmapLevel(),e.renderObjectFunction=r.getRenderObjectFunction(),e.pixelRatio=r.getPixelRatio(),e.mrt=r.getMRT(),e.clearColor=r.getClearColor(e.clearColor||new Ve),e.clearAlpha=r.getClearAlpha(),e.autoClear=r.autoClear,e.scissorTest=r.getScissorTest(),e}function fU(r,e){return e=dU(r,e),r.setMRT(null),r.setRenderObjectFunction(null),r.setClearColor(0,1),r.autoClear=!0,e}function pU(r,e){r.toneMapping=e.toneMapping,r.toneMappingExposure=e.toneMappingExposure,r.outputColorSpace=e.outputColorSpace,r.setRenderTarget(e.renderTarget,e.activeCubeFace,e.activeMipmapLevel),r.setRenderObjectFunction(e.renderObjectFunction),r.setPixelRatio(e.pixelRatio),r.setMRT(e.mrt),r.setClearColor(e.clearColor,e.clearAlpha),r.autoClear=e.autoClear,r.setScissorTest(e.scissorTest)}function mU(r,e={}){return e.background=r.background,e.backgroundNode=r.backgroundNode,e.overrideMaterial=r.overrideMaterial,e}function gU(r,e){return e=mU(r,e),r.background=null,r.backgroundNode=null,r.overrideMaterial=null,e}function _U(r,e){r.background=e.background,r.backgroundNode=e.backgroundNode,r.overrideMaterial=e.overrideMaterial}function xU(r,e,t){return t=fU(r,t),t=gU(e,t),t}function yU(r,e,t){pU(r,t),_U(e,t)}const Wu=new WeakMap,vU=Q(({depthTexture:r,shadowCoord:e,depthLayer:t})=>{let n=Gt(r,e.xy).setName("t_basic");return r.isArrayTexture&&(n=n.depth(t)),n.compare(e.z)}),SU=Q(({depthTexture:r,shadowCoord:e,shadow:t,depthLayer:n})=>{const i=(u,h)=>{let d=Gt(r,u);return r.isArrayTexture&&(d=d.depth(n)),d.compare(h)},s=Qt("mapSize","vec2",t).setGroup(qe),o=Qt("radius","float",t).setGroup(qe),a=Ie(1).div(s),l=o.mul(a.x),c=$y(ja.xy).mul(6.28318530718);return hi(i(e.xy.add(ds(0,5,c).mul(l)),e.z),i(e.xy.add(ds(1,5,c).mul(l)),e.z),i(e.xy.add(ds(2,5,c).mul(l)),e.z),i(e.xy.add(ds(3,5,c).mul(l)),e.z),i(e.xy.add(ds(4,5,c).mul(l)),e.z)).mul(1/5)}),bU=Q(({depthTexture:r,shadowCoord:e,shadow:t,depthLayer:n})=>{const i=(h,d)=>{let f=Gt(r,h);return r.isArrayTexture&&(f=f.depth(n)),f.compare(d)},s=Qt("mapSize","vec2",t).setGroup(qe),o=Ie(1).div(s),a=o.x,l=o.y,c=e.xy,u=Ss(c.mul(s).add(.5));return c.subAssign(u.mul(o)),hi(i(c,e.z),i(c.add(Ie(a,0)),e.z),i(c.add(Ie(0,l)),e.z),i(c.add(o),e.z),Nt(i(c.add(Ie(a.negate(),0)),e.z),i(c.add(Ie(a.mul(2),0)),e.z),u.x),Nt(i(c.add(Ie(a.negate(),l)),e.z),i(c.add(Ie(a.mul(2),l)),e.z),u.x),Nt(i(c.add(Ie(0,l.negate())),e.z),i(c.add(Ie(0,l.mul(2))),e.z),u.y),Nt(i(c.add(Ie(a,l.negate())),e.z),i(c.add(Ie(a,l.mul(2))),e.z),u.y),Nt(Nt(i(c.add(Ie(a.negate(),l.negate())),e.z),i(c.add(Ie(a.mul(2),l.negate())),e.z),u.x),Nt(i(c.add(Ie(a.negate(),l.mul(2))),e.z),i(c.add(Ie(a.mul(2),l.mul(2))),e.z),u.x),u.y)).mul(1/9)}),TU=Q(({depthTexture:r,shadowCoord:e,depthLayer:t},n)=>{let i=Gt(r).sample(e.xy);r.isArrayTexture&&(i=i.depth(t)),i=i.rg;const s=i.x,o=On(1e-7,i.y.mul(i.y)),a=n.renderer.reversedDepthBuffer?Ql(s,e.z):Ql(e.z,s),l=j(1).toVar();return Lt(a.notEqual(1),()=>{const c=e.z.sub(s);let u=o.div(o.add(c.mul(c)));u=Cr(si(u,.3).div(.65)),l.assign(On(a,u))}),l}),MU=r=>{let e=Wu.get(r);return e===void 0&&(e=new dn,e.colorNode=Ze(0,0,0,1),e.isShadowPassMaterial=!0,e.name="ShadowMaterial",e.blending=Cn,e.fog=!1,Wu.set(r,e)),e},EU=r=>{const e=Wu.get(r);e!==void 0&&(e.dispose(),Wu.delete(r))},b_=new Pr,Vo=[],AU=(r,e,t,n)=>{Vo[0]=r,Vo[1]=e;let i=b_.get(Vo);return(i===void 0||i.shadowType!==t||i.useVelocity!==n)&&(i=(s,o,a,l,c,u,...h)=>{(s.castShadow===!0||s.receiveShadow&&t===fs)&&(n&&(f0(s).useVelocity=!0),s.onBeforeShadow(r,s,a,e.camera,l,o.overrideMaterial,u),r.renderObject(s,o,a,l,c,u,...h),s.onAfterShadow(r,s,a,e.camera,l,o.overrideMaterial,u))},i.shadowType=t,i.useVelocity=n,b_.set(Vo,i)),Vo[0]=null,Vo[1]=null,i},RU=Q(({samples:r,radius:e,size:t,shadowPass:n,depthLayer:i})=>{const s=j(0).toVar("meanVertical"),o=j(0).toVar("squareMeanVertical"),a=r.lessThanEqual(j(1)).select(j(0),j(2).div(r.sub(1))),l=r.lessThanEqual(j(1)).select(j(0),j(-1));wi({start:Kt(0),end:Kt(r),type:"int",condition:"<"},({i:u})=>{const h=l.add(j(u).mul(a));let d=n.sample(hi(ja.xy,Ie(0,h).mul(e)).div(t));n.value.isArrayTexture&&(d=d.depth(i)),d=d.x,s.addAssign(d),o.addAssign(d.mul(d))}),s.divAssign(r),o.divAssign(r);const c=Er(o.sub(s.mul(s)).max(0));return Ie(s,c)}),wU=Q(({samples:r,radius:e,size:t,shadowPass:n,depthLayer:i})=>{const s=j(0).toVar("meanHorizontal"),o=j(0).toVar("squareMeanHorizontal"),a=r.lessThanEqual(j(1)).select(j(0),j(2).div(r.sub(1))),l=r.lessThanEqual(j(1)).select(j(0),j(-1));wi({start:Kt(0),end:Kt(r),type:"int",condition:"<"},({i:u})=>{const h=l.add(j(u).mul(a));let d=n.sample(hi(ja.xy,Ie(h,0).mul(e)).div(t));n.value.isArrayTexture&&(d=d.depth(i)),s.addAssign(d.x),o.addAssign(hi(d.y.mul(d.y),d.x.mul(d.x)))}),s.divAssign(r),o.divAssign(r);const c=Er(o.sub(s.mul(s)).max(0));return Ie(s,c)}),CU=[vU,SU,bU,TU];let Ld;const au=new Wy;class Zy extends hU{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:i,shadow:s,depthLayer:o}){const a=i.x.greaterThanEqual(0).and(i.x.lessThanEqual(1)).and(i.y.greaterThanEqual(0)).and(i.y.lessThanEqual(1)).and(i.z.lessThanEqual(1)),l=t({depthTexture:n,shadowCoord:i,shadow:s,depthLayer:o});return a.select(l,j(1))}setupShadowCoord(e,t){const{shadow:n}=this,{renderer:i}=e,s=n.biasNode||Qt("bias","float",n).setGroup(qe);let o=t,a;if(n.camera.isOrthographicCamera||i.logarithmicDepthBuffer!==!0)o=o.xyz.div(o.w),a=o.z;else{const l=o.w;o=o.xy.div(l);const c=Qt("near","float",n.camera).setGroup(qe),u=Qt("far","float",n.camera).setGroup(qe);a=vy(l.negate(),c,u)}return o=K(o.x,o.y.oneMinus(),i.reversedDepthBuffer?a.sub(s):a.add(s)),o}getShadowFilterFn(e){return CU[e]}setupRenderTarget(e,t){const n=new Xn(e.mapSize.width,e.mapSize.height);n.name="ShadowDepthTexture",n.compareFunction=t.renderer.reversedDepthBuffer?$s:Dr;const i=t.createRenderTarget(e.mapSize.width,e.mapSize.height);return i.texture.name="ShadowMap",i.texture.type=e.mapType,i.depthTexture=n,{shadowMap:i,depthTexture:n}}setupShadow(e){const{renderer:t,camera:n}=e,{light:i,shadow:s}=this,{depthTexture:o,shadowMap:a}=this.setupRenderTarget(s,e),l=t.shadowMap.type,c=t.hasCompatibility(_o.TEXTURE_COMPARE);if((l===Yo||l===hx)&&c?(o.minFilter=Ut,o.magFilter=Ut):(o.minFilter=bt,o.magFilter=bt),s.camera.coordinateSystem=n.coordinateSystem,s.camera.updateProjectionMatrix(),l===fs&&s.isPointLightShadow!==!0){o.compareFunction=null,a.depth>1?(a._vsmShadowMapVertical||(a._vsmShadowMapVertical=e.createRenderTarget(s.mapSize.width,s.mapSize.height,{format:Fn,type:en,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapVertical.texture.name="VSMVertical"),this.vsmShadowMapVertical=a._vsmShadowMapVertical,a._vsmShadowMapHorizontal||(a._vsmShadowMapHorizontal=e.createRenderTarget(s.mapSize.width,s.mapSize.height,{format:Fn,type:en,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapHorizontal.texture.name="VSMHorizontal"),this.vsmShadowMapHorizontal=a._vsmShadowMapHorizontal):(this.vsmShadowMapVertical=e.createRenderTarget(s.mapSize.width,s.mapSize.height,{format:Fn,type:en,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(s.mapSize.width,s.mapSize.height,{format:Fn,type:en,depthBuffer:!1}));let T=Gt(o);o.isArrayTexture&&(T=T.depth(this.depthLayer));let A=Gt(this.vsmShadowMapVertical.texture);o.isArrayTexture&&(A=A.depth(this.depthLayer));const y=Qt("blurSamples","float",s).setGroup(qe),R=Qt("radius","float",s).setGroup(qe),P=Qt("mapSize","vec2",s).setGroup(qe);let N=this.vsmMaterialVertical||(this.vsmMaterialVertical=new dn);N.fragmentNode=RU({samples:y,radius:R,size:P,shadowPass:T,depthLayer:this.depthLayer}).context(e.getSharedContext()),N.name="VSMVertical",N=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new dn),N.fragmentNode=wU({samples:y,radius:R,size:P,shadowPass:A,depthLayer:this.depthLayer}).context(e.getSharedContext()),N.name="VSMHorizontal"}const u=Qt("intensity","float",s).setGroup(qe),h=Qt("normalBias","float",s).setGroup(qe),d=Wp(i),f=Ya.mul(h);let p;!t.highPrecision||e.material.receivedShadowPositionNode||e.context.shadowPositionWorld?p=d.mul(Ky.add(f)):p=We("mat4").onObjectUpdate(({object:A},y)=>y.value.multiplyMatrices(d.value,A.matrixWorld)).mul(bn).add(d.mul(Ze(f,0)));const g=this.setupShadowCoord(e,p),m=s.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(m===null)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const _=l===fs&&s.isPointLightShadow!==!0?this.vsmShadowMapHorizontal.texture:o,x=this.setupShadowFilter(e,{filterFn:m,shadowTexture:a.texture,depthTexture:_,shadowCoord:g,shadow:s,depthLayer:this.depthLayer});let v;t.shadowMap.transmitted===!0&&(a.texture.isCubeTexture?v=oi(a.texture,g.xyz):(v=Gt(a.texture,g),o.isArrayTexture&&(v=v.depth(this.depthLayer))));let S;v?S=Nt(1,x.rgb.mix(v,1),u.mul(v.a)).toVar():S=Nt(1,x,u).toVar(),this.shadowMap=a,this.shadow.map=a;const E=`${this.light.type} Shadow [ ${this.light.name||"ID: "+this.light.id} ]`;return v&&S.toInspector(`${E} / Color`,()=>this.shadowMap.texture.isCubeTexture?oi(this.shadowMap.texture):Gt(this.shadowMap.texture)),S.toInspector(`${E} / Depth`,()=>this.shadowMap.texture.isCubeTexture?oi(this.shadowMap.texture).r.oneMinus():Ai(this.shadowMap.depthTexture,Xa().mul(ra(Gt(this.shadowMap.depthTexture)))).r.oneMinus())}setup(e){if(e.renderer.shadowMap.enabled!==!1)return Q(()=>{const t=e.renderer.shadowMap.type;this._currentShadowType!==t&&(this._reset(),this._node=null);let n=this._node;return this.setupShadowPosition(e),n===null&&(this._node=n=this.setupShadow(e),this._currentShadowType=t),e.material.receivedShadowNode&&(n=e.material.receivedShadowNode(n)),n})()}renderShadow(e){const{shadow:t,shadowMap:n,light:i}=this,{renderer:s,scene:o}=e;t.updateMatrices(i),n.setSize(t.mapSize.width,t.mapSize.height,n.depth);const a=o.name;o.name=`Shadow Map [ ${i.name||"ID: "+i.id} ]`,s.render(o,t.camera),o.name=a}updateShadow(e){const{shadowMap:t,light:n,shadow:i}=this,{renderer:s,scene:o,camera:a}=e,l=s.shadowMap.type,c=t.depthTexture.version;this._depthVersionCached=c;const u=i.camera.layers.mask;i.camera.layers.mask&4294967294||(i.camera.layers.mask=a.layers.mask);const h=s.getRenderObjectFunction(),d=s.getMRT(),f=d?d.has("velocity"):!1;Ld=xU(s,o,Ld),o.overrideMaterial=MU(n),s.setRenderObjectFunction(AU(s,i,l,f)),s.setClearColor(0,0),s.setRenderTarget(t),this.renderShadow(e),s.setRenderObjectFunction(h),l===fs&&i.isPointLightShadow!==!0&&this.vsmPass(s),i.camera.layers.mask=u,yU(s,o,Ld)}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),au.material=this.vsmMaterialVertical,au.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),au.material=this.vsmMaterialHorizontal,au.render(e)}dispose(){this._reset(),super.dispose()}_reset(){this._currentShadowType=null,EU(this.light),this.shadowMap&&(this.shadowMap.dispose(),this.shadowMap=null),this.vsmShadowMapVertical!==null&&(this.vsmShadowMapVertical.dispose(),this.vsmShadowMapVertical=null,this.vsmMaterialVertical.dispose(),this.vsmMaterialVertical=null),this.vsmShadowMapHorizontal!==null&&(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 NU=(r,e)=>new Zy(r,e),PU=new Ve,T_=new dt,fl=new C,Ud=new C,DU=[new C(1,0,0),new C(-1,0,0),new C(0,-1,0),new C(0,1,0),new C(0,0,1),new C(0,0,-1)],LU=[new C(0,-1,0),new C(0,-1,0),new C(0,0,-1),new C(0,0,1),new C(0,-1,0),new C(0,-1,0)],UU=[new C(1,0,0),new C(-1,0,0),new C(0,1,0),new C(0,-1,0),new C(0,0,1),new C(0,0,-1)],FU=[new C(0,-1,0),new C(0,-1,0),new C(0,0,1),new C(0,0,-1),new C(0,-1,0),new C(0,-1,0)],IU=Q(({depthTexture:r,bd3D:e,dp:t})=>oi(r,e).compare(t)),BU=Q(({depthTexture:r,bd3D:e,dp:t,shadow:n})=>{const i=Qt("radius","float",n).setGroup(qe),s=Qt("mapSize","vec2",n).setGroup(qe),o=i.div(s.x),a=yi(e),l=gs(ho(e,a.x.greaterThan(a.z).select(K(0,1,0),K(1,0,0)))),c=ho(e,l),u=$y(ja.xy).mul(6.28318530718),h=ds(0,5,u),d=ds(1,5,u),f=ds(2,5,u),p=ds(3,5,u),g=ds(4,5,u);return oi(r,e.add(l.mul(h.x).add(c.mul(h.y)).mul(o))).compare(t).add(oi(r,e.add(l.mul(d.x).add(c.mul(d.y)).mul(o))).compare(t)).add(oi(r,e.add(l.mul(f.x).add(c.mul(f.y)).mul(o))).compare(t)).add(oi(r,e.add(l.mul(p.x).add(c.mul(p.y)).mul(o))).compare(t)).add(oi(r,e.add(l.mul(g.x).add(c.mul(g.y)).mul(o))).compare(t)).mul(1/5)}),OU=Q(({filterFn:r,depthTexture:e,shadowCoord:t,shadow:n},i)=>{const s=t.xyz.toConst(),o=s.abs().toConst(),a=o.x.max(o.y).max(o.z),l=We("float").setGroup(qe).onRenderUpdate(()=>n.camera.near),c=We("float").setGroup(qe).onRenderUpdate(()=>n.camera.far),u=Qt("bias","float",n).setGroup(qe),h=j(1).toVar();return Lt(a.sub(c).lessThanEqual(0).and(a.sub(l).greaterThanEqual(0)),()=>{let d;i.renderer.reversedDepthBuffer?(d=RP(a.negate(),l,c),d.subAssign(u)):(d=xy(a.negate(),l,c),d.addAssign(u));const f=s.normalize();h.assign(r({depthTexture:e,bd3D:f,dp:d,shadow:n}))}),h});class kU extends Zy{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return e===$v?IU:BU}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,depthTexture:n,shadowCoord:i,shadow:s}){return OU({filterFn:t,depthTexture:n,shadowCoord:i,shadow:s})}setupRenderTarget(e,t){const n=new wx(e.mapSize.width);n.name="PointShadowDepthTexture",n.compareFunction=t.renderer.reversedDepthBuffer?$s:Dr;const i=t.createCubeRenderTarget(e.mapSize.width);return i.texture.name="PointShadowMap",i.depthTexture=n,{shadowMap:i,depthTexture:n}}renderShadow(e){const{shadow:t,shadowMap:n,light:i}=this,{renderer:s,scene:o}=e,a=t.camera,l=t.matrix,c=s.coordinateSystem===xs,u=c?DU:UU,h=c?LU:FU;n.setSize(t.mapSize.width,t.mapSize.width);const d=s.autoClear,f=s.getClearColor(PU),p=s.getClearAlpha();s.autoClear=!1,s.setClearColor(t.clearColor,t.clearAlpha);for(let g=0;g<6;g++){s.setRenderTarget(n,g),s.clear();const m=i.distance||a.far;m!==a.far&&(a.far=m,a.updateProjectionMatrix()),fl.setFromMatrixPosition(i.matrixWorld),a.position.copy(fl),Ud.copy(a.position),Ud.add(u[g]),a.up.copy(h[g]),a.lookAt(Ud),a.updateMatrixWorld(),l.makeTranslation(-fl.x,-fl.y,-fl.z),T_.multiplyMatrices(a.projectionMatrix,a.matrixWorldInverse),t._frustum.setFromProjectionMatrix(T_,a.coordinateSystem,a.reversedDepth);const _=o.name;o.name=`Point Light Shadow [ ${i.name||"ID: "+i.id} ] - Face ${g+1}`,s.render(o,a),o.name=_}s.autoClear=d,s.setClearColor(f,p)}}const GU=(r,e)=>new kU(r,e);class To extends Ka{static get type(){return"AnalyticLightNode"}constructor(e=null){super(),this.light=e,this.color=new Ve,this.colorNode=e&&e.colorNode||We(this.color).setGroup(qe),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=je.FRAME,e&&e.shadow&&(this._shadowDisposeListener=()=>{this.disposeShadow()},e.addEventListener("dispose",this._shadowDisposeListener))}dispose(){this._shadowDisposeListener&&this.light.removeEventListener("dispose",this._shadowDisposeListener),super.dispose()}disposeShadow(){this.shadowNode!==null&&(this.shadowNode.dispose(),this.shadowNode=null),this.shadowColorNode=null,this.baseColorNode!==null&&(this.colorNode=this.baseColorNode,this.baseColorNode=null)}getHash(){return this.light.uuid}getLightVector(e){return qy(this.light).sub(e.context.positionView||hn)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return NU(this.light)}setupShadow(e){const{renderer:t}=e;if(t.shadowMap.enabled===!1)return;let n=this.shadowColorNode;if(n===null){const i=this.light.shadow.shadowNode;let s;i!==void 0?s=Be(i):s=this.setupShadowNode(),this.shadowNode=s,this.shadowColorNode=n=this.colorNode.mul(s),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):this.shadowNode!==null&&(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 Qy=Q(({lightDistance:r,cutoffDistance:e,decayExponent:t})=>{const n=r.pow(t).max(.01).reciprocal();return e.greaterThan(0).select(n.mul(r.div(e).pow4().oneMinus().clamp().pow2()),n)}),VU=({color:r,lightVector:e,cutoffDistance:t,decayExponent:n})=>{const i=e.normalize(),s=e.length(),o=Qy({lightDistance:s,cutoffDistance:t,decayExponent:n}),a=r.mul(o);return{lightDirection:i,lightColor:a}};class zU extends To{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=We(0).setGroup(qe),this.decayExponentNode=We(2).setGroup(qe)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return GU(this.light)}setupDirect(e){return VU({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}}Q(([r=Xa()],{renderer:e,material:t})=>{const n=k0(r.mul(2).sub(1));let i;if(t.alphaToCoverage&&e.currentSamples>0){const s=j(n.fwidth()).toVar();i=Xs(s.oneMinus(),s.add(1),n).oneMinus()}else i=Si(n.greaterThan(1),0,1);return i});const HU=Q(([r,e])=>{const t=r.x,n=r.y,i=r.z;let s=e.element(0).mul(.886227);return s=s.add(e.element(1).mul(2*.511664).mul(n)),s=s.add(e.element(2).mul(2*.511664).mul(i)),s=s.add(e.element(3).mul(2*.511664).mul(t)),s=s.add(e.element(4).mul(2*.429043).mul(t).mul(n)),s=s.add(e.element(5).mul(2*.429043).mul(n).mul(i)),s=s.add(e.element(6).mul(i.mul(i).mul(.743125).sub(.247708))),s=s.add(e.element(7).mul(2*.429043).mul(t).mul(i)),s=s.add(e.element(8).mul(.429043).mul(nt(t,t).sub(nt(n,n)))),s}),Gi=new zp;class WU extends Ur{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,n){const i=this.renderer,s=this.nodes.getBackgroundNode(e)||e.background;let o=!1;if(s===null)i._clearColor.getRGB(Gi),Gi.a=i._clearColor.a;else if(s.isColor===!0)s.getRGB(Gi),Gi.a=1,o=!0;else if(s.isNode===!0){const l=this.get(e),c=s;Gi.copy(i._clearColor);let u=l.backgroundMesh;if(u===void 0){let v=function(){s.removeEventListener("dispose",v),u.material.dispose(),u.geometry.dispose()};const d=Ze(c).mul(y_).context({getUV:()=>$L.mul(t1),getTextureLevel:()=>WL}),f=Pl.element(3).element(3).equal(1),p=vs(1,Pl.element(1).element(1)).mul(3),g=f.select(bn.mul(p),bn),m=mc.mul(Ze(g,0));let _=Pl.mul(Ze(m.xyz,1));_=_.setZ(_.w);const x=new dn;x.name="Background.material",x.side=Pt,x.depthTest=!1,x.depthWrite=!1,x.allowOverride=!1,x.fog=!1,x.lights=!1,x.vertexNode=_,x.colorNode=d,l.backgroundMeshNode=d,l.backgroundMesh=u=new gn(new hc(1,32,32),x),u.frustumCulled=!1,u.name="Background.mesh",s.addEventListener("dispose",v)}const h=c.getCacheKey();l.backgroundCacheKey!==h&&(l.backgroundMeshNode.node=Ze(c).mul(y_),l.backgroundMeshNode.needsUpdate=!0,u.material.needsUpdate=!0,l.backgroundCacheKey=h),t.unshift(u,u.geometry,u.material,0,0,null,null)}else ne("Renderer: Unsupported background configuration.",s);const a=i.xr.getEnvironmentBlendMode();if(a==="additive"?Gi.set(0,0,0,1):a==="alpha-blend"&&Gi.set(0,0,0,0),i.autoClear===!0||o===!0){const l=n.clearColorValue;l.r=Gi.r,l.g=Gi.g,l.b=Gi.b,l.a=Gi.a,(i.backend.isWebGLBackend===!0||i.alpha===!0)&&(l.r*=l.a,l.g*=l.a,l.b*=l.a),n.depthClearValue=i.getClearDepth(),n.stencilClearValue=i.getClearStencil(),n.clearColor=i.autoClearColor===!0,n.clearDepth=i.autoClearDepth===!0,n.clearStencil=i.autoClearStencil===!0}else n.clearColor=!1,n.clearDepth=!1,n.clearStencil=!1}}let $U=0;class Rf{constructor(e="",t=[]){this.name=e,this.bindings=t,this.id=$U++}}class XU{constructor(e,t,n,i,s,o,a,l,c,u=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=n,this.transforms=u,this.nodeAttributes=i,this.bindings=s,this.updateNodes=o,this.updateBeforeNodes=a,this.updateAfterNodes=l,this.observer=c,this.usedTimes=0}createBindings(){const e=[];for(const t of this.bindings)if(t.bindings[0].groupNode.shared!==!0){const i=new Rf(t.name,[]);e.push(i);for(const s of t.bindings)i.bindings.push(s.clone())}else e.push(t);return e}}class M_{constructor(e,t,n=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=n}}class qU{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 Jy{constructor(e,t,n=!1,i=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=n,this.count=i}}class jU extends Jy{constructor(e,t,n=null,i=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=n,this.interpolationSampling=i}}class YU{constructor(e,t,n=""){this.name=e,this.type=t,this.code=n,Object.defineProperty(this,"isNodeCode",{value:!0})}}let KU=0;class Fd{constructor(e=null){this.id=KU++,this.nodesData=new WeakMap,this.parent=e}getData(e){let t=this.nodesData.get(e);return t===void 0&&this.parent!==null&&(t=this.parent.getData(e)),t}setData(e,t){this.nodesData.set(e,t)}}class ZU{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class Fr{constructor(e,t){this.name=e,this.value=t,this.boundary=0,this.itemSize=0,this.offset=0,this.index=-1}setValue(e){this.value=e}getValue(){return this.value}}class QU extends Fr{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class JU extends Fr{constructor(e,t=new de){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class eF extends Fr{constructor(e,t=new C){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class tF extends Fr{constructor(e,t=new tt){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class nF extends Fr{constructor(e,t=new Ve){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class iF extends Fr{constructor(e,t=new Fu){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}}class sF extends Fr{constructor(e,t=new Ke){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class rF extends Fr{constructor(e,t=new dt){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class oF extends QU{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class aF extends JU{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class lF extends eF{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class cF extends tF{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class uF extends nF{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class hF extends iF{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class dF extends sF{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class fF extends rF{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}let pF=0;const E_=new WeakMap,mF=new WeakMap,gF=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),lu=r=>/e/g.test(r)?String(r).replace(/\+/g,""):(r=Number(r),r+(r%1?"":".0"));class ev{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=Cd(),this.stacks=[],this.tab=" ",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new Fd,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:pF++})}isFlatShading(){return this.material.flatShading===!0||this.geometry.hasAttribute("normal")===!1}isOpaque(){const e=this.material;return e.transparent===!1&&e.blending===Jn&&e.alphaToCoverage===!1}createRenderTarget(e,t,n){return new Lr(e,t,n)}createCubeRenderTarget(e,t){return new My(e,t)}includes(e){return this.nodes.includes(e)}getOutputStructName(){}_getBindGroup(e,t){const n=t[0].groupNode;let i=n.shared;if(i)for(let o=1;oh.nodeUniform.node.id-d.nodeUniform.node.id);for(const h of u.uniforms)o+=h.nodeUniform.node.id}else o+=u.nodeUniform.id;const a=this.renderer._currentRenderContext||this.renderer;let l=E_.get(a);l===void 0&&(l=new Map,E_.set(a,l));const c=Ha(o);s=l.get(c),s===void 0&&(s=new Rf(e,t),l.set(c,s))}else s=new Rf(e,t);return s}getBindGroupArray(e,t){const n=this.bindings[t];let i=n[e];return i===void 0&&(this.bindingsIndexes[e]===void 0&&(this.bindingsIndexes[e]={binding:0,group:Object.keys(this.bindingsIndexes).length}),n[e]=i=[]),i}getBindings(){let e=this.bindGroups;if(e===null){const t={},n=this.bindings;for(const i of ld)for(const s in n[i]){const o=n[i][s],a=t[s]||(t[s]=[]);for(const l of o)a.includes(l)===!1&&a.push(l)}e=[];for(const i in t){const s=t[i],o=this._getBindGroup(i,s);e.push(o)}this.bindGroups=e}return e}sortBindingGroups(){const e=this.getBindings();e.sort((t,n)=>t.bindings[0].groupNode.order-n.bindings[0].groupNode.order);for(let t=0;t=0?`${Math.round(t)}u`:"0u";if(e==="bool")return t?"true":"false";if(e==="color")return`${this.getType("vec3")}( ${lu(t.r)}, ${lu(t.g)}, ${lu(t.b)} )`;const n=this.getTypeLength(e),i=this.getComponentType(e),s=o=>this.generateConst(i,o);if(n===2)return`${this.getType(e)}( ${s(t.x)}, ${s(t.y)} )`;if(n===3)return`${this.getType(e)}( ${s(t.x)}, ${s(t.y)}, ${s(t.z)} )`;if(n===4&&e!=="mat2")return`${this.getType(e)}( ${s(t.x)}, ${s(t.y)}, ${s(t.z)}, ${s(t.w)} )`;if(n>=4&&t&&(t.isMatrix2||t.isMatrix3||t.isMatrix4))return`${this.getType(e)}( ${t.elements.map(s).join(", ")} )`;if(n>4)return`${this.getType(e)}()`;throw new Error(`NodeBuilder: Type '${e}' not found in generate constant attempt.`)}getType(e){return e==="color"?"vec3":e}hasGeometryAttribute(e){return this.geometry&&this.geometry.getAttribute(e)!==void 0}getAttribute(e,t){const n=this.attributes;for(const s of n)if(s.name===e)return s;const i=new M_(e,t);return this.registerDeclaration(i),n.push(i),i}getPropertyName(e){return e.name}isVector(e){return/vec\d/.test(e)}isMatrix(e){return/mat\d/.test(e)}isReference(e){return e==="void"||e==="property"||e==="sampler"||e==="samplerComparison"||e==="texture"||e==="cubeTexture"||e==="storageTexture"||e==="depthTexture"||e==="texture3D"}needsToWorkingColorSpace(){return!1}getComponentTypeFromTexture(e){const t=e.type;if(e.isDataTexture){if(t===Sn)return"int";if(t===wt)return"uint"}return"float"}getElementType(e){return e==="mat2"?"vec2":e==="mat3"?"vec3":e==="mat4"?"vec4":this.getComponentType(e)}getComponentType(e){if(e=this.getVectorType(e),e==="float"||e==="bool"||e==="int"||e==="uint")return e;const t=/(b|i|u|)(vec|mat)([2-4])/.exec(e);return t===null?null:t[1]==="b"?"bool":t[1]==="i"?"int":t[1]==="u"?"uint":"float"}getVectorType(e){return e==="color"?"vec3":e==="texture"||e==="cubeTexture"||e==="storageTexture"||e==="texture3D"?"vec4":e}getTypeFromLength(e,t="float"){if(e===1)return t;let n=d0(e);const i=t==="float"?"":t[0];return/mat2/.test(t)===!0&&(n=n.replace("vec","mat")),i+n}getTypeFromArray(e){return gF.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,i=e.itemSize,s=e.normalized;let o;return!(e instanceof Ex)&&s!==!0&&(o=this.getTypeFromArray(n)),this.getTypeFromLength(i,o)}getTypeLength(e){const t=this.getVectorType(e),n=/vec([2-4])/.exec(t);return n!==null?Number(n[1]):t==="float"||t==="bool"||t==="int"||t==="uint"?1:/mat2/.test(e)===!0?4:/mat3/.test(e)===!0?9:/mat4/.test(e)===!0?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 t==="int"||t==="uint"?e:this.changeComponentType(e,"int")}setActiveStack(e){this.activeStacks.push(e)}removeActiveStack(e){if(this.activeStacks[this.activeStacks.length-1]===e)this.activeStacks.pop();else throw new Error("NodeBuilder: Invalid active stack removal.")}getActiveStack(){return this.activeStacks[this.activeStacks.length-1]}getBaseStack(){return this.activeStacks[0]}addStack(){this.stack=Cd(this.stack);const e=_0();return this.stacks.push(e),Ou(this.stack),this.stack}removeStack(){const e=this.stack;for(const t of e.nodes){const n=this.getDataFromNode(t);n.stack=e}return this.stack=e.parent,Ou(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,n=null){n=n===null?e.isGlobal(this)?this.globalCache:this.cache:n;let i=n.getData(e);i===void 0&&(i={},n.setData(e,i)),i[t]===void 0&&(i[t]={});let s=i[t];const o=i.any?i.any.subBuilds:null,a=this.getClosestSubBuild(o);return a&&(s.subBuildsCache===void 0&&(s.subBuildsCache={}),s=s.subBuildsCache[a]||(s.subBuildsCache[a]={}),s.subBuilds=o),s}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 i=n.bufferAttribute;if(i===void 0){const s=this.uniforms.index++;i=new M_("nodeAttribute"+s,t,e),this.bufferAttributes.push(i),n.bufferAttribute=i}return i}getStructTypeNode(e,t=this.shaderStage){return this.types[t][e]||null}getStructTypeFromNode(e,t,n=null,i=this.shaderStage){const s=this.getDataFromNode(e,i,this.globalCache);let o=s.structType;if(o===void 0){const a=this.structs.index++;n===null&&(n="StructType"+a),o=new ZU(n,t),this.structs[i].push(o),this.types[i][n]=e,s.structType=o}return o}getOutputStructTypeFromNode(e,t){const n=this.getStructTypeFromNode(e,t,"OutputType","fragment");return n.output=!0,n}getUniformFromNode(e,t,n=this.shaderStage,i=null){const s=this.getDataFromNode(e,n,this.globalCache);let o=s.uniform;if(o===void 0){const a=this.uniforms.index++;o=new qU(i||"nodeUniform"+a,t,e),this.uniforms[n].push(o),this.registerDeclaration(o),s.uniform=o}return o}getVarFromNode(e,t=null,n=e.getNodeType(this),i=this.shaderStage,s=!1){const o=this.getDataFromNode(e,i),a=this.getSubBuildProperty("variable",o.subBuilds);let l=o[a];if(l===void 0){const c=s?"_const":"_var",u=this.vars[i]||(this.vars[i]=[]),h=this.vars[c]||(this.vars[c]=0);t===null&&(t=(s?"nodeConst":"nodeVar")+h,this.vars[c]++),a!=="variable"&&(t=this.getSubBuildProperty(t,o.subBuilds));const d=e.getArrayCount(this);l=new Jy(t,n,s,d),s||u.push(l),this.registerDeclaration(l),o[a]=l}return l}isDeterministic(e){if(e.isMathNode)return this.isDeterministic(e.aNode)&&(e.bNode?this.isDeterministic(e.bNode):!0)&&(e.cNode?this.isDeterministic(e.cNode):!0);if(e.isOperatorNode)return this.isDeterministic(e.aNode)&&(e.bNode?this.isDeterministic(e.bNode):!0);if(e.isArrayNode){if(e.values!==null){for(const t of e.values)if(!this.isDeterministic(t))return!1}return!0}else if(e.isConstNode)return!0;return!1}getVaryingFromNode(e,t=null,n=e.getNodeType(this),i=null,s=null){const o=this.getDataFromNode(e,"any"),a=this.getSubBuildProperty("varying",o.subBuilds);let l=o[a];if(l===void 0){const c=this.varyings,u=c.length;t===null&&(t="nodeVarying"+u),a!=="varying"&&(t=this.getSubBuildProperty(t,o.subBuilds)),l=new jU(t,n,i,s),c.push(l),this.registerDeclaration(l),o[a]=l}return l}registerDeclaration(e){const t=this.shaderStage,n=this.declarations[t]||(this.declarations[t]={}),i=this.getPropertyName(e);let s=1,o=i;for(;n[o]!==void 0;)o=i+"_"+s++;s>1&&(e.name=o,ee(`TSL: Declaration name '${i}' of '${e.type}' already in use. Renamed to '${o}'.`)),n[o]=e}getCodeFromNode(e,t,n=this.shaderStage){const i=this.getDataFromNode(e);let s=i.code;if(s===void 0){const o=this.codes[n]||(this.codes[n]=[]),a=o.length;s=new YU("nodeCode"+a,t),o.push(s),i.code=s}return s}addFlowCodeHierarchy(e,t){const{flowCodes:n,flowCodeBlock:i}=this.getDataFromNode(e);let s=!0,o=t;for(;o;){if(i.get(o)===!0){s=!1;break}o=this.getDataFromNode(o).parentNodeBlock}if(s)for(const a of n)this.addLineFlowCode(a)}addLineFlowCodeBlock(e,t,n){const i=this.getDataFromNode(e),s=i.flowCodes||(i.flowCodes=[]),o=i.flowCodeBlock||(i.flowCodeBlock=new WeakMap);s.push(t),o.set(n,!0)}addLineFlowCode(e,t=null){return e===""?this:(t!==null&&this.context.nodeBlock&&this.addLineFlowCodeBlock(t,e,this.context.nodeBlock),e=this.tab+e,/;\s*$/.test(e)||(e=e+`; `),this.flow.code+=e,this)}addFlowCode(e){return this.flow.code+=e,this}addFlowTab(){return this.tab+=" ",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){this.currentFunctionNode!==null&&this.currentFunctionNode.includes.push(e)}buildFunctionNode(e){const t=new iU,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 o=0;const a=Object.values(this);return{next:()=>({value:a[o],done:o++>=a.length})}}};for(const o of t.inputs)n[o.name]=new BL(o.type,o.name);e.layout=null;const i=e.call(n),s=this.flowStagesNode(i,t.type);return e.layout=t,s}flowBuildStage(e,t,n=null){const i=this.getBuildStage();this.setBuildStage(t);const s=e.build(this,n);return this.setBuildStage(i),s}flowStagesNode(e,t=null){const n=this.flow,i=this.vars,s=this.declarations,o=this.cache,a=this.buildStage,l=this.stack,c={code:""};this.flow=c,this.vars={},this.declarations={},this.cache=new Fd,this.stack=Cd();for(const u of ad)this.setBuildStage(u),c.result=e.build(this,t);return c.vars=this.getVars(this.shaderStage),this.flow=n,this.vars=i,this.declarations=s,this.cache=o,this.stack=l,this.setBuildStage(a),c}getFunctionOperator(){return null}buildFunctionCode(){ee("Abstract function.")}flowChildNode(e,t=null){const n=this.flow,i={code:""};return this.flow=i,i.result=e.build(this,t),this.flow=n,i}flowNodeFromShaderStage(e,t,n=null,i=null){const s=this.tab,o=this.cache,a=this.shaderStage,l=this.context;this.setShaderStage(e);const c={...this.context};delete c.nodeBlock,this.cache=this.globalCache,this.tab=" ",this.context=c;let u=null;if(this.buildStage==="generate"){const h=this.flowChildNode(t,n);i!==null&&(h.code+=`${this.tab+i} = ${h.result}; `),this.flowCode[e]=this.flowCode[e]+h.code,u=h}else u=t.build(this);return this.setShaderStage(a),this.cache=o,this.tab=s,this.context=l,u}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){ee("Abstract function.")}getVaryings(){ee("Abstract function.")}getVar(e,t,n=null){return`${n!==null?this.generateArrayDeclaration(e,n):this.getType(e)} ${t}`}getVars(e,t=!1){const n=[],i=this.vars[e];if(i!==void 0)for(const s of i)n.push(`${this.getVar(s.type,s.name,s.count)};`);return n.join(t?` `:` `)}getUniforms(){ee("Abstract function.")}getCodes(e){const t=this.codes[e];let n="";if(t!==void 0)for(const i of t)n+=i.code+` `;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(){ee("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(e&&e.isNode?e.isShaderCallNodeInternal?t=e.shaderNode.subBuilds:e.isStackNode?t=[e.subBuild]:t=this.getDataFromNode(e,"any").subBuilds:e instanceof Set?t=[...e]:t=e,!t)return null;const n=this.subBuildLayers;for(let i=t.length-1;i>=0;i--){const s=t[i];if(n.includes(s))return s}return null}getSubBuildOutput(e){return this.getSubBuildProperty("outputNode",e)}getSubBuildProperty(e="",t=null){let n;t!==null?n=this.getClosestSubBuild(t):n=this.subBuildFn;let i;return n?i=e?n+"_"+e:n:i=e,i}prebuild(){const{object:e,renderer:t,material:n}=this;if(t.contextNode.isContextNode===!0?this.context={...this.context,...t.contextNode.getFlowContextData()}:ne('NodeBuilder: "renderer.contextNode" must be an instance of `context()`.'),n&&n.contextNode&&(n.contextNode.isContextNode===!0?this.context={...this.context,...n.contextNode.getFlowContextData()}:ne('NodeBuilder: "material.contextNode" must be an instance of `context()`.')),n!==null){let i=t.library.fromMaterial(n);i===null&&(ne(`NodeBuilder: Material "${n.type}" is not compatible.`),i=new dn),i.build(this)}else this.addFlow("compute",e)}build(){this.prebuild();for(const e of ad){this.setBuildStage(e),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage("vertex",this.context.position);for(const t of ld){this.setShaderStage(t);const n=this.flowNodes[t];for(const i of n)e==="generate"?this.flowNode(i):i.build(this)}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}async buildAsync(){this.prebuild();for(const e of ad){this.setBuildStage(e),this.context.position&&this.context.position.isNode&&this.flowNodeFromShaderStage("vertex",this.context.position);for(const t of ld){this.setShaderStage(t);const n=this.flowNodes[t];for(const i of n)e==="generate"?this.flowNode(i):i.build(this);await Tx()}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}getSharedDataFromNode(e){let t=mF.get(e);return t===void 0&&(t={}),t}getNodeUniform(e,t){const n=this.getSharedDataFromNode(e);let i=n.cache;if(i===void 0){if(t==="float"||t==="int"||t==="uint")i=new oF(e);else if(t==="vec2"||t==="ivec2"||t==="uvec2")i=new aF(e);else if(t==="vec3"||t==="ivec3"||t==="uvec3")i=new lF(e);else if(t==="vec4"||t==="ivec4"||t==="uvec4")i=new cF(e);else if(t==="color")i=new uF(e);else if(t==="mat2")i=new hF(e);else if(t==="mat3")i=new dF(e);else if(t==="mat4")i=new fF(e);else throw new Error(`Uniform "${t}" not implemented.`);n.cache=i}return i}format(e,t,n){if(t=this.getVectorType(t),n=this.getVectorType(n),t===n||n===null||this.isReference(n))return e;const i=this.getTypeLength(t),s=this.getTypeLength(n);return i===16&&s===9?`${this.getType(n)}( ${e}[ 0 ].xyz, ${e}[ 1 ].xyz, ${e}[ 2 ].xyz )`:i===9&&s===4?`${this.getType(n)}( ${e}[ 0 ].xy, ${e}[ 1 ].xy )`:i>4||s>4||s===0?e:i===s?`${this.getType(n)}( ${e} )`:i>s?(e=n==="bool"?`all( ${e} )`:`${e}.${"xyz".slice(0,s)}`,this.format(e,this.getTypeFromLength(s,this.getComponentType(t)),n)):s===4&&i>1?`${this.getType(n)}( ${this.format(e,t,"vec3")}, 1.0 )`:i===2?`${this.getType(n)}( ${this.format(e,t,"vec2")}, 0.0 )`:(i===1&&s>1&&t!==this.getComponentType(n)&&(e=`${this.getType(this.getComponentType(n))}( ${e} )`),`${this.getType(n)}( ${e} )`)}getSignature(){return`// Three.js r${po} - Node System `}needsPreviousData(){const e=this.renderer.getMRT();return e&&e.has("velocity")||f0(this.object).useVelocity===!0}}class A_{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 n===void 0&&(n={renderId:0,frameId:0},e.set(t,n)),n}updateBeforeNode(e){const t=e.getUpdateBeforeType(),n=e.updateReference(this);if(t===je.FRAME){const i=this._getMaps(this.updateBeforeMap,n);if(i.frameId!==this.frameId){const s=i.frameId;i.frameId=this.frameId,e.updateBefore(this)===!1&&(i.frameId=s)}}else if(t===je.RENDER){const i=this._getMaps(this.updateBeforeMap,n);if(i.renderId!==this.renderId){const s=i.renderId;i.renderId=this.renderId,e.updateBefore(this)===!1&&(i.renderId=s)}}else t===je.OBJECT&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),n=e.updateReference(this);if(t===je.FRAME){const i=this._getMaps(this.updateAfterMap,n);i.frameId!==this.frameId&&e.updateAfter(this)!==!1&&(i.frameId=this.frameId)}else if(t===je.RENDER){const i=this._getMaps(this.updateAfterMap,n);i.renderId!==this.renderId&&e.updateAfter(this)!==!1&&(i.renderId=this.renderId)}else t===je.OBJECT&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),n=e.updateReference(this);if(t===je.FRAME){const i=this._getMaps(this.updateMap,n);i.frameId!==this.frameId&&e.update(this)!==!1&&(i.frameId=this.frameId)}else if(t===je.RENDER){const i=this._getMaps(this.updateMap,n);i.renderId!==this.renderId&&e.update(this)!==!1&&(i.renderId=this.renderId)}else t===je.OBJECT&&e.update(this)}update(){this.frameId++,this.lastTime===void 0&&(this.lastTime=performance.now()),this.deltaTime=(performance.now()-this.lastTime)/1e3,this.lastTime=performance.now(),this.time+=this.deltaTime}}class $p{constructor(e,t,n=null,i="",s=!1){this.type=e,this.name=t,this.count=n,this.qualifier=i,this.isConst=s}}$p.isNodeFunctionInput=!0;class _F extends To{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class xF extends To{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:jy(this.light),lightColor:e}}}class yF extends To{static get type(){return"HemisphereLightNode"}constructor(e=null){super(e),this.lightPositionNode=Xy(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=We(new Ve).setGroup(qe)}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:i}=this,o=Ya.dot(i).mul(.5).add(.5),a=Nt(n,t,o);e.context.irradiance.addAssign(a)}}class Xp extends To{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=We(0).setGroup(qe),this.penumbraCosNode=We(0).setGroup(qe),this.cutoffDistanceNode=We(0).setGroup(qe),this.decayExponentNode=We(0).setGroup(qe),this.colorNode=We(this.color).setGroup(qe)}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:i}=this;return Xs(n,i,t)}getLightCoord(e){const t=e.getNodeProperties(this);let n=t.projectionUV;return n===void 0&&(n=aU(this.light,e.context.positionWorld),t.projectionUV=n),n}setupDirect(e){const{colorNode:t,cutoffDistanceNode:n,decayExponentNode:i,light:s}=this,o=this.getLightVector(e),a=o.normalize(),l=a.dot(jy(s)),c=this.getSpotAttenuation(e,l),u=o.length(),h=Qy({lightDistance:u,cutoffDistance:n,decayExponent:i});let d=t.mul(c).mul(h),f,p;return s.colorNode?(p=this.getLightCoord(e),f=s.colorNode(p)):s.map&&(p=this.getLightCoord(e),f=Gt(s.map,p.xy).onRenderUpdate(()=>s.map)),f&&(d=p.mul(2).sub(1).abs().lessThan(1).all().select(d.mul(f),d)),{lightColor:d,lightDirection:a}}}class vF extends Xp{static get type(){return"IESSpotLightNode"}getSpotAttenuation(e,t){const n=this.light.iesMap;let i=null;if(n&&n.isTexture===!0){const s=t.acos().mul(1/Math.PI);i=Gt(n,Ie(s,0),0).r}else i=super.getSpotAttenuation(t);return i}}class SF extends To{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let n=0;n<9;n++)t.push(new C);this.lightProbe=Ri(t)}update(e){const{light:t}=this;super.update(e);for(let n=0;n<9;n++)this.lightProbe.array[n].copy(t.sh.coefficients[n]).multiplyScalar(t.intensity)}setup(e){const t=HU(Ya,this.lightProbe);e.context.irradiance.addAssign(t)}}const bF=Q(([r,e])=>{const t=r.abs().sub(e);return Ws(On(t,0)).add(Ua(On(t.x,t.y),0))});class TF extends Xp{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),t.aspect===null){let n=1;t.map!==null&&(n=t.map.width/t.map.height),t.shadow.aspect=n}else t.shadow.aspect=t.aspect}getSpotAttenuation(e){const t=j(0),n=this.penumbraCosNode,i=Wp(this.light).mul(e.context.positionWorld||Fa);return Lt(i.w.greaterThan(0),()=>{const s=i.xyz.div(i.w),o=bF(s.xy.sub(Ie(.5)),Ie(.5)),a=vs(-1,si(1,P0(n)).sub(1));t.assign(Up(o.mul(-2).mul(a)))}),t}}const Id=new dt,cu=new dt;let pl=null;class MF extends To{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=We(new C).setGroup(qe),this.halfWidth=We(new C).setGroup(qe),this.updateType=je.RENDER}update(e){super.update(e);const{light:t}=this,n=e.camera.matrixWorldInverse;cu.identity(),Id.copy(t.matrixWorld),Id.premultiply(n),cu.extractRotation(Id),this.halfWidth.value.set(t.width*.5,0,0),this.halfHeight.value.set(0,t.height*.5,0),this.halfWidth.value.applyMatrix4(cu),this.halfHeight.value.applyMatrix4(cu)}setupDirectRectArea(e){let t,n;e.isAvailable("float32Filterable")?(t=Gt(pl.LTC_FLOAT_1),n=Gt(pl.LTC_FLOAT_2)):(t=Gt(pl.LTC_HALF_1),n=Gt(pl.LTC_HALF_2));const{colorNode:i,light:s}=this,o=qy(s);return{lightColor:i,lightPosition:o,halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:n}}static setLTC(e){pl=e}}class tv{parseFunction(){ee("Abstract function.")}}class qp{constructor(e,t,n="",i=""){this.type=e,this.inputs=t,this.name=n,this.precision=i}getCode(){ee("Abstract function.")}}qp.isNodeFunction=!0;const EF=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,AF=/[a-z_0-9]+/ig,R_="#pragma main",RF=r=>{r=r.trim();const e=r.indexOf(R_),t=e!==-1?r.slice(e+R_.length):r,n=t.match(EF);if(n!==null&&n.length===5){const i=n[4],s=[];let o=null;for(;(o=AF.exec(i))!==null;)s.push(o);const a=[];let l=0;for(;l{let l=this._createNodeBuilder(e,e.material);try{t?await l.buildAsync():l.build()}catch(c){l=this._createNodeBuilder(e,new dn),t?await l.buildAsync():l.build(),ne("TSL: "+c)}return l};if(t)return a().then(l=>(i=this._createNodeBuilderState(l),s.set(o,i),i.usedTimes++,n.nodeBuilderState=i,i));{let l=this._createNodeBuilder(e,e.material);try{l.build()}catch(c){l=this._createNodeBuilder(e,new dn),l.build();let u=c.stackTrace;!u&&c.stack&&(u=new jn(c.stack)),ne("TSL: "+c,u)}i=this._createNodeBuilderState(l),s.set(o,i)}}i.usedTimes++,n.nodeBuilderState=i}return i}getForRenderAsync(e){const t=this.getForRender(e,!0);return t.then?t:Promise.resolve(t)}getForRenderDeferred(e){const t=this.get(e);if(t.nodeBuilderState!==void 0)return t.nodeBuilderState;const n=this.getForRenderCacheKey(e),i=this.nodeBuilderCache.get(n);return i!==void 0?(i.usedTimes++,t.nodeBuilderState=i,i):(t.pendingBuild!==!0&&(t.pendingBuild=!0,this._buildQueue.push(()=>this.getForRenderAsync(e).then(()=>{t.pendingBuild=!1})),this._processBuildQueue()),null)}_processBuildQueue(){if(this._buildInProgress||this._buildQueue.length===0)return;this._buildInProgress=!0,this._buildQueue.shift()().then(()=>{this._buildInProgress=!1,this._processBuildQueue()})}delete(e){if(e.isRenderObject){const t=this.get(e).nodeBuilderState;t!==void 0&&(t.usedTimes--,t.usedTimes===0&&this.nodeBuilderCache.delete(this.getForRenderCacheKey(e)))}return super.delete(e)}getForCompute(e){const t=this.get(e);let n=t.nodeBuilderState;if(n===void 0){const i=this.backend.createNodeBuilder(e,this.renderer);i.build(),n=this._createNodeBuilderState(i),t.nodeBuilderState=n}return n}_createNodeBuilderState(e){return new XU(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){Mi[0]=e,Mi[1]=t;const n=this.renderer.info.calls,i=this.callHashCache.get(Mi)||{};if(i.callId!==n){const s=this.getEnvironmentNode(e),o=this.getFogNode(e);t&&rr.push(t.getCacheKey(!0)),s&&rr.push(s.getCacheKey()),o&&rr.push(o.getCacheKey()),rr.push(this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview?1:0),rr.push(this.renderer.shadowMap.enabled?1:0),rr.push(this.renderer.shadowMap.type),i.callId=n,i.cacheKey=dc(rr),this.callHashCache.set(Mi,i),rr.length=0}return Mi[0]=null,Mi[1]=null,i.cacheKey}get isToneMappingState(){return!this.renderer.getRenderTarget()}updateBackground(e){const t=this.get(e),n=e.background;if(n){const i=e.backgroundBlurriness===0&&t.backgroundBlurriness>0||e.backgroundBlurriness>0&&t.backgroundBlurriness===0;if(t.background!==n||i){const s=this.getCacheNode("background",n,()=>{if(n.isCubeTexture===!0||n.mapping===Ko||n.mapping===Zo||n.mapping===so){if(e.backgroundBlurriness>0||n.mapping===so)return Fy(n);{let o;return n.isCubeTexture===!0?o=oi(n):o=Gt(n),Ay(o)}}else{if(n.isTexture===!0)return Gt(n,no.flipY()).setUpdateMatrix(!0);n.isColor!==!0&&ne("WebGPUNodes: Unsupported background configuration.",n)}},i);t.backgroundNode=s,t.background=n,t.backgroundBlurriness=e.backgroundBlurriness}}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}getCacheNode(e,t,n,i=!1){const s=this.cacheLib[e]||(this.cacheLib[e]=new WeakMap);let o=s.get(t);return(o===void 0||i)&&(o=n(),s.set(t,o)),o}updateFog(e){const t=this.get(e),n=e.fog;if(n){if(t.fog!==n){const i=this.getCacheNode("fog",n,()=>{if(n.isFogExp2){const s=Qt("color","color",n).setGroup(qe),o=Qt("density","float",n).setGroup(qe);return S_(s,rU(o))}else if(n.isFog){const s=Qt("color","color",n).setGroup(qe),o=Qt("near","float",n).setGroup(qe),a=Qt("far","float",n).setGroup(qe);return S_(s,sU(o,a))}else ne("Renderer: Unsupported fog configuration.",n)});t.fogNode=i,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 i=this.getCacheNode("environment",n,()=>{if(n.isCubeTexture===!0)return oi(n);if(n.isTexture===!0)return Gt(n);ne("Nodes: Unsupported environment configuration.",n)});t.environmentNode=i,t.environment=n}}else t.environmentNode&&(delete t.environmentNode,delete t.environment)}getNodeFrame(e=this.renderer,t=null,n=null,i=null,s=null){const o=this.nodeFrame;return o.renderer=e,o.scene=t,o.object=n,o.camera=i,o.material=s,o}getNodeFrameForRender(e){return this.getNodeFrame(e.renderer,e.scene,e.object,e.camera,e.material)}getOutputCacheKey(){const e=this.renderer;return e.toneMapping+","+e.currentColorSpace+","+e.xr.isPresenting}getOutputNode(e){const t=this.renderer;return e.isArrayTexture?Gt(e,no).depth(qa("gl_ViewID_OVR")).renderOutput(t.toneMapping,t.currentColorSpace):Gt(e,no).renderOutput(t.toneMapping,t.currentColorSpace)}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 i of n.updateNodes)t.updateNode(i)}updateForRender(e){const t=this.getNodeFrameForRender(e),n=e.getNodeBuilderState();for(const i of n.updateNodes)t.updateNode(i)}needsRefresh(e){const t=this.getNodeFrameForRender(e);return e.getMonitor().needsRefresh(e,t)}dispose(){super.dispose(),this.nodeFrame=new A_,this.nodeBuilderCache=new Map,this.cacheLib={}}}const Bd=new os;class $u{constructor(e=null){this.version=0,this.clipIntersection=null,this.cacheKey="",this.shadowPass=!1,this.viewNormalMatrix=new Ke,this.clippingGroupContexts=new WeakMap,this.intersectionPlanes=[],this.unionPlanes=[],this.parentVersion=null,e!==null&&(this.viewNormalMatrix=e.viewNormalMatrix,this.clippingGroupContexts=e.clippingGroupContexts,this.shadowPass=e.shadowPass,this.viewMatrix=e.viewMatrix)}projectPlanes(e,t,n){const i=e.length;for(let s=0;sj0(h,n.toneMapping,n.outputColorSpace)}),P_.set(l,c))}else c=l;n.contextNode=c,n.setRenderTarget(a.renderTarget),a.rendercall(),n.contextNode=l}n.setRenderTarget(o),n._setXRLayerSize(s.x,s.y),this.isPresenting=i}getSession(){return this._session}async setSession(e){const t=this._renderer,n=t.backend;this._gl=t.getContext();const i=this._gl,s=i.getContextAttributes();if(this._session=e,e!==null){if(n.isWebGPUBackend===!0)throw new Error('THREE.XRManager: XR is currently not supported with a WebGPU backend. Use WebGL by passing "{ forceWebGL: true }" to the constructor of the renderer.');if(e.addEventListener("select",this._onSessionEvent),e.addEventListener("selectstart",this._onSessionEvent),e.addEventListener("selectend",this._onSessionEvent),e.addEventListener("squeeze",this._onSessionEvent),e.addEventListener("squeezestart",this._onSessionEvent),e.addEventListener("squeezeend",this._onSessionEvent),e.addEventListener("end",this._onSessionEnd),e.addEventListener("inputsourceschange",this._onInputSourcesChange),await n.makeXRCompatible(),this._currentPixelRatio=t.getPixelRatio(),t.getSize(this._currentSize),this._currentAnimationContext=t._animation.getContext(),this._currentAnimationLoop=t._animation.getAnimationLoop(),t._animation.stop(),this._supportsLayers===!0){let o=null,a=null,l=null;t.depth&&(l=t.stencil?i.DEPTH24_STENCIL8:i.DEPTH_COMPONENT24,o=t.stencil?$n:Nn,a=t.stencil?ui:wt);const c={colorFormat:i.RGBA8,depthFormat:l,scaleFactor:this._framebufferScaleFactor,clearOnAccess:!1};this._useMultiviewIfPossible&&t.hasFeature("OVR_multiview2")&&(c.textureType="texture-array",this._useMultiview=!0),this._glBinding=this.getBinding();const u=this._glBinding.createProjectionLayer(c),h=[u];this._glProjLayer=u,t.setPixelRatio(1),t._setXRLayerSize(u.textureWidth,u.textureHeight);const d=this._useMultiview?2:1,f=new Xn(u.textureWidth,u.textureHeight,a,void 0,void 0,void 0,void 0,void 0,void 0,o,d);if(this._xrRenderTarget=new vl(u.textureWidth,u.textureHeight,{format:an,type:$t,colorSpace:t.outputColorSpace,depthTexture:f,stencilBuffer:t.stencil,samples:s.antialias?4:0,resolveDepthBuffer:u.ignoreDepthValues===!1,resolveStencilBuffer:u.ignoreDepthValues===!1,depth:this._useMultiview?2:1,multiview:this._useMultiview}),this._xrRenderTarget._hasExternalTextures=!0,this._xrRenderTarget.depth=this._useMultiview?2:1,this._sessionUsesLayers=e.enabledFeatures.includes("layers"),this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType()),this._sessionUsesLayers)for(const p of this._layers)p.plane.material=new us({color:16777215,side:p.type==="cylinder"?Pt:ni}),p.plane.material.blending=Jr,p.plane.material.blendEquation=Wn,p.plane.material.blendSrc=Us,p.plane.material.blendDst=Us,p.xrlayer=this._createXRLayer(p),h.unshift(p.xrlayer);e.updateRenderState({layers:h})}else{const o={antialias:t.currentSamples>0,alpha:!0,depth:t.depth,stencil:t.stencil,framebufferScaleFactor:this.getFramebufferScaleFactor()},a=new XRWebGLLayer(e,i,o);this._glBaseLayer=a,e.updateRenderState({baseLayer:a}),t.setPixelRatio(1),t._setXRLayerSize(a.framebufferWidth,a.framebufferHeight),this._xrRenderTarget=new vl(a.framebufferWidth,a.framebufferHeight,{format:an,type:$t,colorSpace:t.outputColorSpace,stencilBuffer:t.stencil,resolveDepthBuffer:a.ignoreDepthValues===!1,resolveStencilBuffer:a.ignoreDepthValues===!1}),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(t===null)return;const n=e.near,i=e.far,s=this._cameraXR,o=this._cameraL,a=this._cameraR;s.near=a.near=o.near=n,s.far=a.far=o.far=i,s.isMultiViewCamera=this._useMultiview,(this._currentDepthNear!==s.near||this._currentDepthFar!==s.far)&&(t.updateRenderState({depthNear:s.near,depthFar:s.far}),this._currentDepthNear=s.near,this._currentDepthFar=s.far),s.layers.mask=e.layers.mask|6,o.layers.mask=s.layers.mask&-5,a.layers.mask=s.layers.mask&-3;const l=e.parent,c=s.cameras;D_(s,l);for(let u=0;u=0&&(t[s]=null,e[s].disconnect(i))}for(let n=0;n=t.length){t.push(i),s=a;break}else if(t[a]===null){t[a]=i,s=a;break}if(s===-1)break}const o=e[s];o&&o.connect(i)}}function VF(r){return r.type==="quad"?this._glBinding.createQuadLayer({transform:new XRRigidTransform(r.translation,r.quaternion),width:r.width/2,height:r.height/2,space:this._referenceSpace,viewPixelWidth:r.pixelwidth,viewPixelHeight:r.pixelheight,clearOnAccess:!1}):this._glBinding.createCylinderLayer({transform:new XRRigidTransform(r.translation,r.quaternion),radius:r.radius,centralAngle:r.centralAngle,aspectRatio:r.aspectRatio,space:this._referenceSpace,viewPixelWidth:r.pixelwidth,viewPixelHeight:r.pixelheight,clearOnAccess:!1})}function zF(r,e){if(e===void 0)return;const t=this._cameraXR,n=this._renderer,i=n.backend,s=this._glBaseLayer,o=this.getReferenceSpace(),a=e.getViewerPose(o);if(this._xrFrame=e,a!==null){const l=a.views;this._glBaseLayer!==null&&i.setXRTarget(s.framebuffer);let c=!1;l.length!==t.cameras.length&&(t.cameras.length=0,c=!0);for(let u=0;u{await this.compileAsync(p,g);const _=this._renderLists.get(p,g),x=this._renderContexts.get(this._renderTarget,this._mrt),v=p.overrideMaterial||m.material,S=this._objects.get(m,v,p,g,_.lightsNode,x,x.clippingContext),{fragmentShader:E,vertexShader:T}=S.getNodeBuilderState();return{fragmentShader:E,vertexShader:T}}}}async init(){return this._initPromise!==null?this._initPromise:(this._initPromise=new Promise(async(e,t)=>{let n=this.backend;try{await n.init(this)}catch(i){if(this._getFallback!==null)try{this.backend=n=this._getFallback(i),await n.init(this)}catch(s){t(s);return}else{t(i);return}}this._nodes=new NF(this,n),this._animation=new pL(this,this._nodes,this.info),this._attributes=new SL(n,this.info),this._background=new WU(this,this._nodes),this._geometries=new bL(this._attributes,this.info),this._textures=new IL(this,n,this.info),this._pipelines=new RL(n,this._nodes,this.info),this._bindings=new wL(n,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new xL(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new PL(this.lighting),this._bundles=new DF,this._renderContexts=new UL(this),this._animation.start(),this._initialized=!0,this._inspector.init(),e(this)}),this._initPromise)}get domElement(){return this._canvasTarget.domElement}get coordinateSystem(){return this.backend.coordinateSystem}async compileAsync(e,t,n=null){if(this._isDeviceLost===!0)return;this._initialized===!1&&await this.init();const i=this._nodes.nodeFrame,s=i.renderId,o=this._currentRenderContext,a=this._currentRenderObjectFunction,l=this._handleObjectFunction,c=this._compilationPromises;n===null&&(n=e);const u=e.isScene===!0?e:n.isScene===!0?n:L_,d=this.needsFrameBufferTarget&&this._renderTarget===null?this._getFrameBufferTarget():this._renderTarget||this._outputRenderTarget,f=this._renderContexts.get(d,this._mrt),p=this._activeMipmapLevel,g=[];this._currentRenderContext=f,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=g,i.renderId++,i.update(),f.depth=this.depth,f.stencil=this.stencil,f.clippingContext||(f.clippingContext=new $u),f.clippingContext.updateGlobal(u,t),u.onBeforeRender(this,e,t,d);const m=this._renderLists.get(u,t);if(m.begin(),this._projectObject(e,t,0,m,f.clippingContext),n!==e&&n.traverseVisible(function(E){E.isLight&&E.layers.test(t.layers)&&m.pushLight(E)}),m.finish(),d!==null){this._textures.updateRenderTarget(d,p);const E=this._textures.get(d);f.textures=E.textures,f.depthTexture=E.depthTexture}else f.textures=null,f.depthTexture=null;n!==e?this._background.update(n,m,f):this._background.update(u,m,f);const _=m.opaque,x=m.transparent,v=m.transparentDoublePass,S=m.lightsNode;this.opaque===!0&&_.length>0&&this._renderObjects(_,t,u,S),this.transparent===!0&&x.length>0&&this._renderTransparents(x,v,t,u,S),i.renderId=s,this._currentRenderContext=o,this._currentRenderObjectFunction=a,this._handleObjectFunction=l,this._compilationPromises=c;for(const E of g){const T=this._objects.get(E.object,E.material,E.scene,E.camera,E.lightsNode,E.renderContext,E.clippingContext,E.passId);T.drawRange=E.object.geometry.drawRange,T.group=E.group,this._geometries.updateForRender(T),await this._nodes.getForRenderAsync(T),this._nodes.updateBefore(T),this._nodes.updateForRender(T),this._bindings.updateForRender(T);const A=[];this._pipelines.getForRender(T,A),A.length>0&&await Promise.all(A),this._nodes.updateAfter(T),await Tx()}}async renderAsync(e,t){Yt('Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.render(e,t)}async waitForGPU(){ne("Renderer: waitForGPU() has been removed. Read https://github.com/mrdoob/three.js/issues/32012 for more information.")}set inspector(e){this._inspector!==null&&this._inspector.setRenderer(null),this._inspector=e,this._inspector.setRenderer(this)}get inspector(){return this._inspector}set highPrecision(e){const t=this.contextNode.value;e===!0?(t.modelViewMatrix=Lg,t.modelNormalViewMatrix=Ug):this.highPrecision&&(delete t.modelViewMatrix,delete t.modelNormalViewMatrix)}get highPrecision(){const e=this.contextNode.value;return e.modelViewMatrix===Lg&&e.modelNormalViewMatrix===Ug}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getOutputBufferType(){return this._outputBufferType}getColorBufferType(){return Yt('Renderer: ".getColorBufferType()" has been renamed to ".getOutputBufferType()".'),this.getOutputBufferType()}_onDeviceLost(e){let t=`THREE.WebGPURenderer: ${e.api} Device Lost: Message: ${e.message}`;e.reason&&(t+=` Reason: ${e.reason}`),ne(t),this._isDeviceLost=!0}_renderBundle(e,t,n){const{bundleGroup:i,camera:s,renderList:o}=e,a=this._currentRenderContext,l=this._bundles.get(i,s,a),c=this.backend.get(l),u=i.version!==c.version;if(u||c.bundleGPU===void 0){this.backend.beginBundle(a),(c.renderObjects===void 0||u)&&(c.renderObjects=[]),this._currentRenderBundle=l;const{transparentDoublePass:d,transparent:f,opaque:p}=o;this.opaque===!0&&p.length>0&&this._renderObjects(p,s,t,n),this.transparent===!0&&f.length>0&&this._renderTransparents(f,d,s,t,n),this._currentRenderBundle=null,this.backend.finishBundle(a,l),c.version=i.version}else{const{renderObjects:d}=c;for(let f=0,p=d.length;f{c.removeEventListener("dispose",m),u.dispose(),this._frameBufferTargets.delete(c)};c.addEventListener("dispose",m),this._frameBufferTargets.set(c,u)}const h=this.getOutputRenderTarget();u.depthBuffer=a,u.stencilBuffer=l,h!==null?u.setSize(h.width,h.height,h.depth):u.setSize(s,o,1);const d=this._outputRenderTarget?this._outputRenderTarget.viewport:c._viewport,f=this._outputRenderTarget?this._outputRenderTarget.scissor:c._scissor,p=this._outputRenderTarget?1:c._pixelRatio,g=this._outputRenderTarget?this._outputRenderTarget.scissorTest:c._scissorTest;return u.viewport.copy(d),u.scissor.copy(f),u.viewport.multiplyScalar(p),u.scissor.multiplyScalar(p),u.scissorTest=g,u.multiview=h!==null?h.multiview:!1,u.resolveDepthBuffer=h!==null?h.resolveDepthBuffer:!0,u._autoAllocateDepthBuffer=h!==null?h._autoAllocateDepthBuffer:!1,u}_renderScene(e,t,n=!0){if(this._isDeviceLost===!0)return;const i=n?this._getFrameBufferTarget():null,s=this._nodes.nodeFrame,o=s.renderId,a=this._currentRenderContext,l=this._currentRenderObjectFunction,c=this._handleObjectFunction;this._callDepth++;const u=e.isScene===!0?e:L_,h=this._renderTarget||this._outputRenderTarget,d=this._activeCubeFace,f=this._activeMipmapLevel;let p;if(i!==null?(p=i,this.setRenderTarget(p)):p=h,p!==null&&p.depthBuffer===!0){const V=this._textures.get(p);V.depthInitialized!==!0&&((this.autoClear===!1||this.autoClear===!0&&this.autoClearDepth===!1)&&this.clearDepth(),V.depthInitialized=!0)}const g=this._renderContexts.get(p,this._mrt,this._callDepth);this._currentRenderContext=g,this._currentRenderObjectFunction=this._renderObjectFunction||this.renderObject,this._handleObjectFunction=this._renderObjectDirect,this.info.calls++,this.info.render.calls++,this.info.render.frameCalls++,s.renderId=this.info.calls,this.backend.updateTimeStampUID(g),this.inspector.beginRender(this.backend.getTimestampUID(g),e,t,p);const m=this.xr;if(m.isPresenting===!1){let V=!1;if(this.reversedDepthBuffer===!0&&t.reversedDepth!==!0){if(t._reversedDepth=!0,t.isArrayCamera)for(const B of t.cameras)B._reversedDepth=!0;V=!0}const L=this.coordinateSystem;if(t.coordinateSystem!==L){if(t.coordinateSystem=L,t.isArrayCamera)for(const B of t.cameras)B.coordinateSystem=L;V=!0}if(V===!0&&(t.updateProjectionMatrix(),t.isArrayCamera))for(const B of t.cameras)B.updateProjectionMatrix()}e.matrixWorldAutoUpdate===!0&&e.updateMatrixWorld(),t.parent===null&&t.matrixWorldAutoUpdate===!0&&t.updateMatrixWorld(),m.enabled===!0&&m.isPresenting===!0&&(m.cameraAutoUpdate===!0&&m.updateCamera(t),t=m.getCamera());const _=this._canvasTarget;let x=_._viewport,v=_._scissor,S=_._pixelRatio;p!==null&&(x=p.viewport,v=p.scissor,S=1),this.getDrawingBufferSize(zo),Od.set(0,0,zo.width,zo.height);const E=x.minDepth===void 0?0:x.minDepth,T=x.maxDepth===void 0?1:x.maxDepth;g.viewportValue.copy(x).multiplyScalar(S).floor(),g.viewportValue.width>>=f,g.viewportValue.height>>=f,g.viewportValue.minDepth=E,g.viewportValue.maxDepth=T,g.viewport=g.viewportValue.equals(Od)===!1,g.scissorValue.copy(v).multiplyScalar(S).floor(),g.scissor=_._scissorTest&&g.scissorValue.equals(Od)===!1,g.scissorValue.width>>=f,g.scissorValue.height>>=f,g.clippingContext||(g.clippingContext=new $u),g.clippingContext.updateGlobal(u,t),u.onBeforeRender(this,e,t,p);const A=t.isArrayCamera?Gd:kd;t.isArrayCamera||(uu.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),A.setFromProjectionMatrix(uu,t.coordinateSystem,t.reversedDepth));const y=this._renderLists.get(e,t);if(y.begin(),this._projectObject(e,t,0,y,g.clippingContext),y.finish(),this.sortObjects===!0&&y.sort(this._opaqueSort,this._transparentSort),p!==null){this._textures.updateRenderTarget(p,f);const V=this._textures.get(p);g.textures=V.textures,g.depthTexture=V.depthTexture,g.width=V.width,g.height=V.height,g.renderTarget=p,g.depth=p.depthBuffer,g.stencil=p.stencilBuffer}else g.textures=null,g.depthTexture=null,g.width=zo.width,g.height=zo.height,g.depth=this.depth,g.stencil=this.stencil;g.width>>=f,g.height>>=f,g.activeCubeFace=d,g.activeMipmapLevel=f,g.occlusionQueryCount=y.occlusionQueryCount,g.scissorValue.max(Ps.set(0,0,0,0)),g.scissorValue.x+g.scissorValue.width>g.width&&(g.scissorValue.width=Math.max(g.width-g.scissorValue.x,0)),g.scissorValue.y+g.scissorValue.height>g.height&&(g.scissorValue.height=Math.max(g.height-g.scissorValue.y,0)),this._background.update(u,y,g),g.camera=t,this.backend.beginRender(g);const{bundles:R,lightsNode:P,transparentDoublePass:N,transparent:U,opaque:G}=y;return R.length>0&&this._renderBundles(R,u,P),this.opaque===!0&&G.length>0&&this._renderObjects(G,t,u,P),this.transparent===!0&&U.length>0&&this._renderTransparents(U,N,t,u,P),this.backend.finishRender(g),s.renderId=o,this._currentRenderContext=a,this._currentRenderObjectFunction=l,this._handleObjectFunction=c,this._callDepth--,i!==null&&(this.setRenderTarget(h,d,f),this._renderOutput(p)),u.onAfterRender(this,e,t,p),this.inspector.finishRender(this.backend.getTimestampUID(g)),g}_setXRLayerSize(e,t){this._canvasTarget._width=e,this._canvasTarget._height=t,this.setViewport(0,0,e,t)}_renderOutput(e){const t=this._nodes.getOutputCacheKey();let n=this._quadCache.get(e.texture),i;if(n===void 0){i=new Wy(new dn),i.name="Output Color Transform",i.material.name="outputColorTransform",i.material.fragmentNode=this._nodes.getOutputNode(e.texture),n={quad:i,cacheKey:t},this._quadCache.set(e.texture,n);const a=()=>{i.material.dispose(),this._quadCache.delete(e.texture),e.texture.removeEventListener("dispose",a)};e.texture.addEventListener("dispose",a)}else i=n.quad,n.cacheKey!==t&&(i.material.fragmentNode=this._nodes.getOutputNode(e.texture),i.material.needsUpdate=!0,n.cacheKey=t);const s=this.autoClear,o=this.xr.enabled;this.autoClear=!1,this.xr.enabled=!1,this._renderScene(i,i.camera,!1),this.autoClear=s,this.xr.enabled=o}getMaxAnisotropy(){return this.backend.capabilities.getMaxAnisotropy()}getActiveCubeFace(){return this._activeCubeFace}getActiveMipmapLevel(){return this._activeMipmapLevel}async setAnimationLoop(e){this._initialized===!1&&await this.init(),this._animation.setAnimationLoop(e)}getAnimationLoop(){return this._animation.getAnimationLoop()}async getArrayBufferAsync(e,t=null,n=0,i=-1){if(t!==null&&t.isReadbackBuffer&&this.info.memoryMap.has(t)===!1){this.info.createReadbackBuffer(t);const s=()=>{t.removeEventListener("dispose",s),this.info.destroyReadbackBuffer(t)};t.addEventListener("dispose",s)}if(n%4!==0||i>0&&i%4!==0)throw new Error('THREE.Renderer: "getArrayBufferAsync()" offset and count must be a multiple of 4.');return await this.backend.getArrayBufferAsync(e,t,n,i)}getContext(){return this.backend.getContext()}getPixelRatio(){return this._canvasTarget.getPixelRatio()}getDrawingBufferSize(e){return this._canvasTarget.getDrawingBufferSize(e)}getSize(e){return this._canvasTarget.getSize(e)}setPixelRatio(e=1){this._canvasTarget.setPixelRatio(e)}setDrawingBufferSize(e,t,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,i){this._canvasTarget.setScissor(e,t,n,i)}getScissorTest(){return this._canvasTarget.getScissorTest()}setScissorTest(e){this._canvasTarget.setScissorTest(e),this.backend.setScissorTest(e)}getViewport(e){return this._canvasTarget.getViewport(e)}setViewport(e,t,n,i,s=0,o=1){this._canvasTarget.setViewport(e,t,n,i,s,o)}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.reversedDepthBuffer===!0?1-this._clearDepth:this._clearDepth}setClearDepth(e){this._clearDepth=e}getClearStencil(){return this._clearStencil}setClearStencil(e){this._clearStencil=e}isOccluded(e){const t=this._currentRenderContext;return t&&this.backend.isOccluded(t,e)}clear(e=!0,t=!0,n=!0){if(this._initialized===!1)throw new Error('Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before before using this method.');const i=this._renderTarget||this._getFrameBufferTarget();let s=null;if(i!==null){this._textures.updateRenderTarget(i);const o=this._textures.get(i);s=this._renderContexts.get(i,null,-1),s.textures=o.textures,s.depthTexture=o.depthTexture,s.width=o.width,s.height=o.height,s.renderTarget=i,s.depth=i.depthBuffer,s.stencil=i.stencilBuffer;const a=this.backend.getClearColor();s.clearColorValue.r=a.r,s.clearColorValue.g=a.g,s.clearColorValue.b=a.b,s.clearColorValue.a=a.a,s.clearDepthValue=this.getClearDepth(),s.clearStencilValue=this.getClearStencil(),s.activeCubeFace=this.getActiveCubeFace(),s.activeMipmapLevel=this.getActiveMipmapLevel(),i.depthBuffer===!0&&(o.depthInitialized=!0)}this.backend.clear(e,t,n,s),i!==null&&this._renderTarget===null&&this._renderOutput(i)}clearColor(){this.clear(!0,!1,!1)}clearDepth(){this.clear(!1,!0,!1)}clearStencil(){this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,n=!0){Yt('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(){Yt('Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.'),this.clear(!0,!1,!1)}async clearDepthAsync(){Yt('Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!0,!1)}async clearStencilAsync(){Yt('Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!1,!0)}get needsFrameBufferTarget(){const e=this.currentToneMapping!==Un,t=this.currentColorSpace!==Xe.workingColorSpace;return e||t}get samples(){return this._samples}get currentSamples(){let e=this._samples;return this._renderTarget!==null?e=this._renderTarget.samples:this.needsFrameBufferTarget&&(e=0),e}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:Un}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:Xe.workingColorSpace}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||this._renderTarget===null}dispose(){if(this._initialized===!0){this.info.dispose(),this.backend.dispose(),this._animation.dispose(),this._objects.dispose(),this._geometries.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose(),this._textures.dispose();for(const e of this._frameBufferTargets.keys())e.dispose();Object.values(this.backend.timestampQueryPool).forEach(e=>{e!==null&&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);for(const e of this._frameBufferTargets.keys())e.dispose()}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}compute(e,t=null){if(this._isDeviceLost===!0)return;if(this._initialized===!1)return ee("Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead."),this.computeAsync(e,t);const n=this._nodes.nodeFrame,i=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 s=this.backend,o=this._pipelines,a=this._bindings,l=this._nodes,c=Array.isArray(e)?e:[e];if(c[0]===void 0||c[0].isComputeNode!==!0)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");s.beginCompute(e);for(const u of c){if(o.has(u)===!1){const f=()=>{u.removeEventListener("dispose",f),o.delete(u),a.deleteForCompute(u),l.delete(u)};u.addEventListener("dispose",f);const p=u.onInitFunction;p!==null&&p.call(u,{renderer:this})}l.updateForCompute(u),a.updateForCompute(u);const h=a.getForCompute(u),d=o.getForCompute(u,h);s.compute(e,u,h,d,t)}s.finishCompute(e),n.renderId=i,this.inspector.finishCompute(this.backend.getTimestampUID(e))}async computeAsync(e,t=null){this._initialized===!1&&await this.init(),this.compute(e,t)}async hasFeatureAsync(e){return Yt('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 this._initialized===!1&&await this.init(),this.backend.resolveTimestampsAsync(e)}hasFeature(e){if(this._initialized===!1)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){Yt('Renderer: "initTextureAsync()" has been deprecated. Use "initTexture()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.initTexture(e)}initTexture(e){if(this._initialized===!1)throw new Error('Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before before using this method.');this._textures.updateTexture(e)}initRenderTarget(e){if(this._initialized===!1)throw new Error('Renderer: .initRenderTarget() called before the backend is initialized. Use "await renderer.init();" before before using this method.');this._textures.updateRenderTarget(e);const t=this._textures.get(e),n=this._renderContexts.get(e);n.textures=t.textures,n.depthTexture=t.depthTexture,n.width=t.width,n.height=t.height,n.renderTarget=e,n.depth=e.depthBuffer,n.stencil=e.stencilBuffer,this.backend.initRenderTarget(n)}copyFramebufferToTexture(e,t=null){if(t!==null)if(t.isVector2)t=Ps.set(t.x,t.y,e.image.width,e.image.height).floor();else if(t.isVector4)t=Ps.copy(t).floor();else{ne("Renderer.copyFramebufferToTexture: Invalid rectangle.");return}else t=Ps.set(0,0,e.image.width,e.image.height);let n=this._currentRenderContext,i;n!==null?i=n.renderTarget:(i=this._renderTarget||this._getFrameBufferTarget(),i!==null&&(this._textures.updateRenderTarget(i),n=this._textures.get(i))),this._textures.updateTexture(e,{renderTarget:i}),this.backend.copyFramebufferToTexture(e,n,t),this._inspector.copyFramebufferToTexture(e)}copyTextureToTexture(e,t,n=null,i=null,s=0,o=0){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,n,i,s,o),this._inspector.copyTextureToTexture(e,t)}async readRenderTargetPixelsAsync(e,t,n,i,s,o=0,a=0){return this.backend.copyTextureToBuffer(e.textures[o],t,n,i,s,a)}_projectObject(e,t,n,i,s){if(e.visible===!1)return;if(e.layers.test(t.layers)){if(e.isGroup)n=e.renderOrder,e.isClippingGroup&&e.enabled&&(s=s.getGroupContext(e));else if(e.isLOD)e.autoUpdate===!0&&e.update(t);else if(e.isLight)i.pushLight(e);else if(e.isSprite){const l=t.isArrayCamera?Gd:kd;if(!e.frustumCulled||l.intersectsSprite(e,t)){this.sortObjects===!0&&Ps.setFromMatrixPosition(e.matrixWorld).applyMatrix4(uu);const{geometry:c,material:u}=e;u.visible&&i.push(e,c,u,n,Ps.z,null,s)}}else if(e.isLineLoop)ne("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 l=t.isArrayCamera?Gd:kd;if(!e.frustumCulled||l.intersectsObject(e,t)){const{geometry:c,material:u}=e;if(this.sortObjects===!0&&(c.boundingSphere===null&&c.computeBoundingSphere(),Ps.copy(c.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(uu)),Array.isArray(u)){const h=c.groups;for(let d=0,f=h.length;d0){for(const{material:o}of t)o.side=Pt;this._renderObjects(t,n,i,s,"backSide");for(const{material:o}of t)o.side=ni;this._renderObjects(e,n,i,s);for(const{material:o}of t)o.side=wn}else this._renderObjects(e,n,i,s)}_renderObjects(e,t,n,i,s=null){for(let o=0,a=e.length;o(f.not().discard(),p))(c)}}e.depthNode&&e.depthNode.isNode&&(u=e.depthNode),e.castShadowPositionNode&&e.castShadowPositionNode.isNode?l=e.castShadowPositionNode:e.positionNode&&e.positionNode.isNode&&(l=e.positionNode),n={version:t,colorNode:c,depthNode:u,positionNode:l},this._cacheShadowNodes.set(e,n)}return n}renderObject(e,t,n,i,s,o,a,l=null,c=null){let u=!1,h,d,f,p;if(e.onBeforeRender(this,t,n,i,s,o),s.allowOverride===!0&&t.overrideMaterial!==null){const g=t.overrideMaterial;if(u=!0,h=g.isNodeMaterial?g.colorNode:null,d=g.isNodeMaterial?g.depthNode:null,f=g.isNodeMaterial?g.positionNode:null,p=t.overrideMaterial.side,s.positionNode&&s.positionNode.isNode&&(g.positionNode=s.positionNode),g.alphaTest=s.alphaTest,g.alphaMap=s.alphaMap,g.transparent=s.transparent||s.transmission>0||s.transmissionNode&&s.transmissionNode.isNode||s.backdropNode&&s.backdropNode.isNode,g.isShadowPassMaterial){const{colorNode:m,depthNode:_,positionNode:x}=this._getShadowNodes(s);this.shadowMap.type===fs?g.side=s.shadowSide!==null?s.shadowSide:s.side:g.side=s.shadowSide!==null?s.shadowSide:WF[s.side],m!==null&&(g.colorNode=m),_!==null&&(g.depthNode=_),x!==null&&(g.positionNode=x)}s=g}s.transparent===!0&&s.side===wn&&s.forceSinglePass===!1?(s.side=Pt,this._handleObjectFunction(e,s,t,n,a,o,l,"backSide"),s.side=ni,this._handleObjectFunction(e,s,t,n,a,o,l,c),s.side=wn):this._handleObjectFunction(e,s,t,n,a,o,l,c),u&&(t.overrideMaterial.colorNode=h,t.overrideMaterial.depthNode=d,t.overrideMaterial.positionNode=f,t.overrideMaterial.side=p),e.onAfterRender(this,t,n,i,s,o)}hasCompatibility(e){if(this._initialized===!1)throw new Error('Renderer: .hasCompatibility() called before the backend is initialized. Use "await renderer.init();" before using this method.');return this.backend.hasCompatibility(e)}_renderObjectDirect(e,t,n,i,s,o,a,l){const c=this._objects.get(e,t,n,i,s,this._currentRenderContext,a,l);c.drawRange=e.geometry.drawRange,c.group=o,this._currentRenderBundle!==null&&(this.backend.get(this._currentRenderBundle).renderObjects.push(c),c.bundle=this._currentRenderBundle.bundleGroup);const u=this._nodes.needsRefresh(c);u&&(this._nodes.updateBefore(c),this._geometries.updateForRender(c),this._nodes.updateForRender(c),this._bindings.updateForRender(c)),this._pipelines.updateForRender(c),this._pipelines.isReady(c)&&(this.backend.draw(c,this.info),u&&this._nodes.updateAfter(c))}_createObjectPipeline(e,t,n,i,s,o,a,l){if(this._compilationPromises!==null){this._compilationPromises.push({object:e,material:t,scene:n,camera:i,lightsNode:s,group:o,clippingContext:a,passId:l,renderContext:this._currentRenderContext});return}const c=this._objects.get(e,t,n,i,s,this._currentRenderContext,a,l);c.drawRange=e.geometry.drawRange,c.group=o,this._nodes.updateBefore(c),this._geometries.updateForRender(c),this._nodes.updateForRender(c),this._bindings.updateForRender(c),this._pipelines.getForRender(c,this._compilationPromises),this._nodes.updateAfter(c)}_onCanvasTargetResize(){this._initialized&&this.backend.updateSize()}get compile(){return this.compileAsync}}class iv{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}getVisibility(){return this.visibility}clone(){return Object.assign(new this.constructor,this)}}function XF(r){return r+(ur-r%ur)%ur}class sv extends iv{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 XF(this._buffer.byteLength)}get buffer(){return this._buffer}update(){return!0}}class rv extends sv{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let qF=0;class ov extends rv{constructor(e,t){super("UniformBuffer_"+qF++,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 jF extends rv{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[],this._updateRangeCache=new Map}addUniformUpdateRange(e){const t=e.index;if(this._updateRangeCache.has(t)!==!0){const n=this.updateRanges,i=e.offset,s=e.itemSize,o={start:i,count:s};n.push(o),this._updateRangeCache.set(t,o)}}clearUpdateRanges(){this._updateRangeCache.clear(),super.clearUpdateRanges()}addUniform(e){return this.uniforms.push(e),this}removeUniform(e){const t=this.uniforms.indexOf(e);return t!==-1&&this.uniforms.splice(t,1),this}get values(){return this._values===null&&(this._values=Array.from(this.buffer)),this._values}get buffer(){let e=this._buffer;if(e===null){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,i=this.uniforms.length;n{this.generation=null,this.version=-1},this.texture=t,this.version=t?t.version:-1,this.generation=null,this.samplerKey="",this.isSampler=!0}set texture(e){this._texture!==e&&(this._texture&&this._texture.removeEventListener("dispose",this._onTextureDispose),this._texture=e,this.generation=null,this.version=-1,this._texture&&this._texture.addEventListener("dispose",this._onTextureDispose))}get texture(){return this._texture}update(){const{texture:e,version:t}=this;return t!==e.version?(this.version=e.version,!0):!1}clone(){const e=super.clone();return e._texture=null,e._onTextureDispose=()=>{e.generation=null,e.version=-1},e.texture=this.texture,e}}let QF=0;class JF extends lv{constructor(e,t){super(e,t),this.id=QF++,this.store=!1,this.mipLevel=0,this.isSampledTexture=!0}}class mh extends JF{constructor(e,t,n,i=null){super(e,t?t.value:null),this.textureNode=t,this.groupNode=n,this.access=i}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class cv extends mh{constructor(e,t,n,i=null){super(e,t,n,i),this.isSampledCubeTexture=!0}}class wf extends mh{constructor(e,t,n,i=null){super(e,t,n,i),this.isSampledTexture3D=!0}}const U_={bitcast_int_uint:new An("uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }"),bitcast_uint_int:new An("uint tsl_bitcast_uint_to_int ( uint x ) { return floatBitsToInt( uintBitsToFloat ( x ) ); }")},eI={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"},F_={low:"lowp",medium:"mediump",high:"highp"},I_={swizzleAssign:!0,storageBuffer:!1},B_={perspective:"smooth",linear:"noperspective"},O_={centroid:"centroid"},k_=` precision highp float; precision highp int; precision highp sampler2D; precision highp sampler3D; precision highp samplerCube; precision highp sampler2DArray; precision highp usampler2D; precision highp usampler3D; precision highp usamplerCube; precision highp usampler2DArray; precision highp isampler2D; precision highp isampler3D; precision highp isamplerCube; precision highp isampler2DArray; precision highp sampler2DShadow; precision highp sampler2DArrayShadow; precision highp samplerCubeShadow; `;class tI extends ev{constructor(e,t){super(e,t,new CF),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]}}needsToWorkingColorSpace(e){return e.isVideoTexture===!0&&e.colorSpace!==ri}_include(e){const t=U_[e];return t.build(this),this.addInclude(t),t}getMethod(e){return U_[e]!==void 0&&this._include(e),eI[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),i=[];for(const o of t.inputs)i.push(this.getType(o.type)+" "+o.name);return`${this.getType(t.type)} ${t.name}( ${i.join(", ")} ) { ${n.vars} ${n.code} return ${n.result}; }`}setupPBO(e){const t=e.value;if(t.pbo===void 0){const n=t.array,i=t.count*t.itemSize,{itemSize:s}=t,o=t.array.constructor.name.toLowerCase().includes("int");let a=o?mo:Oa;s===2?a=o?go:Fn:s===3?a=o?xx:Ba:s===4&&(a=o?ka:an);const l={Float32Array:Zt,Uint8Array:$t,Uint16Array:Ci,Uint32Array:wt,Int8Array:_r,Int16Array:xr,Int32Array:Sn,Uint8ClampedArray:$t},c=Math.pow(2,Math.ceil(Math.log2(Math.sqrt(i/s))));let u=Math.ceil(i/s/c);c*u*s0?h:"";a=`${c.name} { ${u} ${o.name}[${d}]; }; `}else{const c=o.groupNode.name;if(i[c]===void 0){const u=this.uniformGroups[c];if(u!==void 0){const h=[];for(const d of u.uniforms){const f=d.getType(),p=this.getVectorType(f),g=d.nodeUniform.node.precision;let m=`${p} ${d.name};`;g!==null&&(m=F_[g]+" "+m),h.push(" "+m)}i[c]=h}}l=!0}if(!l){const c=o.node.precision;c!==null&&(a=F_[c]+" "+a),a="uniform "+a,n.push(a)}}let s="";for(const o in i){const a=i[o];s+=this._getGLSLUniformStruct(o,a.join(` `))+` `}return s+=n.join(` `),s}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==Sn){let n=e;e.isInterleavedBufferAttribute&&(n=e.data);const i=n.array;i instanceof Uint32Array||i instanceof Int32Array||(t=t.slice(1))}return t}getAttributes(e){let t="";if(e==="vertex"||e==="compute"){const n=this.getAttributesArray();let i=0;for(const s of n)t+=`layout( location = ${i++} ) in ${s.type} ${s.name}; `}return t}getStructMembers(e){const t=[];for(const n of e.members)t.push(` ${n.type} ${n.name};`);return t.join(` `)}getStructs(e){const t=[],n=this.structs[e],i=[];for(const s of n)if(s.output)for(const o of s.members)i.push(`layout( location = ${o.index} ) out ${o.type} ${o.name};`);else{let o="struct "+s.name+` { `;o+=this.getStructMembers(s),o+=` }; `,t.push(o)}return i.length===0&&i.push("layout( location = 0 ) out vec4 fragColor;"),` `+i.join(` `)+` `+t.join(` `)}getVaryings(e){let t="";const n=this.varyings;if(e==="vertex"||e==="compute")for(const i of n){e==="compute"&&(i.needsInterpolation=!0);const s=this.getType(i.type);if(i.needsInterpolation)if(i.interpolationType){const o=B_[i.interpolationType]||i.interpolationType,a=O_[i.interpolationSampling]||"";t+=`${o} ${a} out ${s} ${i.name}; `}else{const o=s.includes("int")||s.includes("uv")||s.includes("iv")?"flat ":"";t+=`${o}out ${s} ${i.name}; `}else t+=`${s} ${i.name}; `}else if(e==="fragment"){for(const i of n)if(i.needsInterpolation){const s=this.getType(i.type);if(i.interpolationType){const o=B_[i.interpolationType]||i.interpolationType,a=O_[i.interpolationSampling]||"";t+=`${o} ${a} in ${s} ${i.name}; `}else{const o=s.includes("int")||s.includes("uv")||s.includes("iv")?"flat ":"";t+=`${o}in ${s} ${i.name}; `}}}for(const i of this.builtins[e])t+=`${i}; `;return t}getVertexIndex(){return"uint( gl_VertexID )"}getInstanceIndex(){return"uint( gl_InstanceID )"}getInvocationLocalIndex(){return`uint( gl_InstanceID ) % ${this.object.workgroupSize.reduce((n,i)=>n*i,1)}u`}getSubgroupSize(){ne("GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node")}getInvocationSubgroupIndex(){ne("GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node")}getSubgroupIndex(){ne("GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node")}getDrawIndex(){return this.renderer.backend.extensions.has("WEBGL_multi_draw")?"uint( gl_DrawID )":"nodeUniformDrawId"}getFrontFacing(){return"gl_FrontFacing"}getFragCoord(){return"gl_FragCoord.xy"}getFragDepth(){return"gl_FragDepth"}enableExtension(e,t,n=this.shaderStage){const i=this.extensions[n]||(this.extensions[n]=new Map);i.has(e)===!1&&i.set(e,{name:e,behavior:t})}getExtensions(e){const t=[];if(e==="vertex"){const i=this.renderer.backend.extensions;this.object.isBatchedMesh&&i.has("WEBGL_multi_draw")&&this.enableExtension("GL_ANGLE_multi_draw","require",e)}const n=this.extensions[e];if(n!==void 0)for(const{name:i,behavior:s}of n.values())t.push(`#extension ${i} : ${s}`);return t.join(` `)}getClipDistance(){return"gl_ClipDistance"}isAvailable(e){let t=I_[e];if(t===void 0){let n;switch(t=!1,e){case"float32Filterable":n="OES_texture_float_linear";break;case"clipDistance":n="WEBGL_clip_cull_distance";break}if(n!==void 0){const i=this.renderer.backend.extensions;i.has(n)&&(i.get(n),t=!0)}I_[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+=` // flow -> ${c} `),n+=`${l.code} `,a===s&&t!=="compute"&&(n+=`// result `,t==="vertex"?(n+="gl_Position = ",n+=`${l.result};`):t==="fragment"&&(a.outputNode.isOutputStructNode||(n+="fragColor = ",n+=`${l.result};`)))}const o=e[t];if(o.extensions=this.getExtensions(t),o.uniforms=this.getUniforms(t),o.attributes=this.getAttributes(t),o.varyings=this.getVaryings(t),o.vars=this.getVars(t,!0),o.structs=this.getStructs(t),o.codes=this.getCodes(t),o.transforms=this.getTransforms(t),o.flow=n,t==="vertex"){const a=this.renderer.backend.extensions;this.object.isBatchedMesh&&a.has("WEBGL_multi_draw")===!1&&(o.uniforms+=` uniform uint nodeUniformDrawId; `)}}this.material!==null?(this.vertexShader=this._getGLSLVertexCode(e.vertex),this.fragmentShader=this._getGLSLFragmentCode(e.fragment)):this.computeShader=this._getGLSLVertexCode(e.compute)}getUniformFromNode(e,t,n,i=null){const s=super.getUniformFromNode(e,t,n,i),o=this.getDataFromNode(e,n,this.globalCache);let a=o.uniformGPU;if(a===void 0){const l=e.groupNode,c=l.name,u=this.getBindGroupArray(c,n);if(t==="texture")a=new mh(s.name,s.node,l),u.push(a);else if(t==="cubeTexture"||t==="cubeDepthTexture")a=new cv(s.name,s.node,l),u.push(a);else if(t==="texture3D")a=new wf(s.name,s.node,l),u.push(a);else if(t==="buffer"){s.name=`buffer${e.id}`;const h=this.getSharedDataFromNode(e);let d=h.buffer;d===void 0&&(e.name=`NodeBuffer_${e.id}`,d=new ov(e,l),d.name=e.name,h.buffer=d),u.push(d),a=d}else{let h=this.uniformGroups[c];h===void 0?(h=new av(c,l),this.uniformGroups[c]=h,u.push(h)):u.indexOf(h)===-1&&u.push(h),a=this.getNodeUniform(s,t);const d=a.name;h.uniforms.some(p=>p.name===d)||h.addUniform(a)}o.uniformGPU=a}return s}}let Vd=null,Ho=null;class uv{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={[ps.RENDER]:null,[ps.COMPUTE]:null},this.trackTimestamp=e.trackTimestamp===!0}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 i;e.isComputeNode===!0?i="c:"+this.renderer.info.compute.frameCalls:i="r:"+this.renderer.info.render.frameCalls,t.timestampUID=i+":"+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:")?ps.COMPUTE:ps.RENDER;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){Yt("WebGPURenderer: Timestamp tracking is disabled.");return}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(){}getDrawingBufferSize(){return Vd=Vd||new de,this.renderer.getDrawingBufferSize(Vd)}setScissorTest(){}getClearColor(){const e=this.renderer;return Ho=Ho||new zp,e.getClearColor(Ho),Ho.getRGB(Ho),Ho}getDomElement(){let e=this.domElement;return e===null&&(e=this.parameters.canvas!==void 0?this.parameters.canvas:Sx(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${po} webgpu`),this.domElement=e),e}hasCompatibility(){return!1}initRenderTarget(){}set(e,t){this.data.set(e,t)}get(e){let t=this.data.get(e);return t===void 0&&(t={},this.data.set(e,t)),t}has(e){return this.data.has(e)}delete(e){this.data.delete(e)}deleteBindGroupData(){}dispose(){}}let nI=0;class iI{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[this.activeBufferIndex^1]}switchBuffers(){this.activeBufferIndex^=1}}class sI{constructor(e){this.backend=e}createAttribute(e,t){const n=this.backend,{gl:i}=n,s=e.array,o=e.usage||i.STATIC_DRAW,a=e.isInterleavedBufferAttribute?e.data:e,l=n.get(a);let c=l.bufferGPU;c===void 0&&(c=this._createBuffer(i,t,s,o),l.bufferGPU=c,l.bufferType=t,l.version=a.version);let u;if(s instanceof Float32Array)u=i.FLOAT;else if(typeof Float16Array<"u"&&s instanceof Float16Array)u=i.HALF_FLOAT;else if(s instanceof Uint16Array)e.isFloat16BufferAttribute?u=i.HALF_FLOAT:u=i.UNSIGNED_SHORT;else if(s instanceof Int16Array)u=i.SHORT;else if(s instanceof Uint32Array)u=i.UNSIGNED_INT;else if(s instanceof Int32Array)u=i.INT;else if(s instanceof Int8Array)u=i.BYTE;else if(s instanceof Uint8Array)u=i.UNSIGNED_BYTE;else if(s instanceof Uint8ClampedArray)u=i.UNSIGNED_BYTE;else throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+s);let h={bufferGPU:c,bufferType:t,type:u,byteLength:s.byteLength,bytesPerElement:s.BYTES_PER_ELEMENT,version:e.version,pbo:e.pbo,isInteger:u===i.INT||u===i.UNSIGNED_INT||e.gpuType===Sn,id:nI++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const d=this._createBuffer(i,t,s,o);h=new iI(h,d)}n.set(e,h)}updateAttribute(e){const t=this.backend,{gl:n}=t,i=e.array,s=e.isInterleavedBufferAttribute?e.data:e,o=t.get(s),a=o.bufferType,l=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(n.bindBuffer(a,o.bufferGPU),l.length===0)n.bufferSubData(a,0,i);else{for(let c=0,u=l.length;c{t.buffer=null,t._mapped=!1,t.removeEventListener("release",d),t.removeEventListener("dispose",d)};t.addEventListener("release",d),t.addEventListener("dispose",d),h=new Uint8Array(new ArrayBuffer(u)),t.buffer=h.buffer}else h=new Uint8Array(t);return o.bindBuffer(o.COPY_READ_BUFFER,c),o.getBufferSubData(o.COPY_READ_BUFFER,n,h),o.bindBuffer(o.COPY_READ_BUFFER,null),o.bindBuffer(o.COPY_WRITE_BUFFER,null),t&&t.isReadbackBuffer?t:h.buffer}_createBuffer(e,t,n,i){const s=e.createBuffer();return e.bindBuffer(t,s),e.bufferData(t,n,i),e.bindBuffer(t,null),s}}let ml,Ds;class rI{constructor(e){this.backend=e,this.gl=this.backend.gl,this.enabled={},this.parameters={},this.currentFlipSided=null,this.currentCullFace=null,this.currentProgram=null,this.currentBlendingEnabled=!1,this.currentBlending=null,this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentPremultipledAlpha=null,this.currentPolygonOffsetFactor=null,this.currentPolygonOffsetUnits=null,this.currentColorMask=null,this.currentDepthReversed=!1,this.currentDepthFunc=null,this.currentDepthMask=null,this.currentStencilFunc=null,this.currentStencilRef=null,this.currentStencilFuncMask=null,this.currentStencilFail=null,this.currentStencilZFail=null,this.currentStencilZPass=null,this.currentStencilMask=null,this.currentLineWidth=null,this.currentClippingPlanes=0,this.currentVAO=null,this.currentIndex=null,this.currentBoundFramebuffers={},this.currentDrawbuffers=new WeakMap,this.maxTextures=this.gl.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.currentTextureSlot=null,this.currentBoundTextures={},this.currentBoundBufferBases={},this._init()}_init(){const e=this.gl;ml={[Wn]:e.FUNC_ADD,[Lf]:e.FUNC_SUBTRACT,[Uf]:e.FUNC_REVERSE_SUBTRACT},Ds={[Us]:e.ZERO,[Ff]:e.ONE,[If]:e.SRC_COLOR,[Ul]:e.SRC_ALPHA,[zf]:e.SRC_ALPHA_SATURATE,[Gf]:e.DST_COLOR,[Of]:e.DST_ALPHA,[Bf]:e.ONE_MINUS_SRC_COLOR,[Fl]:e.ONE_MINUS_SRC_ALPHA,[Vf]:e.ONE_MINUS_DST_COLOR,[kf]:e.ONE_MINUS_DST_ALPHA};const t=e.getParameter(e.SCISSOR_BOX),n=e.getParameter(e.VIEWPORT);this.currentScissor=new tt().fromArray(t),this.currentViewport=new tt().fromArray(n),this._tempVec4=new tt}enable(e){const{enabled:t}=this;t[e]!==!0&&(this.gl.enable(e),t[e]=!0)}disable(e){const{enabled:t}=this;t[e]!==!1&&(this.gl.disable(e),t[e]=!1)}setFlipSided(e){if(this.currentFlipSided!==e){const{gl:t}=this;e?t.frontFace(t.CW):t.frontFace(t.CCW),this.currentFlipSided=e}}setCullFace(e){const{gl:t}=this;e!==cx?(this.enable(t.CULL_FACE),e!==this.currentCullFace&&(e===Qd?t.cullFace(t.BACK):e===ux?t.cullFace(t.FRONT):t.cullFace(t.FRONT_AND_BACK))):this.disable(t.CULL_FACE),this.currentCullFace=e}setLineWidth(e){const{currentLineWidth:t,gl:n}=this;e!==t&&(n.lineWidth(e),this.currentLineWidth=e)}setMRTBlending(e,t,n){const i=this.gl,s=this.backend.drawBuffersIndexedExt;if(!s){Yt("WebGPURenderer: Multiple Render Targets (MRT) blending configuration is not fully supported in compatibility mode. The material blending will be used for all render targets.");return}for(let o=0;o0?this.enable(i.SAMPLE_ALPHA_TO_COVERAGE):this.disable(i.SAMPLE_ALPHA_TO_COVERAGE),n>0&&this.currentClippingPlanes!==n)for(let l=0;l<8;l++)l{function s(){const o=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(o===e.WAIT_FAILED){e.deleteSync(t),i();return}if(o===e.TIMEOUT_EXPIRED){requestAnimationFrame(s);return}e.deleteSync(t),n()}s()})}}let G_=!1,hu,zd,V_;class aI{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},this._srcFramebuffer=null,this._dstFramebuffer=null,G_===!1&&(this._init(),G_=!0)}_init(){const e=this.gl;hu={[ro]:e.REPEAT,[ai]:e.CLAMP_TO_EDGE,[oo]:e.MIRRORED_REPEAT},zd={[bt]:e.NEAREST,[Kf]:e.NEAREST_MIPMAP_NEAREST,[Gs]:e.NEAREST_MIPMAP_LINEAR,[Ut]:e.LINEAR,[Qo]:e.LINEAR_MIPMAP_NEAREST,[li]:e.LINEAR_MIPMAP_LINEAR},V_={[Zf]:e.NEVER,[ep]:e.ALWAYS,[Ku]:e.LESS,[Dr]:e.LEQUAL,[Qf]:e.EQUAL,[$s]:e.GEQUAL,[jl]:e.GREATER,[Jf]:e.NOTEQUAL}}getGLTextureType(e){const{gl:t}=this;let n;return e.isCubeTexture===!0?n=t.TEXTURE_CUBE_MAP:e.isArrayTexture===!0||e.isDataArrayTexture===!0||e.isCompressedArrayTexture===!0?n=t.TEXTURE_2D_ARRAY:e.isData3DTexture===!0?n=t.TEXTURE_3D:n=t.TEXTURE_2D,n}getInternalFormat(e,t,n,i,s,o=!1){const{gl:a,extensions:l}=this;if(e!==null){if(a[e]!==void 0)return a[e];ee("WebGLBackend: Attempt to use non-existing WebGL internal format '"+e+"'")}let c=null;i&&(c=l.get("EXT_texture_norm16"),c||ee("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let u=t;if(t===a.RED&&(n===a.FLOAT&&(u=a.R32F),n===a.HALF_FLOAT&&(u=a.R16F),n===a.UNSIGNED_BYTE&&(u=a.R8),n===a.BYTE&&(u=a.R8_SNORM),n===a.UNSIGNED_SHORT&&c&&(u=c.R16_EXT),n===a.SHORT&&c&&(u=c.R16_SNORM_EXT)),t===a.RED_INTEGER&&(n===a.UNSIGNED_BYTE&&(u=a.R8UI),n===a.UNSIGNED_SHORT&&(u=a.R16UI),n===a.UNSIGNED_INT&&(u=a.R32UI),n===a.BYTE&&(u=a.R8I),n===a.SHORT&&(u=a.R16I),n===a.INT&&(u=a.R32I)),t===a.RG&&(n===a.FLOAT&&(u=a.RG32F),n===a.HALF_FLOAT&&(u=a.RG16F),n===a.UNSIGNED_BYTE&&(u=a.RG8),n===a.BYTE&&(u=a.RG8_SNORM),n===a.UNSIGNED_SHORT&&c&&(u=c.RG16_EXT),n===a.SHORT&&c&&(u=c.RG16_SNORM_EXT)),t===a.RG_INTEGER&&(n===a.UNSIGNED_BYTE&&(u=a.RG8UI),n===a.UNSIGNED_SHORT&&(u=a.RG16UI),n===a.UNSIGNED_INT&&(u=a.RG32UI),n===a.BYTE&&(u=a.RG8I),n===a.SHORT&&(u=a.RG16I),n===a.INT&&(u=a.RG32I)),t===a.RGB){const h=o?Na:Xe.getTransfer(s);n===a.FLOAT&&(u=a.RGB32F),n===a.HALF_FLOAT&&(u=a.RGB16F),n===a.UNSIGNED_BYTE&&(u=h===Ee?a.SRGB8:a.RGB8),n===a.BYTE&&(u=a.RGB8_SNORM),n===a.UNSIGNED_SHORT&&c&&(u=c.RGB16_EXT),n===a.SHORT&&c&&(u=c.RGB16_SNORM_EXT),n===a.UNSIGNED_SHORT_5_6_5&&(u=a.RGB565),n===a.UNSIGNED_SHORT_5_5_5_1&&(u=a.RGB5_A1),n===a.UNSIGNED_SHORT_4_4_4_4&&(u=a.RGB4),n===a.UNSIGNED_INT_5_9_9_9_REV&&(u=a.RGB9_E5),n===a.UNSIGNED_INT_10F_11F_11F_REV&&(u=a.R11F_G11F_B10F)}if(t===a.RGB_INTEGER&&(n===a.UNSIGNED_BYTE&&(u=a.RGB8UI),n===a.UNSIGNED_SHORT&&(u=a.RGB16UI),n===a.UNSIGNED_INT&&(u=a.RGB32UI),n===a.BYTE&&(u=a.RGB8I),n===a.SHORT&&(u=a.RGB16I),n===a.INT&&(u=a.RGB32I)),t===a.RGBA){const h=o?Na:Xe.getTransfer(s);n===a.FLOAT&&(u=a.RGBA32F),n===a.HALF_FLOAT&&(u=a.RGBA16F),n===a.UNSIGNED_BYTE&&(u=h===Ee?a.SRGB8_ALPHA8:a.RGBA8),n===a.BYTE&&(u=a.RGBA8_SNORM),n===a.UNSIGNED_SHORT&&c&&(u=c.RGBA16_EXT),n===a.SHORT&&c&&(u=c.RGBA16_SNORM_EXT),n===a.UNSIGNED_SHORT_4_4_4_4&&(u=a.RGBA4),n===a.UNSIGNED_SHORT_5_5_5_1&&(u=a.RGB5_A1)}return t===a.RGBA_INTEGER&&(n===a.UNSIGNED_BYTE&&(u=a.RGBA8UI),n===a.UNSIGNED_SHORT&&(u=a.RGBA16UI),n===a.UNSIGNED_INT&&(u=a.RGBA32UI),n===a.BYTE&&(u=a.RGBA8I),n===a.SHORT&&(u=a.RGBA16I),n===a.INT&&(u=a.RGBA32I)),t===a.DEPTH_COMPONENT&&(n===a.UNSIGNED_SHORT&&(u=a.DEPTH_COMPONENT16),n===a.UNSIGNED_INT&&(u=a.DEPTH_COMPONENT24),n===a.FLOAT&&(u=a.DEPTH_COMPONENT32F)),t===a.DEPTH_STENCIL&&n===a.UNSIGNED_INT_24_8&&(u=a.DEPTH24_STENCIL8),(u===a.R16F||u===a.R32F||u===a.RG16F||u===a.RG32F||u===a.RGBA16F||u===a.RGBA32F)&&l.get("EXT_color_buffer_float"),u}setTextureParameters(e,t){const{gl:n,extensions:i,backend:s}=this,{state:o}=this.backend,a=Xe.getPrimaries(Xe.workingColorSpace),l=t.colorSpace===ri?null:Xe.getPrimaries(t.colorSpace),c=t.colorSpace===ri||a===l?n.NONE:n.BROWSER_DEFAULT_WEBGL;o.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,t.flipY),o.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),o.pixelStorei(n.UNPACK_ALIGNMENT,t.unpackAlignment),o.pixelStorei(n.UNPACK_COLORSPACE_CONVERSION_WEBGL,c),n.texParameteri(e,n.TEXTURE_WRAP_S,hu[t.wrapS]),n.texParameteri(e,n.TEXTURE_WRAP_T,hu[t.wrapT]),(e===n.TEXTURE_3D||e===n.TEXTURE_2D_ARRAY)&&(t.isArrayTexture||n.texParameteri(e,n.TEXTURE_WRAP_R,hu[t.wrapR])),n.texParameteri(e,n.TEXTURE_MAG_FILTER,zd[t.magFilter]);const u=t.mipmaps!==void 0&&t.mipmaps.length>0,h=t.minFilter===Ut&&u?li:t.minFilter;if(n.texParameteri(e,n.TEXTURE_MIN_FILTER,zd[h]),t.compareFunction&&(n.texParameteri(e,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE),n.texParameteri(e,n.TEXTURE_COMPARE_FUNC,V_[t.compareFunction])),i.has("EXT_texture_filter_anisotropic")===!0){if(t.magFilter===bt||t.minFilter!==Gs&&t.minFilter!==li||t.type===Zt&&i.has("OES_texture_float_linear")===!1)return;if(t.anisotropy>1){const d=i.get("EXT_texture_filter_anisotropic");n.texParameterf(e,d.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,s.capabilities.getMaxAnisotropy()))}}}createDefaultTexture(e){const{gl:t,backend:n,defaultTextures:i}=this,s=this.getGLTextureType(e);let o=i[s];o===void 0&&(o=t.createTexture(),n.state.bindTexture(s,o),t.texParameteri(s,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(s,t.TEXTURE_MAG_FILTER,t.NEAREST),i[s]=o),n.set(e,{textureGPU:o,glTextureType:s})}createTexture(e,t){const{gl:n,backend:i}=this,{levels:s,width:o,height:a,depth:l}=t,c=i.utils.convert(e.format,e.colorSpace),u=i.utils.convert(e.type),h=this.getInternalFormat(e.internalFormat,c,u,e.normalized,e.colorSpace,e.isVideoTexture),d=n.createTexture(),f=this.getGLTextureType(e);i.state.bindTexture(f,d),this.setTextureParameters(f,e),e.isArrayTexture||e.isDataArrayTexture||e.isCompressedArrayTexture?n.texStorage3D(n.TEXTURE_2D_ARRAY,s,h,o,a,l):e.isData3DTexture?n.texStorage3D(n.TEXTURE_3D,s,h,o,a,l):e.isVideoTexture||n.texStorage2D(f,s,h,o,a),i.set(e,{textureGPU:d,glTextureType:f,glFormat:c,glType:u,glInternalFormat:h})}copyBufferToTexture(e,t){const{gl:n,backend:i}=this,{state:s}=i,{textureGPU:o,glTextureType:a,glFormat:l,glType:c}=i.get(t),{width:u,height:h}=t.source.data;n.bindBuffer(n.PIXEL_UNPACK_BUFFER,e),i.state.bindTexture(a,o),s.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!1),s.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),n.texSubImage2D(a,0,0,0,u,h,l,c,0),n.bindBuffer(n.PIXEL_UNPACK_BUFFER,null),i.state.unbindTexture()}updateTexture(e,t){const{gl:n}=this,{width:i,height:s}=t,{textureGPU:o,glTextureType:a,glFormat:l,glType:c,glInternalFormat:u}=this.backend.get(e);if(!(e.isRenderTargetTexture||o===void 0))if(this.backend.state.bindTexture(a,o),this.setTextureParameters(a,e),e.isCompressedTexture){const h=e.mipmaps,d=t.image;for(let f=0;f0){const d=sf(h.width,h.height,e.format,e.type);for(const f of e.layerUpdates){const p=h.data.subarray(f*d/h.data.BYTES_PER_ELEMENT,(f+1)*d/h.data.BYTES_PER_ELEMENT);n.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,f,h.width,h.height,1,l,c,p)}e.clearLayerUpdates()}else n.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,0,h.width,h.height,h.depth,l,c,h.data)}else if(e.isData3DTexture){const h=t.image;n.texSubImage3D(n.TEXTURE_3D,0,0,0,0,h.width,h.height,h.depth,l,c,h.data)}else if(e.isVideoTexture)e.update(),n.texImage2D(a,0,u,l,c,t.image);else if(e.isHTMLTexture)typeof n.texElementImage2D=="function"&&n.texElementImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,t.image);else{const h=e.mipmaps;if(h.length>0)for(let d=0,f=h.length;d0,d=t.renderTarget?t.renderTarget.height:this.backend.getDrawingBufferSize().y;if(h){const f=a!==0||l!==0;let p,g;if(e.isDepthTexture===!0?(p=i.DEPTH_BUFFER_BIT,g=i.DEPTH_ATTACHMENT,t.stencil&&(p|=i.STENCIL_BUFFER_BIT)):(p=i.COLOR_BUFFER_BIT,g=i.COLOR_ATTACHMENT0),f){const m=this.backend.get(t.renderTarget),_=m.framebuffers[t.getCacheKey()],x=m.msaaFrameBuffer;s.bindFramebuffer(i.DRAW_FRAMEBUFFER,_),s.bindFramebuffer(i.READ_FRAMEBUFFER,x);const v=d-l-u;i.blitFramebuffer(a,v,a+c,v+u,a,v,a+c,v+u,p,i.NEAREST),s.bindFramebuffer(i.READ_FRAMEBUFFER,_),s.bindTexture(i.TEXTURE_2D,o),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,a,v,c,u),s.unbindTexture()}else{const m=i.createFramebuffer();s.bindFramebuffer(i.DRAW_FRAMEBUFFER,m),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,g,i.TEXTURE_2D,o,0),i.blitFramebuffer(0,0,c,u,0,0,c,u,p,i.NEAREST),i.deleteFramebuffer(m)}}else s.bindTexture(i.TEXTURE_2D,o),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,a,d-u-l,c,u),s.unbindTexture();e.generateMipmaps&&this.generateMipmaps(e),this.backend._setFramebuffer(t)}setupRenderBufferStorage(e,t,n,i=!1){const{gl:s}=this,o=t.renderTarget,{depthTexture:a,depthBuffer:l,stencilBuffer:c,width:u,height:h}=o;if(s.bindRenderbuffer(s.RENDERBUFFER,e),l&&!c){let d=s.DEPTH_COMPONENT24;i===!0?this.extensions.get("WEBGL_multisampled_render_to_texture").renderbufferStorageMultisampleEXT(s.RENDERBUFFER,o.samples,d,u,h):n>0?(a&&a.isDepthTexture&&a.type===s.FLOAT&&(d=s.DEPTH_COMPONENT32F),s.renderbufferStorageMultisample(s.RENDERBUFFER,n,d,u,h)):s.renderbufferStorage(s.RENDERBUFFER,d,u,h),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,e)}else l&&c&&(n>0?s.renderbufferStorageMultisample(s.RENDERBUFFER,n,s.DEPTH24_STENCIL8,u,h):s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_STENCIL,u,h),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_STENCIL_ATTACHMENT,s.RENDERBUFFER,e));s.bindRenderbuffer(s.RENDERBUFFER,null)}async copyTextureToBuffer(e,t,n,i,s,o){const{backend:a,gl:l}=this,{textureGPU:c,glFormat:u,glType:h}=this.backend.get(e),d=l.createFramebuffer();a.state.bindFramebuffer(l.READ_FRAMEBUFFER,d);const f=e.isCubeTexture?l.TEXTURE_CUBE_MAP_POSITIVE_X+o:l.TEXTURE_2D;l.framebufferTexture2D(l.READ_FRAMEBUFFER,l.COLOR_ATTACHMENT0,f,c,0);const p=this._getTypedArrayType(h),g=this._getBytesPerTexel(h,u),_=i*s*g,x=l.createBuffer();l.bindBuffer(l.PIXEL_PACK_BUFFER,x),l.bufferData(l.PIXEL_PACK_BUFFER,_,l.STREAM_READ),l.readPixels(t,n,i,s,u,h,0),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),await a.utils._clientWaitAsync();const v=new p(_/p.BYTES_PER_ELEMENT);return l.bindBuffer(l.PIXEL_PACK_BUFFER,x),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,v),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),a.state.bindFramebuffer(l.READ_FRAMEBUFFER,null),l.deleteFramebuffer(d),v}_getTypedArrayType(e){const{gl:t}=this;if(e===t.UNSIGNED_BYTE)return Uint8Array;if(e===t.UNSIGNED_SHORT_4_4_4_4||e===t.UNSIGNED_SHORT_5_5_5_1||e===t.UNSIGNED_SHORT_5_6_5||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 i=0;if(e===n.UNSIGNED_BYTE&&(i=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)&&(i=2),(e===n.UNSIGNED_INT||e===n.FLOAT)&&(i=4),t===n.RGBA)return i*4;if(t===n.RGB)return i*3;if(t===n.ALPHA)return i}dispose(){const{gl:e}=this;this._srcFramebuffer!==null&&e.deleteFramebuffer(this._srcFramebuffer),this._dstFramebuffer!==null&&e.deleteFramebuffer(this._dstFramebuffer)}}function du(r){return r.isDataTexture?r.image.data:typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&r instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&r instanceof ImageBitmap||typeof OffscreenCanvas<"u"&&r instanceof OffscreenCanvas?r:r.data}class lI{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 t===void 0&&(t=this.gl.getExtension(e),this.extensions[e]=t),t}has(e){return this.availableExtensions.includes(e)}}class cI{constructor(e){this.backend=e,this.maxAnisotropy=null,this.maxUniformBlockSize=null}getMaxAnisotropy(){if(this.maxAnisotropy!==null)return this.maxAnisotropy;const e=this.backend.gl,t=this.backend.extensions;if(t.has("EXT_texture_filter_anisotropic")===!0){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}getUniformBufferLimit(){if(this.maxUniformBlockSize!==null)return this.maxUniformBlockSize;const e=this.backend.gl;return this.maxUniformBlockSize=e.getParameter(e.MAX_UNIFORM_BLOCK_SIZE),this.maxUniformBlockSize}}const z_={WEBGL_multi_draw:"WEBGL_multi_draw",WEBGL_compressed_texture_astc:"texture-compression-astc",WEBGL_compressed_texture_etc:"texture-compression-etc2",WEBGL_compressed_texture_etc1:"texture-compression-etc1",WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBGL_compressed_texture_s3tc:"texture-compression-s3tc",EXT_texture_compression_bptc:"texture-compression-bc",EXT_disjoint_timer_query_webgl2:"timestamp-query",OVR_multiview2:"OVR_multiview2"};class uI{constructor(e){this.gl=e.gl,this.extensions=e.extensions,this.info=e.renderer.info,this.mode=null,this.index=0,this.type=null,this.object=null}render(e,t){const{gl:n,mode:i,object:s,type:o,info:a,index:l}=this;l!==0?n.drawElements(i,t,o,e):n.drawArrays(i,e,t),a.update(s,t,1)}renderInstances(e,t,n){const{gl:i,mode:s,type:o,index:a,object:l,info:c}=this;n!==0&&(a!==0?i.drawElementsInstanced(s,t,o,e,n):i.drawArraysInstanced(s,e,t,n),c.update(l,t,n))}renderMultiDraw(e,t,n){const{extensions:i,mode:s,object:o,info:a}=this;if(n===0)return;const l=i.get("WEBGL_multi_draw");if(l===null)for(let c=0;cthis.maxQueries)return Yt(`WebGLTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryStates.set(t,"inactive"),this.queryOffsets.set(e,t),t}beginQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e);if(t==null||this.activeQuery!==null)return;const n=this.queries[t];if(n)try{this.queryStates.get(t)==="inactive"&&(this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,n),this.activeQuery=t,this.queryStates.set(t,"started"))}catch(i){ne("Error in beginQuery:",i),this.activeQuery=null,this.queryStates.set(t,"inactive")}}endQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e);if(t!=null&&this.activeQuery===t)try{this.gl.endQuery(this.ext.TIME_ELAPSED_EXT),this.queryStates.set(t,"ended"),this.activeQuery=null}catch(n){ne("Error in endQuery:",n),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[s,o]of this.queryOffsets)if(this.queryStates.get(o)==="ended"){const l=this.queries[o];e.set(s,this.resolveQuery(l))}if(e.size===0)return this.lastValue;const t={},n=[];for(const[s,o]of e){const a=s.match(/^(.*):f(\d+)$/),l=parseInt(a[2]);n.includes(l)===!1&&n.push(l),t[l]===void 0&&(t[l]=0);const c=await o;this.timestamps.set(s,c),t[l]+=c}const i=t[n[n.length-1]];return this.lastValue=i,this.frames=n,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,i}catch(e){return ne("Error resolving queries:",e),this.lastValue}finally{this.pendingResolve=!1}}async resolveQuery(e){return new Promise(t=>{if(this.isDisposed){t(this.lastValue);return}let n,i=!1;const s=()=>{n&&(clearTimeout(n),n=null)},o=l=>{i||(i=!0,s(),t(l))},a=()=>{if(this.isDisposed){o(this.lastValue);return}try{if(this.gl.getParameter(this.ext.GPU_DISJOINT_EXT)){o(this.lastValue);return}if(!this.gl.getQueryParameter(e,this.gl.QUERY_RESULT_AVAILABLE)){n=setTimeout(a,1);return}const u=this.gl.getQueryParameter(e,this.gl.QUERY_RESULT);t(Number(u)/1e6)}catch(l){ne("Error checking query:",l),t(this.lastValue)}};a()})}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 H_ extends uv{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=typeof navigator>"u"?!1:/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},i=t.context!==void 0?t.context:e.domElement.getContext("webgl2",n);function s(o){o.preventDefault();const a={api:"WebGL",message:o.statusMessage||"Unknown reason",reason:null,originalEvent:o};e.onDeviceLost(a)}this._onContextLost=s,e.domElement.addEventListener("webglcontextlost",s,!1),this.gl=i,this.extensions=new lI(this),this.capabilities=new cI(this),this.attributeUtils=new sI(this),this.textureUtils=new aI(this),this.bufferRenderer=new uI(this),this.state=new rI(this),this.utils=new oI(this),this.extensions.get("EXT_color_buffer_float"),this.extensions.get("WEBGL_clip_cull_distance"),this.extensions.get("OES_texture_float_linear"),this.extensions.get("EXT_color_buffer_half_float"),this.extensions.get("WEBGL_multisampled_render_to_texture"),this.extensions.get("WEBGL_render_shared_exponent"),this.extensions.get("WEBGL_multi_draw"),this.extensions.get("OVR_multiview2"),this.extensions.get("EXT_clip_control"),this.disjoint=this.extensions.get("EXT_disjoint_timer_query_webgl2"),this.parallel=this.extensions.get("KHR_parallel_shader_compile"),this.drawBuffersIndexedExt=this.extensions.get("OES_draw_buffers_indexed"),t.reversedDepthBuffer&&(this.extensions.has("EXT_clip_control")?e.reversedDepthBuffer=!0:(ee("WebGPURenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer."),e.reversedDepthBuffer=!1)),e.reversedDepthBuffer&&this.state.setReversedDepth(!0)}get coordinateSystem(){return ti}async getArrayBufferAsync(e,t=null,n=0,i=-1){return await this.attributeUtils.getArrayBufferAsync(e,t,n,i)}async makeXRCompatible(){this.gl.getContextAttributes().xrCompatible!==!0&&await this.gl.makeXRCompatible()}setXRTarget(e){this._xrFramebuffer=e}setXRRenderTargetTextures(e,t,n=null){const i=this.gl;if(this.set(e.texture,{textureGPU:t,glInternalFormat:i.RGBA8}),n!==null){const s=e.stencilBuffer?i.DEPTH24_STENCIL8:i.DEPTH_COMPONENT24;this.set(e.depthTexture,{textureGPU:n,glInternalFormat:s}),this.extensions.has("WEBGL_multisampled_render_to_texture")===!0&&e._autoAllocateDepthBuffer===!0&&e.multiview===!1&&ee("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 hI(this.gl,e,2048));const n=this.timestampQueryPool[e];n.allocateQueriesForContext(t)!==null&&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:s,height:o}=this.getDrawingBufferSize();t.viewport(0,0,s,o)}if(e.scissor)this.updateScissor(e);else{const{width:s,height:o}=this.getDrawingBufferSize();t.scissor(0,0,s,o)}this.initTimestampQuery(ps.RENDER,this.getTimestampUID(e)),n.previousContext=this._currentContext,this._currentContext=e,this._setFramebuffer(e),this.clear(e.clearColor,e.clearDepth,e.clearStencil,e,!1);const i=e.occlusionQueryCount;i>0&&(n.currentOcclusionQueries=n.occlusionQueries,n.currentOcclusionQueryObjects=n.occlusionQueryObjects,n.lastOcclusionObject=null,n.occlusionQueries=new Array(i),n.occlusionQueryObjects=new Array(i),n.occlusionQueryIndex=0)}finishRender(e){const{gl:t,state:n}=this,i=this.get(e),s=i.previousContext;n.resetVertexState();const o=e.occlusionQueryCount;o>0&&(o>i.occlusionQueryIndex&&t.endQuery(t.ANY_SAMPLES_PASSED),this.resolveOccludedAsync(e));const a=e.textures;if(a!==null)for(let l=0;l{let l=0;for(let c=0;c1?t.renderInstances(n,i,s):t.render(n,i)}draw(e){const{object:t,pipeline:n,material:i,context:s,hardwareClippingPlanes:o}=e,{programGPU:a}=this.get(n),{gl:l,state:c}=this,u=this.get(s),h=e.getDrawParameters();if(h===null)return;this._bindUniforms(e.getBindings());const d=t.isMesh&&t.matrixWorld.determinant()<0;c.setMaterial(i,d,o),s.mrt!==null&&s.textures!==null&&c.setMRTBlending(s.textures,s.mrt,i),c.useProgram(a);const f=e.getAttributes(),p=this.get(f);let g=p.vaoGPU;if(g===void 0){const A=this._getVaoKey(f);g=this.vaoCache[A],g===void 0&&(g=this._createVao(f),this.vaoCache[A]=g,p.vaoGPU=g)}const m=e.getIndex(),_=m!==null?this.get(m).bufferGPU:null;c.setVertexState(g,_);const x=u.lastOcclusionObject;if(x!==t&&x!==void 0){if(x!==null&&x.occlusionTest===!0&&(l.endQuery(l.ANY_SAMPLES_PASSED),u.occlusionQueryIndex++),t.occlusionTest===!0){const A=l.createQuery();l.beginQuery(l.ANY_SAMPLES_PASSED,A),u.occlusionQueries[u.occlusionQueryIndex]=A,u.occlusionQueryObjects[u.occlusionQueryIndex]=t}u.lastOcclusionObject=t}const v=this.bufferRenderer;t.isPoints?v.mode=l.POINTS:t.isLineSegments?v.mode=l.LINES:t.isLine?v.mode=l.LINE_STRIP:t.isLineLoop?v.mode=l.LINE_LOOP:i.wireframe===!0?(c.setLineWidth(i.wireframeLinewidth*this.renderer.getPixelRatio()),v.mode=l.LINES):v.mode=l.TRIANGLES;const{vertexCount:S,instanceCount:E}=h;let{firstVertex:T}=h;if(v.object=t,m!==null){T*=m.array.BYTES_PER_ELEMENT;const A=this.get(m);v.index=m.count,v.type=A.type}else v.index=0;if(e.camera.isArrayCamera===!0&&e.camera.cameras.length>0&&e.camera.isMultiViewCamera===!1){const A=this.get(e.camera),y=e.camera.cameras,R=e.getBindingGroup("cameraIndex").bindings[0];if(A.indexesGPU===void 0||A.indexesGPU.length!==y.length){const L=new Uint32Array([0,0,0,0]),B=[];for(let H=0,ie=y.length;H{const d=this.parallel,f=()=>{n.getProgramParameter(a,d.COMPLETION_STATUS_KHR)?(this._completeCompile(e,i),h()):requestAnimationFrame(f)};f()});t.push(u);return}this._completeCompile(e,i)}_handleSource(e,t){const n=e.split(` `),i=[],s=Math.max(t-6,0),o=Math.min(t+6,n.length);for(let a=s;a":" "} ${l}: ${n[a]}`)}return i.join(` `)}_getShaderErrors(e,t,n){const i=e.getShaderParameter(t,e.COMPILE_STATUS),o=(e.getShaderInfoLog(t)||"").trim();if(i&&o==="")return"";const a=/ERROR: 0:(\d+)/.exec(o);if(a){const l=parseInt(a[1]);return n.toUpperCase()+` `+o+` `+this._handleSource(e.getShaderSource(t),l)}else return o}_logProgramError(e,t,n){if(this.renderer.debug.checkShaderErrors){const i=this.gl,o=(i.getProgramInfoLog(e)||"").trim();if(i.getProgramParameter(e,i.LINK_STATUS)===!1)if(typeof this.renderer.debug.onShaderError=="function")this.renderer.debug.onShaderError(i,e,n,t);else{const a=this._getShaderErrors(i,n,"vertex"),l=this._getShaderErrors(i,t,"fragment");ne("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(e,i.VALIDATE_STATUS)+` Program Info Log: `+o+` `+a+` `+l)}else o!==""&&ee("WebGLProgram: Program Info Log:",o)}}_completeCompile(e,t){const{state:n,gl:i}=this,s=this.get(t),{programGPU:o,fragmentShader:a,vertexShader:l}=s;i.getProgramParameter(o,i.LINK_STATUS)===!1&&this._logProgramError(o,a,l),n.useProgram(o);const c=e.getBindings();this._setupBindings(c,o),this.set(t,{programGPU:o,pipeline:o})}createComputePipeline(e,t){const{state:n,gl:i}=this,s={stage:"fragment",code:`#version 300 es precision highp float; void main() {}`};this.createProgram(s);const{computeProgram:o}=e,a=i.createProgram(),l=this.get(s).shaderGPU,c=this.get(o).shaderGPU,u=o.transforms,h=[],d=[];for(let m=0;mz_[i]===e),n=this.extensions;for(let i=0;i1,f=s.isXRRenderTarget===!0,p=f===!0&&s._hasExternalTextures===!0;let g=o.msaaFrameBuffer,m=o.depthRenderbuffer;const _=this.extensions.get("WEBGL_multisampled_render_to_texture"),x=this.extensions.get("OVR_multiview2"),v=this._useMultisampledExtension(s),S=zy(e);let E;if(u?(o.cubeFramebuffers||(o.cubeFramebuffers={}),E=o.cubeFramebuffers[S]):f&&p===!1?E=this._xrFramebuffer:(o.framebuffers||(o.framebuffers={}),E=o.framebuffers[S]),E===void 0){E=t.createFramebuffer(),n.bindFramebuffer(t.FRAMEBUFFER,E);const T=e.textures,A=[];if(u){o.cubeFramebuffers[S]=E;const{textureGPU:R}=this.get(T[0]),P=this.renderer._activeCubeFace,N=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+P,R,N)}else{o.framebuffers[S]=E;for(let R=0;R0&&v===!1&&!s.multiview){if(g===void 0){const T=[];g=t.createFramebuffer(),n.bindFramebuffer(t.FRAMEBUFFER,g);const A=[],y=e.textures;for(let R=0;R0&&this._useMultisampledExtension(i)===!1){const o=s.framebuffers[e.getCacheKey()];let a=t.COLOR_BUFFER_BIT;i.resolveDepthBuffer&&(i.depthBuffer&&(a|=t.DEPTH_BUFFER_BIT),i.stencilBuffer&&i.resolveStencilBuffer&&(a|=t.STENCIL_BUFFER_BIT));const l=s.msaaFrameBuffer,c=s.msaaRenderbuffers,u=e.textures,h=u.length>1;if(n.bindFramebuffer(t.READ_FRAMEBUFFER,l),n.bindFramebuffer(t.DRAW_FRAMEBUFFER,o),h)for(let d=0;d0&&this.extensions.has("WEBGL_multisampled_render_to_texture")===!0&&e._autoAllocateDepthBuffer!==!1}dispose(){this.textureUtils!==null&&this.textureUtils.dispose();const e=this.extensions.get("WEBGL_lose_context");e&&e.loseContext(),this.renderer.domElement.removeEventListener("webglcontextlost",this._onContextLost)}}const fu={PointList:"point-list",LineList:"line-list",LineStrip:"line-strip",TriangleList:"triangle-list"},ms=typeof self<"u"&&self.GPUShaderStage?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},Dn={Never:"never",Less:"less",Equal:"equal",LessEqual:"less-equal",Greater:"greater",NotEqual:"not-equal",GreaterEqual:"greater-equal",Always:"always"},Zn={Store:"store"},At={Load:"load",Clear:"clear"},W_={CCW:"ccw",CW:"cw"},$_={None:"none",Back:"back"},Xu={Uint16:"uint16",Uint32:"uint32"},D={R8Unorm:"r8unorm",R8Snorm:"r8snorm",R8Uint:"r8uint",R8Sint:"r8sint",R16Uint:"r16uint",R16Sint:"r16sint",R16Float:"r16float",RG8Unorm:"rg8unorm",RG8Snorm:"rg8snorm",RG8Uint:"rg8uint",RG8Sint:"rg8sint",R16Unorm:"r16unorm",R16Snorm:"r16snorm",R32Uint:"r32uint",R32Sint:"r32sint",R32Float:"r32float",RG16Uint:"rg16uint",RG16Sint:"rg16sint",RG16Float:"rg16float",RGBA8Unorm:"rgba8unorm",RGBA8UnormSRGB:"rgba8unorm-srgb",RGBA8Snorm:"rgba8snorm",RGBA8Uint:"rgba8uint",RGBA8Sint:"rgba8sint",BGRA8Unorm:"bgra8unorm",BGRA8UnormSRGB:"bgra8unorm-srgb",RG16Unorm:"rg16unorm",RG16Snorm:"rg16snorm",RGB9E5UFloat:"rgb9e5ufloat",RGB10A2Unorm:"rgb10a2unorm",RG11B10UFloat:"rg11b10ufloat",RG32Uint:"rg32uint",RG32Sint:"rg32sint",RG32Float:"rg32float",RGBA16Uint:"rgba16uint",RGBA16Sint:"rgba16sint",RGBA16Float:"rgba16float",RGBA16Unorm:"rgba16unorm",RGBA16Snorm:"rgba16snorm",RGBA32Uint:"rgba32uint",RGBA32Sint:"rgba32sint",RGBA32Float:"rgba32float",Depth16Unorm:"depth16unorm",Depth24Plus:"depth24plus",Depth24PlusStencil8:"depth24plus-stencil8",Depth32Float:"depth32float",Depth32FloatStencil8:"depth32float-stencil8",BC1RGBAUnorm:"bc1-rgba-unorm",BC1RGBAUnormSRGB:"bc1-rgba-unorm-srgb",BC2RGBAUnorm:"bc2-rgba-unorm",BC2RGBAUnormSRGB:"bc2-rgba-unorm-srgb",BC3RGBAUnorm:"bc3-rgba-unorm",BC3RGBAUnormSRGB:"bc3-rgba-unorm-srgb",BC4RUnorm:"bc4-r-unorm",BC4RSnorm:"bc4-r-snorm",BC5RGUnorm:"bc5-rg-unorm",BC5RGSnorm:"bc5-rg-snorm",BC6HRGBUFloat:"bc6h-rgb-ufloat",BC6HRGBFloat:"bc6h-rgb-float",BC7RGBAUnorm:"bc7-rgba-unorm",BC7RGBAUnormSRGB:"bc7-rgba-unorm-srgb",ETC2RGB8Unorm:"etc2-rgb8unorm",ETC2RGB8UnormSRGB:"etc2-rgb8unorm-srgb",ETC2RGB8A1Unorm:"etc2-rgb8a1unorm",ETC2RGB8A1UnormSRGB:"etc2-rgb8a1unorm-srgb",ETC2RGBA8Unorm:"etc2-rgba8unorm",ETC2RGBA8UnormSRGB:"etc2-rgba8unorm-srgb",EACR11Unorm:"eac-r11unorm",EACR11Snorm:"eac-r11snorm",EACRG11Unorm:"eac-rg11unorm",EACRG11Snorm:"eac-rg11snorm",ASTC4x4Unorm:"astc-4x4-unorm",ASTC4x4UnormSRGB:"astc-4x4-unorm-srgb",ASTC5x4Unorm:"astc-5x4-unorm",ASTC5x4UnormSRGB:"astc-5x4-unorm-srgb",ASTC5x5Unorm:"astc-5x5-unorm",ASTC5x5UnormSRGB:"astc-5x5-unorm-srgb",ASTC6x5Unorm:"astc-6x5-unorm",ASTC6x5UnormSRGB:"astc-6x5-unorm-srgb",ASTC6x6Unorm:"astc-6x6-unorm",ASTC6x6UnormSRGB:"astc-6x6-unorm-srgb",ASTC8x5Unorm:"astc-8x5-unorm",ASTC8x5UnormSRGB:"astc-8x5-unorm-srgb",ASTC8x6Unorm:"astc-8x6-unorm",ASTC8x6UnormSRGB:"astc-8x6-unorm-srgb",ASTC8x8Unorm:"astc-8x8-unorm",ASTC8x8UnormSRGB:"astc-8x8-unorm-srgb",ASTC10x5Unorm:"astc-10x5-unorm",ASTC10x5UnormSRGB:"astc-10x5-unorm-srgb",ASTC10x6Unorm:"astc-10x6-unorm",ASTC10x6UnormSRGB:"astc-10x6-unorm-srgb",ASTC10x8Unorm:"astc-10x8-unorm",ASTC10x8UnormSRGB:"astc-10x8-unorm-srgb",ASTC10x10Unorm:"astc-10x10-unorm",ASTC10x10UnormSRGB:"astc-10x10-unorm-srgb",ASTC12x10Unorm:"astc-12x10-unorm",ASTC12x10UnormSRGB:"astc-12x10-unorm-srgb",ASTC12x12Unorm:"astc-12x12-unorm",ASTC12x12UnormSRGB:"astc-12x12-unorm-srgb"},Hd={ClampToEdge:"clamp-to-edge",Repeat:"repeat",MirrorRepeat:"mirror-repeat"},rs={Linear:"linear",Nearest:"nearest"},pt={Zero:"zero",One:"one",Src:"src",OneMinusSrc:"one-minus-src",SrcAlpha:"src-alpha",OneMinusSrcAlpha:"one-minus-src-alpha",Dst:"dst",OneMinusDst:"one-minus-dst",DstAlpha:"dst-alpha",OneMinusDstAlpha:"one-minus-dst-alpha",SrcAlphaSaturated:"src-alpha-saturated",Constant:"constant",OneMinusConstant:"one-minus-constant"},zr={Add:"add",Subtract:"subtract",ReverseSubtract:"reverse-subtract",Min:"min",Max:"max"},X_={None:0,All:15},ar={Keep:"keep",Zero:"zero",Replace:"replace",Invert:"invert",IncrementClamp:"increment-clamp",DecrementClamp:"decrement-clamp",IncrementWrap:"increment-wrap",DecrementWrap:"decrement-wrap"},Wd={Storage:"storage",ReadOnlyStorage:"read-only-storage"},$d={WriteOnly:"write-only",ReadOnly:"read-only",ReadWrite:"read-write"},q_={NonFiltering:"non-filtering",Comparison:"comparison"},Hr={Float:"float",UnfilterableFloat:"unfilterable-float",Depth:"depth",SInt:"sint",UInt:"uint"},j_={TwoD:"2d",ThreeD:"3d"},zn={TwoD:"2d",TwoDArray:"2d-array",Cube:"cube",ThreeD:"3d"},dI={All:"all"},pu={Vertex:"vertex",Instance:"instance"},qu={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"},Y_={"texture-compression-s3tc":"texture-compression-bc","texture-compression-etc1":"texture-compression-etc2"};class fI extends lv{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 pI extends sv{constructor(e,t){super(e,t?t.array:null),this._attribute=t,this.isStorageBuffer=!0}get attribute(){return this._attribute}}let mI=0;class gI extends pI{constructor(e,t){super("StorageBuffer_"+mI++,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:Ni.READ_WRITE,this.groupNode=t}get attribute(){return this.nodeUniform.value}get buffer(){return this.nodeUniform.value.array}}class _I extends Ur{constructor(e){super(),this.device=e;const t=` struct VarysStruct { @builtin( position ) Position: vec4f, @location( 0 ) vTex : vec2f, @location( 1 ) @interpolate(flat, either) vBaseArrayLayer: u32, }; @group( 0 ) @binding ( 2 ) var flipY: u32; @vertex fn mainVS( @builtin( vertex_index ) vertexIndex : u32, @builtin( instance_index ) instanceIndex : u32 ) -> VarysStruct { var Varys : VarysStruct; var pos = array( vec2f( -1, -1 ), vec2f( -1, 3 ), vec2f( 3, -1 ), ); let p = pos[ vertexIndex ]; let mult = select( vec2f( 0.5, -0.5 ), vec2f( 0.5, 0.5 ), flipY != 0 ); Varys.vTex = p * mult + vec2f( 0.5 ); Varys.Position = vec4f( p, 0, 1 ); Varys.vBaseArrayLayer = instanceIndex; return Varys; } @group( 0 ) @binding( 0 ) var imgSampler : sampler; @group( 0 ) @binding( 1 ) var img2d : texture_2d; @fragment fn main_2d( Varys: VarysStruct ) -> @location( 0 ) vec4 { return textureSample( img2d, imgSampler, Varys.vTex ); } @group( 0 ) @binding( 1 ) var img2dArray : texture_2d_array; @fragment fn main_2d_array( Varys: VarysStruct ) -> @location( 0 ) vec4 { return textureSample( img2dArray, imgSampler, Varys.vTex, Varys.vBaseArrayLayer ); } const faceMat = array( mat3x3f( 0, 0, -2, 0, -2, 0, 1, 1, 1 ), // pos-x mat3x3f( 0, 0, 2, 0, -2, 0, -1, 1, -1 ), // neg-x mat3x3f( 2, 0, 0, 0, 0, 2, -1, 1, -1 ), // pos-y mat3x3f( 2, 0, 0, 0, 0, -2, -1, -1, 1 ), // neg-y mat3x3f( 2, 0, 0, 0, -2, 0, -1, 1, 1 ), // pos-z mat3x3f( -2, 0, 0, 0, -2, 0, 1, 1, -1 ), // neg-z ); @group( 0 ) @binding( 1 ) var imgCube : texture_cube; @fragment fn main_cube( Varys: VarysStruct ) -> @location( 0 ) vec4 { return textureSample( imgCube, imgSampler, faceMat[ Varys.vBaseArrayLayer ] * vec3f( fract( Varys.vTex ), 1 ) ); } `;this.mipmapSampler=e.createSampler({minFilter:rs.Linear}),this.flipYSampler=e.createSampler({minFilter:rs.Nearest}),this.flipUniformBuffer=e.createBuffer({size:4,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),e.queue.writeBuffer(this.flipUniformBuffer,0,new Uint32Array([1])),this.noFlipUniformBuffer=e.createBuffer({size:4,usage:GPUBufferUsage.UNIFORM}),this.transferPipelines={},this.mipmapShaderModule=e.createShaderModule({label:"mipmap",code:t})}getTransferPipeline(e,t){t=t||"2d-array";const n=`${e}-${t}`;let i=this.transferPipelines[n];return i===void 0&&(i=this.device.createRenderPipeline({label:`mipmap-${e}-${t}`,vertex:{module:this.mipmapShaderModule},fragment:{module:this.mipmapShaderModule,entryPoint:`main_${t.replace("-","_")}`,targets:[{format:e}]},layout:"auto"}),this.transferPipelines[n]=i),i}flipY(e,t,n=0){const i=t.format,{width:s,height:o}=t.size,a=this.device.createTexture({size:{width:s,height:o},format:i,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),l=this.getTransferPipeline(i,e.textureBindingViewDimension),c=this.getTransferPipeline(i,a.textureBindingViewDimension),u=this.device.createCommandEncoder({}),h=(d,f,p,g,m,_)=>{const x=d.getBindGroupLayout(0),v=this.device.createBindGroup({layout:x,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:f.createView({dimension:f.textureBindingViewDimension||"2d-array",baseMipLevel:0,mipLevelCount:1})},{binding:2,resource:{buffer:_?this.flipUniformBuffer:this.noFlipUniformBuffer}}]}),S=u.beginRenderPass({colorAttachments:[{view:g.createView({dimension:"2d",baseMipLevel:0,mipLevelCount:1,baseArrayLayer:m,arrayLayerCount:1}),loadOp:At.Clear,storeOp:Zn.Store}]});S.setPipeline(d),S.setBindGroup(0,v),S.draw(3,1,0,p),S.end()};h(l,e,n,a,0,!1),h(c,a,0,e,n,!0),this.device.queue.submit([u.finish()]),a.destroy()}generateMipmaps(e,t=null){const n=this.get(e),i=n.layers||this._mipmapCreateBundles(e),s=t||this.device.createCommandEncoder({label:"mipmapEncoder"});this._mipmapRunBundles(s,i),t===null&&this.device.queue.submit([s.finish()]),n.layers=i}_mipmapCreateBundles(e){const t=e.textureBindingViewDimension||"2d-array",n=this.getTransferPipeline(e.format,t),i=n.getBindGroupLayout(0),s=[];for(let o=1;o0)for(let o=0,a=i.length;o0){for(const o of e.layerUpdates)this._copyBufferToTexture(t.image,n.texture,s,o,e.flipY,o);e.clearLayerUpdates()}else for(let o=0;o0)for(let o=0,a=i.length;o0?e.width:n.size.width,u=a>0?e.height:n.size.height;try{l.queue.copyExternalImageToTexture({source:e,flipY:s},{texture:t,mipLevel:a,origin:{x:0,y:0,z:i},premultipliedAlpha:o},{width:c,height:u,depthOrArrayLayers:1})}catch{}}_getPassUtils(){let e=this._passUtils;return e===null&&(this._passUtils=e=new _I(this.backend.device)),e}_generateMipmaps(e,t=null){this._getPassUtils().generateMipmaps(e,t)}_flipY(e,t,n=0){this._getPassUtils().flipY(e,t,n)}_copyBufferToTexture(e,t,n,i,s,o=0,a=0){const l=this.backend.device,c=e.data,u=this._getBytesPerTexel(n.format),h=e.width*u;l.queue.writeTexture({texture:t,mipLevel:a,origin:{x:0,y:0,z:i}},c,{offset:e.width*e.height*u*o,bytesPerRow:h},{width:e.width,height:e.height,depthOrArrayLayers:1}),s===!0&&this._flipY(t,n,i)}_copyCompressedBufferToTexture(e,t,n){const i=this.backend.device,s=this._getBlockData(n.format),o=n.size.depthOrArrayLayers>1;for(let a=0;a]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,bI=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig,K_={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"},TI=r=>{r=r.trim();const e=r.match(SI);if(e!==null&&e.length===4){const t=e[2],n=[];let i=null;for(;(i=bI.exec(t))!==null;)n.push({name:i[1],type:i[2]});const s=[];for(let u=0;u "+this.outputType:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class EI extends tv{parseFunction(e){return new MI(e)}}const AI={[Ni.READ_ONLY]:"read",[Ni.WRITE_ONLY]:"write",[Ni.READ_WRITE]:"read_write"},Z_={[ro]:"repeat",[ai]:"clamp",[oo]:"mirror"},Xd={vertex:ms.VERTEX,fragment:ms.FRAGMENT,compute:ms.COMPUTE},Q_={instance:!0,swizzleAssign:!1,storageBuffer:!0},RI={"^^":"tsl_xor"},wI={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"},J_={},gl={tsl_xor:new An("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new An("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new An("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new An("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new An("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new An("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new An("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2 { return vec2( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new An("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 An("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 An("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new An("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 An("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),biquadraticTexture:new An(` fn tsl_biquadraticTexture( map : texture_2d, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f { let res = vec2f( iRes ); let uvScaled = coord * res; let uvWrapping = ( ( uvScaled % res ) + res ) % res; // https://www.shadertoy.com/view/WtyXRy let uv = uvWrapping - 0.5; let iuv = floor( uv ); let f = fract( uv ); let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level ); let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level ); let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level ); let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level ); return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y ); } `),biquadraticTextureArray:new An(` fn tsl_biquadraticTexture_array( map : texture_2d_array, coord : vec2f, iRes : vec2u, layer : u32, level : u32 ) -> vec4f { let res = vec2f( iRes ); let uvScaled = coord * res; let uvWrapping = ( ( uvScaled % res ) + res ) % res; // https://www.shadertoy.com/view/WtyXRy let uv = uvWrapping - 0.5; let iuv = floor( uv ); let f = fract( uv ); let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, layer, level ); let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, layer, level ); let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, layer, level ); let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, layer, level ); return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y ); } `)},CI={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 dv="";(typeof navigator<"u"&&/Firefox|Deno/g.test(navigator.userAgent))!==!0&&(dv+=`diagnostic( off, derivative_uniformity ); `);class NI extends ev{constructor(e,t){super(e,t,new EI),this.uniformGroups={},this.uniformGroupsBindings={},this.builtins={},this.directives={},this.scopedArrays=new Map,this.allowEarlyReturns=!0,this.allowGlobalVariables=!0}_generateTextureSample(e,t,n,i,s,o=this.shaderStage){return o==="fragment"?i?s?`textureSample( ${t}, ${t}_sampler, ${n}, ${i}, ${s} )`:`textureSample( ${t}, ${t}_sampler, ${n}, ${i} )`:s?`textureSample( ${t}, ${t}_sampler, ${n}, ${s} )`:`textureSample( ${t}, ${t}_sampler, ${n} )`:this.generateTextureSampleLevel(e,t,n,"0",i)}generateTextureSampleLevel(e,t,n,i,s,o){return this.isUnfilterable(e)===!1?s?o?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${s}, ${i}, ${o} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${s}, ${i} )`:o?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${i}, ${o} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${i} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,n,o,i,s):this.generateTextureLod(e,t,n,s,o,i)}generateWrapFunction(e){const t=`tsl_coord_${Z_[e.wrapS]}S_${Z_[e.wrapT]}_${e.is3DTexture||e.isData3DTexture?"3d":"2d"}T`;let n=J_[t];if(n===void 0){const i=[],s=e.is3DTexture||e.isData3DTexture?"vec3f":"vec2f";let o=`fn ${t}( coord : ${s} ) -> ${s} { return ${s}( `;const a=(l,c)=>{l===ro?(i.push(gl.repeatWrapping_float),o+=` tsl_repeatWrapping_float( coord.${c} )`):l===ai?(i.push(gl.clampWrapping_float),o+=` tsl_clampWrapping_float( coord.${c} )`):l===oo?(i.push(gl.mirrorWrapping_float),o+=` tsl_mirrorWrapping_float( coord.${c} )`):(o+=` coord.${c}`,ee(`WebGPURenderer: Unsupported texture wrap type "${l}" for vertex shader.`))};a(e.wrapS,"x"),o+=`, `,a(e.wrapT,"y"),(e.is3DTexture||e.isData3DTexture)&&(o+=`, `,a(e.wrapR,"z")),o+=` ); } `,J_[t]=n=new An(o,i)}return n.build(this),t}generateArrayDeclaration(e,t){return`array< ${this.getType(e)}, ${t} >`}generateTextureDimension(e,t,n){const i=this.getDataFromNode(e,this.shaderStage,this.cache);i.dimensionsSnippet===void 0&&(i.dimensionsSnippet={});let s=i.dimensionsSnippet[n];if(i.dimensionsSnippet[n]===void 0){let o,a;const{primarySamples:l}=this.renderer.backend.utils.getTextureSampleData(e),c=l>1;e.is3DTexture||e.isData3DTexture?a="vec3":a="vec2",c||e.isStorageTexture?o=t:o=`${t}${n?`, u32( ${n} )`:""}`,s=new Au(new Ru(`textureDimensions( ${o} )`,a)),i.dimensionsSnippet[n]=s,(e.isArrayTexture||e.isDataArrayTexture||e.is3DTexture||e.isData3DTexture)&&(i.arrayLayerCount=new Au(new Ru(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(i.cubeFaceCount=new Au(new Ru("6u","u32")))}return s.build(this)}generateFilteredTexture(e,t,n,i,s="0u",o){const a=this.generateWrapFunction(e),l=this.generateTextureDimension(e,t,s);return i&&(n=`${n} + vec2(${i}) / ${l}`),o?(this._include("biquadraticTextureArray"),`tsl_biquadraticTexture_array( ${t}, ${a}( ${n} ), ${l}, u32( ${o} ), u32( ${s} ) )`):(this._include("biquadraticTexture"),`tsl_biquadraticTexture( ${t}, ${a}( ${n} ), ${l}, u32( ${s} ) )`)}generateTextureLod(e,t,n,i,s,o="0u"){if(e.isCubeTexture===!0){s&&(n=`${n} + vec3(${s})`);const f=e.isDepthTexture?"u32":"f32";return`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${f}( ${o} ) )`}const a=this.generateWrapFunction(e),l=this.generateTextureDimension(e,t,o),c=e.is3DTexture||e.isData3DTexture?"vec3":"vec2",u=c==="vec3"?"vec3( 1, 1, 1 )":"vec2( 1, 1 )";s&&(n=`${n} + ${c}(${s}) / ${c}( ${l} )`);const h=`${c}( 0 )`,d=`${c}( ${l} - ${u} )`;return n=`${c}( clamp( floor( ${a}( ${n} ) * ${c}( ${l} ) ), ${h}, ${d} ) )`,this.generateTextureLoad(e,t,n,o,i,null)}generateStorageTextureLoad(e,t,n,i,s,o){o&&(n=`${n} + ${o}`);let a;return s?a=`textureLoad( ${t}, ${n}, ${s} )`:a=`textureLoad( ${t}, ${n} )`,a}generateTextureLoad(e,t,n,i,s,o){i===null&&(i="0u"),o&&(n=`${n} + ${o}`);let a;return s?a=`textureLoad( ${t}, ${n}, ${s}, u32( ${i} ) )`:(a=`textureLoad( ${t}, ${n}, u32( ${i} ) )`,this.renderer.backend.compatibilityMode&&e.isDepthTexture&&(a+=".x")),a}generateTextureStore(e,t,n,i,s){let o;return i?o=`textureStore( ${t}, ${n}, ${i}, ${s} )`:o=`textureStore( ${t}, ${n}, ${s} )`,o}isSampleCompare(e){return e.isDepthTexture===!0&&e.compareFunction!==null&&this.renderer.hasCompatibility(_o.TEXTURE_COMPARE)}isUnfilterable(e){return this.getComponentTypeFromTexture(e)!=="float"||!this.isAvailable("float32Filterable")&&e.type===Zt||this.isSampleCompare(e)===!1&&e.minFilter===bt&&e.magFilter===bt||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1}generateTexture(e,t,n,i,s,o=this.shaderStage){let a=null;return this.isUnfilterable(e)?a=this.generateTextureLod(e,t,n,i,s,"0",o):a=this._generateTextureSample(e,t,n,i,s,o),a}generateTextureGrad(e,t,n,i,s,o,a=this.shaderStage){if(a==="fragment")return s?o?`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${s}, ${i[0]}, ${i[1]}, ${o} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${s}, ${i[0]}, ${i[1]} )`:o?`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${i[0]}, ${i[1]}, ${o} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${n}, ${i[0]}, ${i[1]} )`;ne(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${a} shader.`)}generateTextureCompare(e,t,n,i,s,o,a=this.shaderStage){if(a==="fragment")return e.isDepthTexture===!0&&e.isArrayTexture===!0?o?`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${s}, ${i}, ${o} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${s}, ${i} )`:o?`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${i}, ${o} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${n}, ${i} )`;ne(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${a} shader.`)}generateTextureLevel(e,t,n,i,s,o){return this.isUnfilterable(e)===!1?s?o?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${s}, ${i}, ${o} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${s}, ${i} )`:o?`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${i}, ${o} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${n}, ${i} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,n,o,i,s):this.generateTextureLod(e,t,n,s,o,i)}generateTextureBias(e,t,n,i,s,o,a=this.shaderStage){if(a==="fragment")return s?o?`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${s}, ${i}, ${o} )`:`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${s}, ${i} )`:o?`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${i}, ${o} )`:`textureSampleBias( ${t}, ${t}_sampler, ${n}, ${i} )`;ne(`WebGPURenderer: THREE.TextureNode.biasNode does not support ${a} shader.`)}getPropertyName(e,t=this.shaderStage){if(e.isNodeVarying===!0&&e.needsInterpolation===!0){if(t==="vertex")return`varyings.${e.name}`}else if(e.isNodeUniform===!0){const n=e.name,i=e.type;return i==="texture"||i==="cubeTexture"||i==="cubeDepthTexture"||i==="storageTexture"||i==="texture3D"?n:i==="buffer"||i==="storageBuffer"||i==="indirectStorageBuffer"?this.isCustomStruct(e)?n:n+".value":e.groupNode.name+"."+n}return super.getPropertyName(e)}getOutputStructName(){return"output"}getFunctionOperator(e){const t=RI[e];return t!==void 0?(this._include(t),t):null}getNodeAccess(e,t){return t!=="compute"?e.isAtomic===!0?(ee("WebGPURenderer: Atomic operations are only supported in compute shaders."),Ni.READ_WRITE):Ni.READ_ONLY:e.access}getStorageAccess(e,t){return AI[this.getNodeAccess(e,t)]}getUniformFromNode(e,t,n,i=null){const s=super.getUniformFromNode(e,t,n,i),o=this.getDataFromNode(e,n,this.globalCache);if(o.uniformGPU===void 0){let a;const l=e.groupNode,c=l.name,u=this.getBindGroupArray(c,n);if(t==="texture"||t==="cubeTexture"||t==="cubeDepthTexture"||t==="storageTexture"||t==="texture3D"){let h=null;const d=this.getNodeAccess(e,n);if(t==="texture"||t==="storageTexture"?e.value.is3DTexture===!0?h=new wf(s.name,s.node,l,d):h=new mh(s.name,s.node,l,d):t==="cubeTexture"||t==="cubeDepthTexture"?h=new cv(s.name,s.node,l,d):t==="texture3D"&&(h=new wf(s.name,s.node,l,d)),h.store=e.isStorageTextureNode===!0,h.mipLevel=h.store?e.mipLevel:0,h.setVisibility(Xd[n]),e.value.isCubeTexture===!0||this.isUnfilterable(e.value)===!1&&h.store===!1){const p=new fI(`${s.name}_sampler`,s.node,l);p.setVisibility(Xd[n]),u.push(p,h),a=[p,h]}else u.push(h),a=[h]}else if(t==="buffer"||t==="storageBuffer"||t==="indirectStorageBuffer"){const h=this.getSharedDataFromNode(e);let d=h.buffer;if(d===void 0){const f=t==="buffer"?ov:gI;d=new f(e,l),h.buffer=d}d.setVisibility(d.getVisibility()|Xd[n]),u.push(d),a=d,s.name=i||"NodeBuffer_"+s.id}else{let h=this.uniformGroups[c];h===void 0&&(h=new av(c,l),h.setVisibility(ms.VERTEX|ms.FRAGMENT|ms.COMPUTE),this.uniformGroups[c]=h),u.indexOf(h)===-1&&u.push(h),a=this.getNodeUniform(s,t);const d=a.name;h.uniforms.some(p=>p.name===d)||h.addUniform(a)}o.uniformGPU=a}return s}getBuiltin(e,t,n,i=this.shaderStage){const s=this.builtins[i]||(this.builtins[i]=new Map);return s.has(e)===!1&&s.set(e,{name:e,property:t,type:n}),t}hasBuiltin(e,t=this.shaderStage){return this.builtins[t]!==void 0&&this.builtins[t].has(e)}getVertexIndex(){return this.shaderStage==="vertex"?this.getBuiltin("vertex_index","vertexIndex","u32","attribute"):"vertexIndex"}buildFunctionCode(e){const t=e.layout,n=this.flowShaderNode(e),i=[];for(const o of t.inputs)i.push(o.name+" : "+this.getType(o.type));let s=`fn ${t.name}( ${i.join(", ")} ) -> ${this.getType(t.type)} { ${n.vars} ${n.code} `;return n.result&&(s+=` return ${n.result}; `),s+=` } `,s}getInstanceIndex(){return this.shaderStage==="vertex"?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(n!==void 0)for(const i of n)t.push(`enable ${i};`);return t.join(` `)}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(n!==void 0)for(const{name:i,property:s,type:o}of n.values())t.push(`@builtin( ${i} ) ${s} : ${o}`);return t.join(`, `)}getScopedArray(e,t,n,i){return this.scopedArrays.has(e)===!1&&this.scopedArrays.set(e,{name:e,scope:t,bufferType:n,bufferCount:i}),e}getScopedArrays(e){if(e!=="compute")return;const t=[];for(const{name:n,scope:i,bufferType:s,bufferCount:o}of this.scopedArrays.values()){const a=this.getType(s);t.push(`var<${i}> ${n}: array< ${a}, ${o} >;`)}return t.join(` `)}getAttributes(e){const t=[];if(e==="compute"&&(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"))),e==="vertex"||e==="compute"){const n=this.getBuiltins("attribute");n&&t.push(n);const i=this.getAttributesArray();for(let s=0,o=i.length;s"),t.push(` ${i+n.name} : ${s}`)}return e.output&&t.push(` ${this.getBuiltins("output")}`),t.join(`, `)}getStructs(e){let t="";const n=this.structs[e];if(n.length>0){const i=[];for(const s of n){let o=`struct ${s.name} { `;o+=this.getStructMembers(s),o+=` };`,i.push(o)}t=` `+i.join(` `)+` `}return t}getVar(e,t,n=null,i=""){let s=`var${i} ${t} : `;return n!==null?s+=this.generateArrayDeclaration(e,n):s+=this.getType(e),s}getVars(e,t=!1){let n="";t&&(n="");const i=[],s=this.vars[e];if(s!==void 0)for(const o of s)i.push(`${this.getVar(o.type,o.name,o.count,n)};`);return t?i.join(` `):` ${i.join(` `)} `}getVaryings(e){const t=[];if(e==="vertex"&&this.getBuiltin("position","builtinClipSpace","vec4","vertex"),e==="vertex"||e==="fragment"){const s=this.varyings,o=this.vars[e];let a=0;for(let l=0;ln.value.itemSize;return i&&!s}getUniforms(e){const t=this.renderer.backend,n=this.uniforms[e],i=[],s=[],o=[],a={};for(const c of n){const u=c.groupNode.name,h=this.bindingsIndexes[u];if(c.type==="texture"||c.type==="cubeTexture"||c.type==="cubeDepthTexture"||c.type==="storageTexture"||c.type==="texture3D"){const d=c.node.value;(d.isCubeTexture===!0||this.isUnfilterable(d)===!1&&c.node.isStorageTextureNode!==!0)&&(this.isSampleCompare(d)?i.push(`@binding( ${h.binding++} ) @group( ${h.group} ) var ${c.name}_sampler : sampler_comparison;`):i.push(`@binding( ${h.binding++} ) @group( ${h.group} ) var ${c.name}_sampler : sampler;`));let p,g="";const{primarySamples:m}=t.utils.getTextureSampleData(d);if(m>1&&(g="_multisampled"),d.isCubeTexture===!0&&d.isDepthTexture===!0)p="texture_depth_cube";else if(d.isCubeTexture===!0)p="texture_cube";else if(d.isDepthTexture===!0)t.compatibilityMode&&d.compareFunction===null?p=`texture${g}_2d`:p=`texture_depth${g}_2d${d.isArrayTexture===!0?"_array":""}`;else if(c.node.isStorageTextureNode===!0){const _=Cf(d,t.device),x=this.getStorageAccess(c.node,e),v=c.node.value.is3DTexture,S=c.node.value.isArrayTexture;p=`texture_storage_${v?"3d":`2d${S?"_array":""}`}<${_}, ${x}>`}else if(d.isArrayTexture===!0||d.isDataArrayTexture===!0||d.isCompressedArrayTexture===!0)p="texture_2d_array";else if(d.is3DTexture===!0||d.isData3DTexture===!0)p="texture_3d";else{const _=this.getComponentTypeFromTexture(d).charAt(0);p=`texture${g}_2d<${_}32>`}i.push(`@binding( ${h.binding++} ) @group( ${h.group} ) var ${c.name} : ${p};`)}else if(c.type==="buffer"||c.type==="storageBuffer"||c.type==="indirectStorageBuffer"){const d=c.node,f=this.getType(d.getNodeType(this)),p=d.bufferCount,g=p>0&&c.type==="buffer"?", "+p:"",m=d.isStorageBufferNode?`storage, ${this.getStorageAccess(d,e)}`:"uniform";if(this.isCustomStruct(c))s.push(`@binding( ${h.binding++} ) @group( ${h.group} ) var<${m}> ${c.name} : ${f};`);else{const x=` value : array< ${d.isAtomic?`atomic<${f}>`:`${f}`}${g} >`;s.push(this._getWGSLStructBinding(c.name,x,m,h.binding++,h.group))}}else{const d=c.groupNode.name;if(a[d]===void 0){const f=this.uniformGroups[d];if(f!==void 0){const p=[];for(const m of f.uniforms){const _=m.getType(),x=this.getType(this.getVectorType(_));p.push(` ${m.name} : ${x}`)}let g=this.uniformGroupsBindings[d];g===void 0&&(g={index:h.binding++,id:h.group},this.uniformGroupsBindings[d]=g),a[d]={index:g.index,id:g.id,snippets:p}}}}}for(const c in a){const u=a[c];o.push(this._getWGSLStructBinding(c,u.snippets.join(`, `),"uniform",u.index,u.id))}return[...i,...s,...o].join(` `)}buildCode(){const e=this.material!==null?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){this.shaderStage=t;const n=this.allowGlobalVariables,i=e[t];i.uniforms=this.getUniforms(t),i.attributes=this.getAttributes(t),i.varyings=this.getVaryings(t),i.structs=this.getStructs(t),i.vars=this.getVars(t,n),i.codes=this.getCodes(t),i.directives=this.getDirectives(t),i.scopedArrays=this.getScopedArrays(t);let s=`// code `;s+=this.flowCode[t];const o=this.flowNodes[t],a=o[o.length-1],l=a.outputNode,c=l!==void 0&&l.isOutputStructNode===!0;for(const u of o){const h=this.getFlowData(u),d=u.name;if(d&&(s.length>0&&(s+=` `),s+=` // flow -> ${d} `),s+=`${h.code} `,u===a&&t!=="compute"){if(s+=`// result `,t==="vertex")s+=`varyings.builtinClipSpace = ${h.result};`;else if(t==="fragment")if(c)i.returnType=l.getNodeType(this),i.structs+="var output : "+i.returnType+";",s+=`return ${h.result};`;else{let f=" @location( 0 ) color: vec4";const p=this.getBuiltins("output");p&&(f+=`, `+p),i.returnType="OutputStruct",i.structs+=this._getWGSLStruct("OutputStruct",f),i.structs+=` var output : OutputStruct;`,s+=`output.color = ${h.result}; return output;`}}}i.flow=s}if(this.shaderStage=null,this.material!==null)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 t!==null&&(n=this._getWGSLMethod(e+"_"+t)),n===void 0&&(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 wI[e]||e}isAvailable(e){let t=Q_[e];return t===void 0&&(e==="float32Filterable"?t=this.renderer.hasFeature("float32-filterable"):e==="clipDistance"&&(t=this.renderer.hasFeature("clip-distances")),Q_[e]=t),t}_getWGSLMethod(e){return gl[e]!==void 0&&this._include(e),CI[e]}_include(e){const t=gl[e];return t.build(this),this.addInclude(t),t}_getWGSLVertexCode(e){return`${this.getSignature()} // directives ${e.directives} // structs ${e.structs} // uniforms ${e.uniforms} // varyings ${e.varyings} var varyings : VaryingsStruct; // vars ${e.vars} // codes ${e.codes} @vertex fn main( ${e.attributes} ) -> VaryingsStruct { // flow ${e.flow} return varyings; } `}_getWGSLFragmentCode(e){return`${this.getSignature()} // global ${dv} // structs ${e.structs} // uniforms ${e.uniforms} // vars ${e.vars} // codes ${e.codes} @fragment fn main( ${e.varyings} ) -> ${e.returnType} { // flow ${e.flow} } `}_getWGSLComputeCode(e,t){const[n,i,s]=t;return`${this.getSignature()} // directives ${e.directives} // system var instanceIndex : u32; // locals ${e.scopedArrays} // structs ${e.structs} // uniforms ${e.uniforms} // vars ${this.allowGlobalVariables?e.vars:""} // codes ${e.codes} @compute @workgroup_size( ${n}, ${i}, ${s} ) fn main( ${e.attributes} ) { // local vars ${this.allowGlobalVariables?"":e.vars} // system instanceIndex = globalId.x + globalId.y * ( ${n} * numWorkgroups.x ) + globalId.z * ( ${n} * numWorkgroups.x ) * ( ${i} * numWorkgroups.y ); // flow ${e.flow} } `}_getWGSLStruct(e,t){return` struct ${e} { ${t} };`}_getWGSLStructBinding(e,t,n,i=0,s=0){const o=e+"Struct";return`${this._getWGSLStruct(o,t)} @binding( ${i} ) @group( ${s} ) var<${n}> ${e} : ${o};`}}class PI{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return e.depth&&(e.depthTexture!==null?t=this.getTextureFormatGPU(e.depthTexture):e.stencil?this.backend.renderer.reversedDepthBuffer===!0?t=D.Depth32FloatStencil8:t=D.Depth24PlusStencil8:this.backend.renderer.reversedDepthBuffer===!0?t=D.Depth32Float:t=D.Depth24Plus),t}getTextureFormatGPU(e){return this.backend.get(e).format}getTextureSampleData(e){let t;if(e.isFramebufferTexture)t=1;else if(e.isDepthTexture&&!e.renderTarget){const s=this.backend.renderer,o=s.getRenderTarget();t=o?o.samples:s.currentSamples}else e.renderTarget&&(t=e.renderTarget.samples);t=t||1;const n=t>1&&e.renderTarget!==null&&e.isDepthTexture!==!0&&e.isFramebufferTexture!==!0;return{samples:t,primarySamples:n?1:t,isMSAA:n}}getCurrentColorFormat(e){let t;return e.textures!==null?t=this.getTextureFormatGPU(e.textures[0]):t=this.getPreferredCanvasFormat(),t}getCurrentColorFormats(e){return e.textures!==null?e.textures.map(t=>this.getTextureFormatGPU(t)):[this.getPreferredCanvasFormat()]}getCurrentColorSpace(e){return e.textures!==null?e.textures[0].colorSpace:this.backend.renderer.outputColorSpace}getPrimitiveTopology(e,t){if(e.isPoints)return fu.PointList;if(e.isLineSegments||e.isMesh&&t.wireframe===!0)return fu.LineList;if(e.isLine)return fu.LineStrip;if(e.isMesh)return fu.TriangleList}getSampleCount(e){return e>=4?4:1}getSampleCountRenderContext(e){return e.textures!==null?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.currentSamples)}getPreferredCanvasFormat(){const t=this.backend.parameters.outputType;if(t===void 0)return navigator.gpu.getPreferredCanvasFormat();if(t===$t)return D.BGRA8Unorm;if(t===en)return D.RGBA16Float;throw new Error("Unsupported output buffer type.")}}const fv=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]);typeof Float16Array<"u"&&fv.set(Float16Array,["float16"]);const DI=new Map([[Ex,["float16"]]]),LI=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class UI{constructor(e){this.backend=e}createAttribute(e,t){const n=this._getBufferAttribute(e),i=this.backend,s=i.get(n);let o=s.buffer;if(o===void 0){const a=i.device;let l=n.array;if(e.normalized===!1){if(l.constructor===Int16Array||l.constructor===Int8Array)l=new Int32Array(l);else if((l.constructor===Uint16Array||l.constructor===Uint8Array)&&(l=new Uint32Array(l),t&GPUBufferUsage.INDEX))for(let h=0;h{t.buffer=null,t._mapped=!1,u.unmap()},g=()=>{t.buffer=null,t._mapped=!1,u.destroy(),s.delete(t),t.removeEventListener("release",p),t.removeEventListener("dispose",g)};t.addEventListener("release",p),t.addEventListener("dispose",g),f.readBufferGPU=u}else u=f.readBufferGPU}else u=o.createBuffer({label:`${e.name}_readback`,size:c,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});const h=o.createCommandEncoder({label:`readback_encoder_${e.name}`});h.copyBufferToBuffer(l,n,u,0,c);const d=h.finish();if(o.queue.submit([d]),await u.mapAsync(GPUMapMode.READ,0,c),t===null){const p=u.getMappedRange(0,c).slice();return u.destroy(),p}else{if(t.isReadbackBuffer)return t.buffer=u.getMappedRange(0,c),t;{const f=u.getMappedRange(0,c);return new Uint8Array(t).set(new Uint8Array(f)),u.destroy(),t}}}_getVertexFormat(e){const{itemSize:t,normalized:n}=e,i=e.array.constructor,s=e.constructor;let o;if(t===1)o=LI.get(i);else{const l=(DI.get(s)||fv.get(i))[n?1:0];if(l){const c=i.BYTES_PER_ELEMENT*t,h=Math.floor((c+3)/4)*4/i.BYTES_PER_ELEMENT;if(h%1)throw new Error("THREE.WebGPUAttributeUtils: Bad vertex format item size.");o=`${l}x${h}`}}return o||ne("WebGPUAttributeUtils: Vertex format not supported yet."),o}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}class FI{constructor(e){this.layoutGPU=e,this.usedTimes=0}}class II{constructor(e){this.backend=e,this._bindGroupLayoutCache=new Map}createBindingsLayout(e){const t=this.backend,n=t.device,i=t.get(e);if(i.layout)return i.layout.layoutGPU;const s=this._createLayoutEntries(e),o=Ha(JSON.stringify(s));let a=this._bindGroupLayoutCache.get(o);return a===void 0&&(a=new FI(n.createBindGroupLayout({entries:s})),this._bindGroupLayoutCache.set(o,a)),a.usedTimes++,i.layout=a,i.layoutKey=o,a.layoutGPU}createBindings(e,t,n,i=0){const{backend:s}=this,o=s.get(e),a=this.createBindingsLayout(e);let l;n>0&&(o.groups===void 0&&(o.groups=[],o.versions=[]),o.versions[n]===i&&(l=o.groups[n])),l===void 0&&(l=this.createBindGroup(e,a),n>0&&(o.groups[n]=l,o.versions[n]=i)),o.group=l}updateBinding(e){const t=this.backend,n=t.device,i=e.buffer,s=t.get(e).buffer,o=e.updateRanges;if(o.length===0)n.queue.writeBuffer(s,0,i,0);else{const a=Pu(i),l=a?1:i.BYTES_PER_ELEMENT;for(let c=0,u=o.length;c1&&(d+=`-${l.texture.depthOrArrayLayers}`),d+=`-${u}-${h}`,c=l[d],c===void 0){const f=dI.All;let p;a.isSampledCubeTexture?p=zn.Cube:a.isSampledTexture3D?p=zn.ThreeD:a.texture.isArrayTexture||a.texture.isDataArrayTexture||a.texture.isCompressedArrayTexture?p=zn.TwoDArray:p=zn.TwoD,c=l[d]=l.texture.createView({aspect:f,dimension:p,mipLevelCount:u,baseMipLevel:h})}}o.push({binding:s,resource:c})}else if(a.isSampler){const l=n.get(a.texture);o.push({binding:s,resource:l.sampler})}s++}return i.createBindGroup({label:"bindGroup_"+e.name,layout:t,entries:o})}_createLayoutEntries(e){const t=[];let n=0;for(const i of e.bindings){const s=this.backend,o={binding:n,visibility:i.visibility};if(i.isUniformBuffer||i.isStorageBuffer){const a={};i.isStorageBuffer&&(i.visibility&ms.COMPUTE&&(i.access===Ni.READ_WRITE||i.access===Ni.WRITE_ONLY)?a.type=Wd.Storage:a.type=Wd.ReadOnlyStorage),o.buffer=a}else if(i.isSampledTexture&&i.store){const a={};a.format=this.backend.get(i.texture).texture.format;const l=i.access;l===Ni.READ_WRITE?a.access=$d.ReadWrite:l===Ni.WRITE_ONLY?a.access=$d.WriteOnly:a.access=$d.ReadOnly,i.texture.isArrayTexture?a.viewDimension=zn.TwoDArray:i.texture.is3DTexture&&(a.viewDimension=zn.ThreeD),o.storageTexture=a}else if(i.isSampledTexture){const a={},{primarySamples:l}=s.utils.getTextureSampleData(i.texture);if(l>1&&(a.multisampled=!0,i.texture.isDepthTexture||(a.sampleType=Hr.UnfilterableFloat)),i.texture.isDepthTexture)s.compatibilityMode&&i.texture.compareFunction===null?a.sampleType=Hr.UnfilterableFloat:a.sampleType=Hr.Depth;else if(i.texture.isDataTexture||i.texture.isDataArrayTexture||i.texture.isData3DTexture||i.texture.isStorageTexture){const c=i.texture.type;c===Sn?a.sampleType=Hr.SInt:c===wt?a.sampleType=Hr.UInt:c===Zt&&(this.backend.hasFeature("float32-filterable")?a.sampleType=Hr.Float:a.sampleType=Hr.UnfilterableFloat)}i.isSampledCubeTexture?a.viewDimension=zn.Cube:i.texture.isArrayTexture||i.texture.isDataArrayTexture||i.texture.isCompressedArrayTexture?a.viewDimension=zn.TwoDArray:i.isSampledTexture3D&&(a.viewDimension=zn.ThreeD),o.texture=a}else if(i.isSampler){const a={};i.texture.isDepthTexture&&(i.texture.compareFunction!==null&&s.hasCompatibility(_o.TEXTURE_COMPARE)?a.type=q_.Comparison:a.type=q_.NonFiltering),o.sampler=a}else ne(`WebGPUBindingUtils: Unsupported binding "${i}".`);t.push(o),n++}return t}deleteBindGroupData(e){const{backend:t}=this,n=t.get(e);n.layout&&(n.layout.usedTimes--,n.layout.usedTimes===0&&this._bindGroupLayoutCache.delete(n.layoutKey),n.layout=void 0,n.layoutKey=void 0)}dispose(){this._bindGroupLayoutCache.clear()}}class BI{constructor(e){this.backend=e}getMaxAnisotropy(){return 16}getUniformBufferLimit(){return this.backend.device.limits.maxUniformBufferBindingSize}}class OI{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:i,geometry:s,pipeline:o}=e,{vertexProgram:a,fragmentProgram:l}=o,c=this.backend,u=c.device,h=c.utils,d=c.get(o),f=[];for(const G of e.getBindings()){const V=c.get(G),{layoutGPU:L}=V.layout;f.push(L)}const p=c.attributeUtils.createShaderVertexBuffers(e);let g;i.blending!==Cn&&(i.blending!==Jn||i.transparent!==!1)&&(g=this._getBlending(i));let m={};i.stencilWrite===!0&&(m={compare:this._getStencilCompare(i),failOp:this._getStencilOperation(i.stencilFail),depthFailOp:this._getStencilOperation(i.stencilZFail),passOp:this._getStencilOperation(i.stencilZPass)});const _=this._getColorWriteMask(i),x=[];if(e.context.textures!==null){const G=e.context.textures,V=e.context.mrt;for(let L=0;L1},layout:u.createPipelineLayout({bindGroupLayouts:f})},P={},N=e.context.depth,U=e.context.stencil;if((N===!0||U===!0)&&(N===!0&&(P.format=A,P.depthWriteEnabled=i.depthWrite,P.depthCompare=T),U===!0&&(P.stencilFront=m,P.stencilBack=m,P.stencilReadMask=i.stencilFuncMask,P.stencilWriteMask=i.stencilWriteMask),i.polygonOffset===!0&&(P.depthBias=i.polygonOffsetUnits,P.depthBiasSlopeScale=i.polygonOffsetFactor,P.depthBiasClamp=0),R.depthStencil=P),u.pushErrorScope("validation"),t===null)d.pipeline=u.createRenderPipeline(R),u.popErrorScope().then(G=>{G!==null&&(d.error=!0,ne(G.message))});else{const G=new Promise(async V=>{try{d.pipeline=await u.createRenderPipelineAsync(R)}catch{}const L=await u.popErrorScope();L!==null&&(d.error=!0,ne(L.message)),V()});t.push(G)}}createBundleEncoder(e,t="renderBundleEncoder"){const n=this.backend,{utils:i,device:s}=n,o=i.getCurrentDepthStencilFormat(e),a=i.getCurrentColorFormats(e),l=this._getSampleCount(e),c={label:t,colorFormats:a,depthStencilFormat:o,sampleCount:l};return s.createRenderBundleEncoder(c)}createComputePipeline(e,t){const n=this.backend,i=n.device,s=n.get(e.computeProgram).module,o=n.get(e),a=[];for(const l of t){const c=n.get(l),{layoutGPU:u}=c.layout;a.push(u)}o.pipeline=i.createComputePipeline({compute:s,layout:i.createPipelineLayout({bindGroupLayouts:a})})}_getBlending(e){let t,n;const i=e.blending,s=e.blendSrc,o=e.blendDst,a=e.blendEquation;if(i===Jr){const l=e.blendSrcAlpha!==null?e.blendSrcAlpha:s,c=e.blendDstAlpha!==null?e.blendDstAlpha:o,u=e.blendEquationAlpha!==null?e.blendEquationAlpha:a;t={srcFactor:this._getBlendFactor(s),dstFactor:this._getBlendFactor(o),operation:this._getBlendOperation(a)},n={srcFactor:this._getBlendFactor(l),dstFactor:this._getBlendFactor(c),operation:this._getBlendOperation(u)}}else{const l=e.premultipliedAlpha,c=(u,h,d,f)=>{t={srcFactor:u,dstFactor:h,operation:zr.Add},n={srcFactor:d,dstFactor:f,operation:zr.Add}};if(l)switch(i){case Jn:c(pt.One,pt.OneMinusSrcAlpha,pt.One,pt.OneMinusSrcAlpha);break;case hr:c(pt.One,pt.One,pt.One,pt.One);break;case dr:c(pt.Zero,pt.OneMinusSrc,pt.Zero,pt.One);break;case fr:c(pt.Dst,pt.OneMinusSrcAlpha,pt.Zero,pt.One);break}else switch(i){case Jn:c(pt.SrcAlpha,pt.OneMinusSrcAlpha,pt.One,pt.OneMinusSrcAlpha);break;case hr:c(pt.SrcAlpha,pt.One,pt.One,pt.One);break;case dr:ne(`WebGPURenderer: "SubtractiveBlending" requires "${e.isMaterial?"material":"blendMode"}.premultipliedAlpha = true".`);break;case fr:ne(`WebGPURenderer: "MultiplyBlending" requires "${e.isMaterial?"material":"blendMode"}.premultipliedAlpha = true".`);break}}if(t!==void 0&&n!==void 0)return{color:t,alpha:n};ne("WebGPURenderer: Invalid blending: ",i)}_getBlendFactor(e){let t;switch(e){case Us:t=pt.Zero;break;case Ff:t=pt.One;break;case If:t=pt.Src;break;case Bf:t=pt.OneMinusSrc;break;case Ul:t=pt.SrcAlpha;break;case Fl:t=pt.OneMinusSrcAlpha;break;case Gf:t=pt.Dst;break;case Vf:t=pt.OneMinusDst;break;case Of:t=pt.DstAlpha;break;case kf:t=pt.OneMinusDstAlpha;break;case zf:t=pt.SrcAlphaSaturated;break;case yL:t=pt.Constant;break;case vL:t=pt.OneMinusConstant;break;default:ne("WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const n=e.stencilFunc;switch(n){case rS:t=Dn.Never;break;case tf:t=Dn.Always;break;case oS:t=Dn.Less;break;case lS:t=Dn.LessEqual;break;case aS:t=Dn.Equal;break;case hS:t=Dn.GreaterEqual;break;case cS:t=Dn.Greater;break;case uS:t=Dn.NotEqual;break;default:ne("WebGPURenderer: Invalid stencil function.",n)}return t}_getStencilOperation(e){let t;switch(e){case $r:t=ar.Keep;break;case Qv:t=ar.Zero;break;case Jv:t=ar.Replace;break;case sS:t=ar.Invert;break;case eS:t=ar.IncrementClamp;break;case tS:t=ar.DecrementClamp;break;case nS:t=ar.IncrementWrap;break;case iS:t=ar.DecrementWrap;break;default:ne("WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case Wn:t=zr.Add;break;case Lf:t=zr.Subtract;break;case Uf:t=zr.ReverseSubtract;break;case fx:t=zr.Min;break;case px:t=zr.Max;break;default:ne("WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,n){const i={},s=this.backend.utils;i.topology=s.getPrimitiveTopology(e,n),t.index!==null&&e.isLine===!0&&e.isLineSegments!==!0&&(i.stripIndexFormat=t.index.array instanceof Uint16Array?Xu.Uint16:Xu.Uint32);let o=n.side===Pt;return e.isMesh&&e.matrixWorld.determinant()<0&&(o=!o),i.frontFace=o===!0?W_.CW:W_.CCW,i.cullMode=n.side===wn?$_.None:$_.Back,i}_getColorWriteMask(e){return e.colorWrite===!0?X_.All:X_.None}_getDepthCompare(e){let t;if(e.depthTest===!1)t=Dn.Always;else{const n=this.backend.parameters.reversedDepthBuffer?tp[e.depthFunc]:e.depthFunc;switch(n){case Il:t=Dn.Never;break;case Bl:t=Dn.Always;break;case Ol:t=Dn.Less;break;case Ar:t=Dn.LessEqual;break;case kl:t=Dn.Equal;break;case Gl:t=Dn.GreaterEqual;break;case Vl:t=Dn.Greater;break;case zl:t=Dn.NotEqual;break;default:ne("WebGPUPipelineUtils: Invalid depth function.",n)}}return t}}class kI extends hv{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 i=this.maxQueries*8;this.resolveBuffer=this.device.createBuffer({label:`buffer_timestamp_resolve_${t}`,size:i,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.resultBuffer=this.device.createBuffer({label:`buffer_timestamp_result_${t}`,size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ})}allocateQueriesForContext(e){if(!this.trackTimestamp||this.isDisposed)return null;if(this.currentQueryIndex+2>this.maxQueries)return Yt(`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||this.currentQueryIndex===0||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(this.resultBuffer.mapState!=="unmapped")return this.lastValue;const e=new Map(this.queryOffsets),t=this.currentQueryIndex,n=t*8;this.currentQueryIndex=0,this.queryOffsets.clear();const i=this.device.createCommandEncoder();i.resolveQuerySet(this.querySet,0,t,this.resolveBuffer,0),i.copyBufferToBuffer(this.resolveBuffer,0,this.resultBuffer,0,n);const s=i.finish();if(this.device.queue.submit([s]),this.resultBuffer.mapState!=="unmapped")return this.lastValue;if(await this.resultBuffer.mapAsync(GPUMapMode.READ,0,n),this.isDisposed)return this.resultBuffer.mapState==="mapped"&&this.resultBuffer.unmap(),this.lastValue;const o=new BigUint64Array(this.resultBuffer.getMappedRange(0,n)),a={},l=[];for(const[u,h]of e){const d=u.match(/^(.*):f(\d+)$/),f=parseInt(d[2]);l.includes(f)===!1&&l.push(f),a[f]===void 0&&(a[f]=0);const p=o[h],g=o[h+1],m=Number(g-p)/1e6;this.timestamps.set(u,m),a[f]+=m}const c=a[l[l.length-1]];return this.resultBuffer.unmap(),this.lastValue=c,this.frames=l,c}catch(e){return ne("Error resolving queries:",e),this.resultBuffer.mapState==="mapped"&&this.resultBuffer.unmap(),this.lastValue}}async dispose(){if(!this.isDisposed){if(this.isDisposed=!0,this.pendingResolve)try{await this.pendingResolve}catch(e){ne("Error waiting for pending resolve:",e)}if(this.resultBuffer&&this.resultBuffer.mapState==="mapped")try{this.resultBuffer.unmap()}catch(e){ne("Error unmapping buffer:",e)}this.querySet&&(this.querySet.destroy(),this.querySet=null),this.resolveBuffer&&(this.resolveBuffer.destroy(),this.resolveBuffer=null),this.resultBuffer&&(this.resultBuffer.destroy(),this.resultBuffer=null),this.queryOffsets.clear(),this.pendingResolve=null}}}const Vi={r:0,g:0,b:0,a:1};class GI extends uv{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=e.alpha===void 0?!0:e.alpha,this.parameters.requiredLimits=e.requiredLimits===void 0?{}:e.requiredLimits,this.compatibilityMode=null,this.device=null,this.defaultRenderPassdescriptor=null,this.utils=new PI(this),this.attributeUtils=new UI(this),this.bindingUtils=new II(this),this.capabilities=new BI(this),this.pipelineUtils=new OI(this),this.textureUtils=new vI(this),this.occludedResolveCache=new Map;const t=typeof navigator>"u"?!0:/Android/.test(navigator.userAgent)===!1;this._compatibility={[_o.TEXTURE_COMPARE]:t}}async init(e){await super.init(e);const t=this.parameters;let n;if(t.device===void 0){const i={powerPreference:t.powerPreference,featureLevel:"compatibility"},s=typeof navigator<"u"?await navigator.gpu.requestAdapter(i):null;if(s===null)throw new Error("WebGPUBackend: Unable to create WebGPU adapter.");const o=Object.values(qu),a=[];for(const c of o)s.features.has(c)&&a.push(c);const l={requiredFeatures:a,requiredLimits:t.requiredLimits};n=await s.requestDevice(l)}else n=t.device;this.compatibilityMode=!n.features.has("core-features-and-limits"),this.compatibilityMode&&(e._samples=0),n.lost.then(i=>{if(i.reason==="destroyed")return;const s={api:"WebGPU",message:i.message||"Unknown reason",reason:i.reason||null,originalEvent:i};e.onDeviceLost(s)}),this.device=n,this.trackTimestamp=this.trackTimestamp&&this.hasFeature(qu.TimestampQuery),this.updateSize()}get context(){const e=this.renderer.getCanvasTarget(),t=this.get(e);let n=t.context;if(n===void 0){const i=this.parameters;e.isDefaultCanvasTarget===!0&&i.context!==void 0?n=i.context:n=e.domElement.getContext("webgpu"),"setAttribute"in e.domElement&&e.domElement.setAttribute("data-engine",`three.js r${po} webgpu`);const s=i.alpha?"premultiplied":"opaque",o=i.outputType===en?"extended":"standard";n.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:s,toneMapping:{mode:o}}),t.context=n}return n}get coordinateSystem(){return xs}async getArrayBufferAsync(e,t=null,n=0,i=-1){return await this.attributeUtils.getArrayBufferAsync(e,t,n,i)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){const e=this.renderer,t=e.getCanvasTarget(),n=this.get(t),i=e.currentSamples;let s=n.descriptor;if(s===void 0||n.samples!==i){s={colorAttachments:[{view:null}]},(e.depth===!0||e.stencil===!0)&&(s.depthStencilAttachment={view:this.textureUtils.getDepthBuffer(e.depth,e.stencil).createView()});const a=s.colorAttachments[0];i>0?a.view=this.textureUtils.getColorBuffer().createView():a.resolveTarget=void 0,n.descriptor=s,n.samples=i}const o=s.colorAttachments[0];return i>0?o.resolveTarget=this.context.getCurrentTexture().createView():o.view=this.context.getCurrentTexture().createView(),s}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.image.depth>1&&e.camera.isArrayCamera}_getRenderPassDescriptor(e,t={}){const n=e.renderTarget,i=this.get(n);let s=i.descriptors;(s===void 0||i.width!==n.width||i.height!==n.height||i.samples!==n.samples)&&(s={},i.descriptors=s);const o=e.getCacheKey();let a=s[o];if(a===void 0){const c=e.textures,u=[];let h;const d=this._isRenderCameraDepthArray(e);for(let f=0;f1)if(d===!0){const m=e.camera.cameras;for(let _=0;_0&&(t.currentOcclusionQuerySet&&t.currentOcclusionQuerySet.destroy(),t.currentOcclusionQueryBuffer&&t.currentOcclusionQueryBuffer.destroy(),t.currentOcclusionQuerySet=t.occlusionQuerySet,t.currentOcclusionQueryBuffer=t.occlusionQueryBuffer,t.currentOcclusionQueryObjects=t.occlusionQueryObjects,s=n.createQuerySet({type:"occlusion",count:i,label:`occlusionQuerySet_${e.id}`}),t.occlusionQuerySet=s,t.occlusionQueryIndex=0,t.occlusionQueryObjects=new Array(i),t.lastOcclusionObject=null);let o;e.textures===null?o=this._getDefaultRenderPassDescriptor():o=this._getRenderPassDescriptor(e,{loadOp:At.Load}),this.initTimestampQuery(ps.RENDER,this.getTimestampUID(e),o),o.occlusionQuerySet=s;const a=o.depthStencilAttachment;if(e.textures!==null){const c=o.colorAttachments;for(let u=0;u0&&t.currentPass.executeBundles(t.renderBundles),n>t.occlusionQueryIndex&&t.currentPass.endOcclusionQuery();const i=t.encoder;if(this._isRenderCameraDepthArray(e)===!0){const s=[];for(let o=0;o0){const s=n*8;let o=this.occludedResolveCache.get(s);o===void 0&&(o=this.device.createBuffer({size:s,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.occludedResolveCache.set(s,o));const a=this.device.createBuffer({size:s,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});t.encoder.resolveQuerySet(t.occlusionQuerySet,0,n,o,0),t.encoder.copyBufferToBuffer(o,0,a,0,s),t.occlusionQueryBuffer=a,this.resolveOccludedAsync(e)}if(this.device.queue.submit([t.encoder.finish()]),e.textures!==null){const s=e.textures;for(let o=0;of&&(s[0]=Math.min(d,f),s[1]=Math.ceil(d/f)),o.dispatchSize=s}s=o.dispatchSize}a.dispatchWorkgroups(s[0],s[1]||1,s[2]||1)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),this.device.queue.submit([t.cmdEncoderGPU.finish()])}_draw(e,t,n,i,s,o,a,l,c){const{object:u,material:h,context:d}=e,f=e.getIndex(),p=f!==null;this.pipelineUtils.setPipeline(l,i),c.pipeline=i;const g=c.bindingGroups;for(let m=0,_=s.length;m<_;m++){const x=s[m],v=this.get(x);g[m]!==x.id&&(l.setBindGroup(m,v.group),g[m]=x.id)}if(p===!0&&c.index!==f){const m=this.get(f).buffer,_=f.array instanceof Uint16Array?Xu.Uint16:Xu.Uint32;l.setIndexBuffer(m,_),c.index=f}for(let m=0,_=o.length;m<_;m++){const x=o[m];if(c.attributes[m]!==x){const v=this.get(x).buffer;l.setVertexBuffer(m,v),c.attributes[m]=x}}if(d.stencil===!0&&h.stencilWrite===!0&&n.currentStencilRef!==h.stencilRef&&(l.setStencilReference(h.stencilRef),n.currentStencilRef=h.stencilRef),u.isBatchedMesh===!0){const m=u._multiDrawStarts,_=u._multiDrawCounts,x=u._multiDrawCount;let v=p===!0?f.array.BYTES_PER_ELEMENT:1;h.wireframe&&(v=u.geometry.attributes.position.count>65535?4:2);for(let S=0;S0){const d=this.get(e.camera),f=e.camera.cameras,p=e.getBindingGroup("cameraIndex");if(d.indexesGPU===void 0||d.indexesGPU.length!==f.length){const m=this.get(p),_=[],x=new Uint32Array([0,0,0,0]);for(let v=0,S=f.length;v(ee("WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new H_(e)));const n=new t(e);super(n,e),this.library=new HI,this.isWebGPURenderer=!0,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}}const qd={type:"change"},jp={type:"start"},Yp={type:"end"},ex=1e-6,Rt={NONE:-1,ROTATE:0,ZOOM:1,PAN:2,TOUCH_ROTATE:3,TOUCH_ZOOM_PAN:4},mu=new de,lr=new de,$I=new C,gu=new C,jd=new C,Wo=new Li,tx=new C,_u=new C,Yd=new C,xu=new C;class XI extends Ju{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:Ln.ROTATE,MIDDLE:Ln.DOLLY,RIGHT:Ln.PAN},this.target=new C,this.state=Rt.NONE,this.keyState=Rt.NONE,this._lastPosition=new C,this._lastZoom=1,this._touchZoomDistanceStart=0,this._touchZoomDistanceEnd=0,this._lastAngle=0,this._eye=new C,this._movePrev=new de,this._moveCurr=new de,this._lastAxis=new C,this._zoomStart=new de,this._zoomEnd=new de,this._panStart=new de,this._panEnd=new de,this._pointers=[],this._pointerPositions={},this._onPointerMove=jI.bind(this),this._onPointerDown=qI.bind(this),this._onPointerUp=YI.bind(this),this._onPointerCancel=KI.bind(this),this._onContextMenu=i3.bind(this),this._onMouseWheel=n3.bind(this),this._onKeyDown=QI.bind(this),this._onKeyUp=ZI.bind(this),this._onTouchStart=s3.bind(this),this._onTouchMove=r3.bind(this),this._onTouchEnd=o3.bind(this),this._onMouseDown=JI.bind(this),this._onMouseMove=e3.bind(this),this._onMouseUp=t3.bind(this),this._target0=this.target.clone(),this._position0=this.object.position.clone(),this._up0=this.object.up.clone(),this._zoom0=this.object.zoom,t!==null&&(this.connect(t),this.handleResize()),this.update()}connect(e){super.connect(e),window.addEventListener("keydown",this._onKeyDown),window.addEventListener("keyup",this._onKeyUp),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerCancel),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction="none"}disconnect(){window.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("keyup",this._onKeyUp),this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerCancel),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction=""}dispose(){this.disconnect()}handleResize(){const e=this.domElement.getBoundingClientRect(),t=this.domElement.ownerDocument.documentElement;this.screen.left=e.left+window.pageXOffset-t.clientLeft,this.screen.top=e.top+window.pageYOffset-t.clientTop,this.screen.width=e.width,this.screen.height=e.height}update(){this._eye.subVectors(this.object.position,this.target),this.noRotate||this._rotateCamera(),this.noZoom||this._zoomCamera(),this.noPan||this._panCamera(),this.object.position.addVectors(this.target,this._eye),this.object.isPerspectiveCamera?(this._checkDistances(),this.object.lookAt(this.target),this._lastPosition.distanceToSquared(this.object.position)>ex&&(this.dispatchEvent(qd),this._lastPosition.copy(this.object.position))):this.object.isOrthographicCamera?(this.object.lookAt(this.target),(this._lastPosition.distanceToSquared(this.object.position)>ex||this._lastZoom!==this.object.zoom)&&(this.dispatchEvent(qd),this._lastPosition.copy(this.object.position),this._lastZoom=this.object.zoom)):console.warn("THREE.TrackballControls: Unsupported camera type.")}reset(){this.state=Rt.NONE,this.keyState=Rt.NONE,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(qd),this._lastPosition.copy(this.object.position),this._lastZoom=this.object.zoom}_panCamera(){if(lr.copy(this._panEnd).sub(this._panStart),lr.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;lr.x*=e,lr.y*=t}lr.multiplyScalar(this._eye.length()*this.panSpeed),gu.copy(this._eye).cross(this.object.up).setLength(lr.x),gu.add($I.copy(this.object.up).setLength(lr.y)),this.object.position.add(gu),this.target.add(gu),this.staticMoving?this._panStart.copy(this._panEnd):this._panStart.add(lr.subVectors(this._panEnd,this._panStart).multiplyScalar(this.dynamicDampingFactor))}}_rotateCamera(){xu.set(this._moveCurr.x-this._movePrev.x,this._moveCurr.y-this._movePrev.y,0);let e=xu.length();e?(this._eye.copy(this.object.position).sub(this.target),tx.copy(this._eye).normalize(),_u.copy(this.object.up).normalize(),Yd.crossVectors(_u,tx).normalize(),_u.setLength(this._moveCurr.y-this._movePrev.y),Yd.setLength(this._moveCurr.x-this._movePrev.x),xu.copy(_u.add(Yd)),jd.crossVectors(xu,this._eye).normalize(),e*=this.rotateSpeed,Wo.setFromAxisAngle(jd,e),this._eye.applyQuaternion(Wo),this.object.up.applyQuaternion(Wo),this._lastAxis.copy(jd),this._lastAngle=e):!this.staticMoving&&this._lastAngle&&(this._lastAngle*=Math.sqrt(1-this.dynamicDampingFactor),this._eye.copy(this.object.position).sub(this.target),Wo.setFromAxisAngle(this._lastAxis,this._lastAngle),this._eye.applyQuaternion(Wo),this.object.up.applyQuaternion(Wo)),this._movePrev.copy(this._moveCurr)}_zoomCamera(){let e;this.state===Rt.TOUCH_ZOOM_PAN?(e=this._touchZoomDistanceStart/this._touchZoomDistanceEnd,this._touchZoomDistanceStart=this._touchZoomDistanceEnd,this.object.isPerspectiveCamera?this._eye.multiplyScalar(e):this.object.isOrthographicCamera?(this.object.zoom=Du.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,e!==1&&e>0&&(this.object.isPerspectiveCamera?this._eye.multiplyScalar(e):this.object.isOrthographicCamera?(this.object.zoom=Du.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 mu.set((e-this.screen.left)/this.screen.width,(t-this.screen.top)/this.screen.height),mu}_getMouseOnCircle(e,t){return mu.set((e-this.screen.width*.5-this.screen.left)/(this.screen.width*.5),(this.screen.height+2*(this.screen.top-t))/this.screen.width),mu}_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-=ii),i<-Math.PI?i+=ii:i>Math.PI&&(i-=ii),n<=i?this._spherical.theta=Math.max(n,Math.min(i,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(n+i)/2?Math.max(n,this._spherical.theta):Math.min(i,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?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 s=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const o=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),s=o!=this._spherical.radius}if(vn.setFromSpherical(this._spherical),vn.applyQuaternion(this._quatInverse),t.copy(this.target).add(vn),this.object.lookAt(this.target),this.enableDamping===!0?(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 o=null;if(this.object.isPerspectiveCamera){const a=vn.length();o=this._clampDistance(a*this._scale);const l=a-o;this.object.position.addScaledVector(this._dollyDirection,l),this.object.updateMatrixWorld(),s=!!l}else if(this.object.isOrthographicCamera){const a=new C(this._mouse.x,this._mouse.y,0);a.unproject(this.object);const l=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),s=l!==this.object.zoom;const c=new C(this._mouse.x,this._mouse.y,0);c.unproject(this.object),this.object.position.sub(c).add(a),this.object.updateMatrixWorld(),o=vn.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;o!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(o).add(this.object.position):(yu.origin.copy(this.object.position),yu.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(yu.direction))Kd||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Kd||this._lastTargetPosition.distanceToSquared(this.target)>Kd?(this.dispatchEvent(nx),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?ii/60*this.autoRotateSpeed*e:ii/60/60*this.autoRotateSpeed}_getZoomScale(e){const t=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){vn.setFromMatrixColumn(t,0),vn.multiplyScalar(-e),this._panOffset.add(vn)}_panUp(e,t){this.screenSpacePanning===!0?vn.setFromMatrixColumn(t,1):(vn.setFromMatrixColumn(t,0),vn.crossVectors(this.object.up,vn)),vn.multiplyScalar(e),this._panOffset.add(vn)}_pan(e,t){const n=this.domElement;if(this.object.isPerspectiveCamera){const i=this.object.position;vn.copy(i).sub(this.target);let s=vn.length();s*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*s/n.clientHeight,this.object.matrix),this._panUp(2*t*s/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(),i=e-n.left,s=t-n.top,o=n.width,a=n.height;this._mouse.x=i/o*2-1,this._mouse.y=-(s/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(ii*this._rotateDelta.x/t.clientHeight),this._rotateUp(ii*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(ii*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(-ii*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(ii*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(-ii*this.keyRotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0;break}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._rotateStart.set(n,i)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panStart.set(n,i)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,i=e.pageY-t.y,s=Math.sqrt(n*n+i*i);this._dollyStart.set(0,s)}_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(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{const n=this._getSecondPointerPosition(e),i=.5*(e.pageX+n.x),s=.5*(e.pageY+n.y);this._rotateEnd.set(i,s)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(ii*this._rotateDelta.x/t.clientHeight),this._rotateUp(ii*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),n=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panEnd.set(n,i)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){const t=this._getSecondPointerPosition(e),n=e.pageX-t.x,i=e.pageY-t.y,s=Math.sqrt(n*n+i*i);this._dollyEnd.set(0,s),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 o=(e.pageX+t.x)*.5,a=(e.pageY+t.y)*.5;this._updateZoomParameters(o,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;tsx||8*(1-this._lastQuaternion.dot(t.quaternion))>sx)&&(this.dispatchEvent(S3),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 T3(r){if(!(r.altKey||this.enabled===!1)){switch(r.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;break}this._updateMovementVector(),this._updateRotationVector()}}function M3(r){if(this.enabled!==!1){switch(r.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;break}this._updateMovementVector(),this._updateRotationVector()}}function E3(r){if(this.enabled!==!1)if(this.dragToLook)this._status++;else{switch(r.button){case 0:this._moveState.forward=1;break;case 2:this._moveState.back=1;break}this._updateMovementVector()}}function A3(r){if(this.enabled!==!1&&(!this.dragToLook||this._status>0)){const e=this._getContainerDimensions(),t=e.size[0]/2,n=e.size[1]/2;this._moveState.yawLeft=-(r.pageX-e.offset[0]-t)/t,this._moveState.pitchDown=(r.pageY-e.offset[1]-n)/n,this._updateRotationVector()}}function R3(r){if(this.enabled!==!1){if(this.dragToLook)this._status--,this._moveState.yawLeft=this._moveState.pitchDown=0;else{switch(r.button){case 0:this._moveState.forward=0;break;case 2:this._moveState.back=0;break}this._updateMovementVector()}this._updateRotationVector()}}function w3(){this.enabled!==!1&&(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 C3(r){this.enabled!==!1&&r.preventDefault()}const N3={name:"CopyShader",uniforms:{tDiffuse:{value:null},opacity:{value:1}},vertexShader:` varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); }`,fragmentShader:` uniform float opacity; uniform sampler2D tDiffuse; varying vec2 vUv; void main() { vec4 texel = texture2D( tDiffuse, vUv ); gl_FragColor = opacity * texel; }`};class gh{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 P3=new Va(-1,1,1,-1,0,1);class D3 extends Pn{constructor(){super(),this.setAttribute("position",new sn([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new sn([0,2,0,0,2,0],2))}}const L3=new D3;class U3{constructor(e){this._mesh=new gn(L3,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,P3)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}}class F3 extends gh{constructor(e,t="tDiffuse"){super(),this.textureID=t,this.uniforms=null,this.material=null,e instanceof Ui?(this.uniforms=e.uniforms,this.material=e):e&&(this.uniforms=Lx.clone(e.uniforms),this.material=new Ui({name:e.name!==void 0?e.name:"unspecified",defines:Object.assign({},e.defines),uniforms:this.uniforms,vertexShader:e.vertexShader,fragmentShader:e.fragmentShader})),this._fsQuad=new U3(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 ox extends gh{constructor(e,t){super(),this.scene=e,this.camera=t,this.clear=!0,this.needsSwap=!1,this.inverse=!1}render(e,t,n){const i=e.getContext(),s=e.state;s.buffers.color.setMask(!1),s.buffers.depth.setMask(!1),s.buffers.color.setLocked(!0),s.buffers.depth.setLocked(!0);let o,a;this.inverse?(o=0,a=1):(o=1,a=0),s.buffers.stencil.setTest(!0),s.buffers.stencil.setOp(i.REPLACE,i.REPLACE,i.REPLACE),s.buffers.stencil.setFunc(i.ALWAYS,o,4294967295),s.buffers.stencil.setClear(a),s.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),s.buffers.color.setLocked(!1),s.buffers.depth.setLocked(!1),s.buffers.color.setMask(!0),s.buffers.depth.setMask(!0),s.buffers.stencil.setLocked(!1),s.buffers.stencil.setFunc(i.EQUAL,1,4294967295),s.buffers.stencil.setOp(i.KEEP,i.KEEP,i.KEEP),s.buffers.stencil.setLocked(!0)}}class I3 extends gh{constructor(){super(),this.needsSwap=!1}render(e){e.state.buffers.stencil.setLocked(!1),e.state.buffers.stencil.setTest(!1)}}class B3{constructor(e,t){if(this.renderer=e,this._pixelRatio=e.getPixelRatio(),t===void 0){const n=e.getSize(new de);this._width=n.width,this._height=n.height,t=new $i(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:en}),t.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 F3(N3),this.copyPass.material.blending=Cn,this.timer=new Vx}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);t!==-1&&this.passes.splice(t,1)}isLastEnabledPass(e){for(let t=e+1;t"u")){var n=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");i.type="text/css",t==="top"&&n.firstChild?n.insertBefore(i,n.firstChild):n.appendChild(i),i.styleSheet?i.styleSheet.cssText=r:i.appendChild(document.createTextNode(r))}}var G3=`.scene-nav-info { position: absolute; bottom: 5px; width: 100%; text-align: center; color: slategrey; opacity: 0.7; font-size: 10px; font-family: sans-serif; pointer-events: none; user-select: none; } .scene-container canvas:focus { outline: none; }`;k3(G3);function Nf(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,n=Array(e);t=e.pointerRaycasterThrottleMs){e.lastRaycasterCheck=t;var n=null;if(e.hoverDuringDrag||!e.isPointerDragging){var i=this.intersectingObjects(e.pointerPos.x,e.pointerPos.y);e.hoverOrderComparator&&i.sort(function(o,a){return e.hoverOrderComparator(o.object,a.object)});var s=i.find(function(o){return e.hoverFilter(o.object)})||null;n=s?s.object:null,e.intersection=s||null}n!==e.hoverObj&&(e.onHover(n,e.hoverObj,e.intersection),e.tooltip.content(n&>(e.tooltipContent)(n,e.intersection)||null),e.hoverObj=n)}e.tweenGroup.update()}return this},getPointerPos:function(e){var t=e.pointerPos,n=t.x,i=t.y;return{x:n,y:i}},cameraPosition:function(e,t,n,i){var s=e.camera;if(t&&e.initialised){var o,a,l=t,c=n||{x:0,y:0,z:0};if((o=e.povPosTween)===null||o===void 0||o.end(),(a=e.povTgtTween)===null||a===void 0||a.end(),!i)d(l),f(c);else{var u=Object.assign({},s.position),h=p();e.tweenGroup.add(e.povPosTween=new um(u).to(l,i).easing(hm.Quadratic.Out).onUpdate(d).onComplete(function(){e.povPosTween=void 0,e.tweenGroup.remove(this)}).start()),e.tweenGroup.add(e.povTgtTween=new um(h).to(c,i/3).easing(hm.Quadratic.Out).onUpdate(f).onComplete(function(){e.povTgtTween=void 0,e.tweenGroup.remove(this)}).start())}return this}return Object.assign({},s.position,{lookAt:p()});function d(g){var m=g.x,_=g.y,x=g.z;m!==void 0&&(s.position.x=m),_!==void 0&&(s.position.y=_),x!==void 0&&(s.position.z=x)}function f(g){var m=new tn.Vector3(g.x,g.y,g.z);e.controls.enabled&&e.controls.target?e.controls.target=m:s.lookAt(m)}function p(){return Object.assign(new tn.Vector3(0,0,-1e3).applyQuaternion(s.quaternion).add(s.position))}},zoomToFit:function(e){for(var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:10,i=arguments.length,s=new Array(i>3?i-3:0),o=3;o2&&arguments[2]!==void 0?arguments[2]:0,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:10,s=e.camera;if(t){var o=new tn.Vector3(0,0,0),a=Math.max.apply(Math,Wr(Object.entries(t).map(function(f){var p=j3(f,2),g=p[0],m=p[1];return Math.max.apply(Math,Wr(m.map(function(_){return Math.abs(o[g]-_)})))})))*2,l=(1-i*2/e.height)*s.fov,c=a/Math.atan(l*Math.PI/180),u=c/s.aspect,h=Math.max(c,u);if(h>0){var d=o.clone().sub(s.position).normalize().multiplyScalar(-h);this.cameraPosition(d,o,n)}}return this},getBbox:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:function(){return!0},n=new tn.Box3(new tn.Vector3(0,0,0),new tn.Vector3(0,0,0)),i=e.objects.filter(t);return i.length?(i.forEach(function(s){return n.expandByObject(s)}),Object.assign.apply(Object,Wr(["x","y","z"].map(function(s){return H3({},s,[n.min[s],n.max[s]])})))):null},getScreenCoords:function(e,t,n,i){var s=new tn.Vector3(t,n,i);return s.project(this.camera()),{x:(s.x+1)*e.width/2,y:-(s.y-1)*e.height/2}},getSceneCoords:function(e,t,n){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0,s=new tn.Vector2(t/e.width*2-1,-(n/e.height)*2+1),o=new tn.Raycaster;return o.setFromCamera(s,e.camera),Object.assign({},o.ray.at(i,new tn.Vector3))},intersectingObjects:function(e,t,n){var i=new tn.Vector2(t/e.width*2-1,-(n/e.height)*2+1),s=new tn.Raycaster;return s.params.Line.threshold=e.lineHoverPrecision,s.params.Points.threshold=e.pointsHoverPrecision,s.setFromCamera(i,e.camera),s.intersectObjects(e.objects,!0)},renderer:function(e){return e.renderer},scene:function(e){return e.scene},camera:function(e){return e.camera},postProcessingComposer:function(e){return e.postProcessingComposer},controls:function(e){return e.controls},tbControls:function(e){return e.controls},_destructor:function(e){var t,n,i;Z3(e.scene),(t=e.controls)===null||t===void 0||t.dispose(),(n=e.renderer)===null||n===void 0||n.dispose(),(i=e.postProcessingComposer)===null||i===void 0||i.dispose()}},stateInit:function(){return{scene:new tn.Scene,camera:new tn.PerspectiveCamera,timer:new tn.Timer,tweenGroup:new Wv,lastRaycasterCheck:0}},init:function(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=n.controlType,s=i===void 0?"trackball":i,o=n.useWebGPU,a=o===void 0?!1:o,l=n.rendererConfig,c=l===void 0?{}:l,u=n.extraRenderers,h=u===void 0?[]:u,d=n.waitForLoadComplete,f=d===void 0?!0:d;e.innerHTML="",e.appendChild(t.container=document.createElement("div")),t.container.className="scene-container",t.container.style.position="relative",t.container.appendChild(t.navInfo=document.createElement("div")),t.navInfo.className="scene-nav-info",t.navInfo.textContent={orbit:"Left-click: rotate, Mouse-wheel/middle-click: zoom, Right-click: pan",trackball:"Left-click: rotate, Mouse-wheel/middle-click: zoom, Right-click: pan",fly:"WASD: move, R|F: up | down, Q|E: roll, up|down: pitch, left|right: yaw"}[s]||"",t.navInfo.style.display=t.showNavInfo?null:"none",t.tooltip=new Hv(t.container),t.pointerPos=new tn.Vector2,t.pointerPos.x=-2,t.pointerPos.y=-2,["pointermove","pointerdown"].forEach(function(p){return t.container.addEventListener(p,function(g){if(p==="pointerdown"&&(t.isPointerPressed=!0),!t.isPointerDragging&&g.type==="pointermove"&&(g.pressure>0||t.isPointerPressed)&&(g.pointerType==="mouse"||g.movementX===void 0||[g.movementX,g.movementY].some(function(x){return Math.abs(x)>1}))&&(t.isPointerDragging=!0),t.enablePointerInteraction){var m=_(t.container);t.pointerPos.x=g.pageX-m.left,t.pointerPos.y=g.pageY-m.top}function _(x){var v=x.getBoundingClientRect(),S=window.pageXOffset||document.documentElement.scrollLeft,E=window.pageYOffset||document.documentElement.scrollTop;return{top:v.top+E,left:v.left+S}}},{passive:!0})}),t.container.addEventListener("pointerup",function(p){t.isPointerPressed&&(t.isPointerPressed=!1,!(t.isPointerDragging&&(t.isPointerDragging=!1,!t.clickAfterDrag))&&requestAnimationFrame(function(){p.button===0&&t.onClick(t.hoverObj||null,p,t.intersection),p.button===2&&t.onRightClick&&t.onRightClick(t.hoverObj||null,p,t.intersection)}))},{passive:!0,capture:!0}),t.container.addEventListener("contextmenu",function(p){t.onRightClick&&p.preventDefault()}),t.renderer=new(a?WI:tn.WebGLRenderer)(Object.assign({antialias:!0,alpha:!0},c)),t.renderer.setPixelRatio(Math.min(2,window.devicePixelRatio)),t.container.appendChild(t.renderer.domElement),t.extraRenderers=h,t.extraRenderers.forEach(function(p){p.domElement.style.position="absolute",p.domElement.style.top="0px",p.domElement.style.pointerEvents="none",t.container.appendChild(p.domElement)}),t.postProcessingComposer=new B3(t.renderer),t.postProcessingComposer.addPass(new O3(t.scene,t.camera)),t.controls=new{trackball:XI,orbit:l3,fly:b3}[s](t.camera,t.renderer.domElement),s==="fly"&&(t.controls.movementSpeed=300,t.controls.rollSpeed=Math.PI/6,t.controls.dragToLook=!0),(s==="trackball"||s==="orbit")&&(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(Wr(t.extraRenderers)).forEach(function(p){return p.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 tn.Mesh),t.skysphere.visible=!1,t.loadComplete=t.scene.visible=!f,window.scene=t.scene},update:function(e,t){if(e.width&&e.height&&(t.hasOwnProperty("width")||t.hasOwnProperty("height"))){var n,i=e.width,s=e.height;e.container.style.width="".concat(i,"px"),e.container.style.height="".concat(s,"px"),[e.renderer,e.postProcessingComposer].concat(Wr(e.extraRenderers)).forEach(function(f){return f.setSize(i,s)}),e.camera.aspect=i/s;var o=e.viewOffset.slice(0,2);o.some(function(f){return f})&&(n=e.camera).setViewOffset.apply(n,[i,s].concat(Wr(o),[i,s])),e.camera.updateProjectionMatrix()}if(t.hasOwnProperty("viewOffset")){var a,l=e.width,c=e.height,u=e.viewOffset.slice(0,2);u.some(function(f){return f})?(a=e.camera).setViewOffset.apply(a,[l,c].concat(Wr(u),[l,c])):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=e.skyRadius*2.5,e.camera.updateProjectionMatrix(),e.skysphere.geometry=new tn.SphereGeometry(e.skyRadius)),t.hasOwnProperty("backgroundColor")){var h=Vv(e.backgroundColor).alpha;h===void 0&&(h=1),e.renderer.setClearColor(new tn.Color(zv(1,e.backgroundColor)),h)}t.hasOwnProperty("backgroundImageUrl")&&(e.backgroundImageUrl?new tn.TextureLoader().load(e.backgroundImageUrl,function(f){f.colorSpace=tn.SRGBColorSpace,e.skysphere.material=new tn.MeshBasicMaterial({map:f,side:tn.BackSide}),e.skysphere.visible=!0,e.onBackgroundImageLoaded&&setTimeout(e.onBackgroundImageLoaded),!e.loadComplete&&d()}):(e.skysphere.visible=!1,e.skysphere.material.map=null,!e.loadComplete&&d())),t.hasOwnProperty("showNavInfo")&&(e.navInfo.style.display=e.showNavInfo?null:"none"),t.hasOwnProperty("lights")&&((t.lights||[]).forEach(function(f){return e.scene.remove(f)}),e.lights.forEach(function(f){return e.scene.add(f)})),t.hasOwnProperty("objects")&&((t.objects||[]).forEach(function(f){return e.scene.remove(f)}),e.objects.forEach(function(f){return e.scene.add(f)}));function d(){e.loadComplete=e.scene.visible=!0}}});function Q3(r,e){e===void 0&&(e={});var t=e.insertAt;if(!(typeof document>"u")){var n=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");i.type="text/css",t==="top"&&n.firstChild?n.insertBefore(i,n.firstChild):n.appendChild(i),i.styleSheet?i.styleSheet.cssText=r:i.appendChild(document.createTextNode(r))}}var J3=`.graph-info-msg { top: 50%; width: 100%; text-align: center; color: lavender; opacity: 0.7; font-size: 22px; position: absolute; font-family: Sans-serif; } .scene-container .clickable { cursor: pointer; } .scene-container .grabbable { cursor: move; cursor: grab; cursor: -moz-grab; cursor: -webkit-grab; } .scene-container .grabbable:active { cursor: grabbing; cursor: -moz-grabbing; cursor: -webkit-grabbing; }`;Q3(J3);function Pf(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,n=Array(e);t1?a-1:0),c=1;c3?s-3:0),a=3;an).backgroundColor(i).nodeThreeObject(l=>{const c=l.color??s;return l.color=c,!1}).nodeThreeObjectExtend(!0).onNodeHover((l,c)=>{if(l){const u=r.data.nodes.find(h=>h.id===l.id);r.onHover(u)}c&&r.onHover(void 0)}).cooldownTicks(100),e}export{y2 as render};