4624 lines
1.1 MiB
Plaintext
4624 lines
1.1 MiB
Plaintext
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<o;s++)i[s].call(this,e);e.target=null}}}const Gn=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];let pm=1234567;const Sl=Math.PI/180,ao=180/Math.PI;function Vs(){const r=Math.random()*4294967295|0,e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0;return(Gn[r&255]+Gn[r>>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;o<s.length;o++)s[o]=zs(s[o]/255)*255;return n.putImageData(i,0,0),t}else if(e.data){const t=e.data.slice(0);for(let n=0;n<t.length;n++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[n]=Math.floor(zs(t[n]/255)*255):t[n]=zs(t[n]);return{data:t,width:e.width,height:e.height}}else return ee("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let DS=0;class ip{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:DS++}),this.uuid=Vs(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){const t=this.data;return typeof HTMLVideoElement<"u"&&t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight,0):typeof VideoFrame<"u"&&t instanceof VideoFrame?e.set(t.displayWidth,t.displayHeight,0):t!==null?e.set(t.width,t.height,t.depth||0):e.set(0,0,0),e}set needsUpdate(e){e===!0&&this.version++}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];const n={uuid:this.uuid,url:""},i=this.data;if(i!==null){let s;if(Array.isArray(i)){s=[];for(let o=0,a=i.length;o<a;o++)i[o].isDataTexture?s.push(Th(i[o].image)):s.push(Th(i[o]))}else s=Th(i);n.url=s}return t||(e.images[this.uuid]=n),n}}function Th(r){return typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&r instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&r instanceof ImageBitmap?PS.getDataURL(r):r.data?{data:Array.from(r.data),width:r.width,height:r.height,type:r.data.constructor.name}:(ee("Texture: Unable to serialize Texture."),{})}let LS=0;const Mh=new C;class pn extends Ii{constructor(e=pn.DEFAULT_IMAGE,t=pn.DEFAULT_MAPPING,n=ai,i=ai,s=Ut,o=li,a=an,l=$t,c=pn.DEFAULT_ANISOTROPY,u=ri){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:LS++}),this.uuid=Vs(),this.name="",this.source=new ip(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=n,this.wrapT=i,this.magFilter=s,this.minFilter=o,this.anisotropy=c,this.format=a,this.internalFormat=null,this.type=l,this.offset=new de(0,0),this.repeat=new de(1,1),this.center=new de(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new Ke,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=u,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(e&&e.depth&&e.depth>1),this.pmremVersion=0,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;a<o;a++)this.textures[a]=s.clone(),this.textures[a].isRenderTargetTexture=!0,this.textures[a].renderTarget=this;this._setTextureOptions(n),this.depthBuffer=n.depthBuffer,this.stencilBuffer=n.stencilBuffer,this.resolveDepthBuffer=n.resolveDepthBuffer,this.resolveStencilBuffer=n.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=n.depthTexture,this.samples=n.samples,this.multiview=n.multiview}_setTextureOptions(e={}){const t={minFilter:Ut,generateMipmaps:!1,flipY:!1,internalFormat:null};e.mapping!==void 0&&(t.mapping=e.mapping),e.wrapS!==void 0&&(t.wrapS=e.wrapS),e.wrapT!==void 0&&(t.wrapT=e.wrapT),e.wrapR!==void 0&&(t.wrapR=e.wrapR),e.magFilter!==void 0&&(t.magFilter=e.magFilter),e.minFilter!==void 0&&(t.minFilter=e.minFilter),e.format!==void 0&&(t.format=e.format),e.type!==void 0&&(t.type=e.type),e.anisotropy!==void 0&&(t.anisotropy=e.anisotropy),e.colorSpace!==void 0&&(t.colorSpace=e.colorSpace),e.flipY!==void 0&&(t.flipY=e.flipY),e.generateMipmaps!==void 0&&(t.generateMipmaps=e.generateMipmaps),e.internalFormat!==void 0&&(t.internalFormat=e.internalFormat);for(let n=0;n<this.textures.length;n++)this.textures[n].setValues(t)}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){this._depthTexture!==null&&(this._depthTexture.renderTarget=null),e!==null&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,n=1){if(this.width!==e||this.height!==t||this.depth!==n){this.width=e,this.height=t,this.depth=n;for(let i=0,s=this.textures.length;i<s;i++)this.textures[i].image.width=e,this.textures[i].image.height=t,this.textures[i].image.depth=n,this.textures[i].isData3DTexture!==!0&&(this.textures[i].isArrayTexture=this.textures[i].image.depth>1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,n=e.textures.length;t<n;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;const i=Object.assign({},e.textures[t].image);this.textures[t].source=new ip(i)}return this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,e.depthTexture!==null&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this.multiview=e.multiview,this}dispose(){this.dispatchEvent({type:"dispose"})}}class $i extends Lr{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}}class sp extends pn{constructor(e=null,t=1,n=1,i=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:n,depth:i},this.magFilter=bt,this.minFilter=bt,this.wrapR=ai,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class US extends pn{constructor(e=null,t=1,n=1,i=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:n,depth:i},this.magFilter=bt,this.minFilter=bt,this.wrapR=ai,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}const ju=class ju{constructor(e,t,n,i,s,o,a,l,c,u,h,d,f,p,g,m){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,n,i,s,o,a,l,c,u,h,d,f,p,g,m)}set(e,t,n,i,s,o,a,l,c,u,h,d,f,p,g,m){const _=this.elements;return _[0]=e,_[4]=t,_[8]=n,_[12]=i,_[1]=s,_[5]=o,_[9]=a,_[13]=l,_[2]=c,_[6]=u,_[10]=h,_[14]=d,_[3]=f,_[7]=p,_[11]=g,_[15]=m,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new ju().fromArray(this.elements)}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){const t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return this.determinant()===0?(e.set(1,0,0),t.set(0,1,0),n.set(0,0,1),this):(e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this)}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){if(e.determinant()===0)return this.identity();const t=this.elements,n=e.elements,i=1/Ro.setFromMatrixColumn(e,0).length(),s=1/Ro.setFromMatrixColumn(e,1).length(),o=1/Ro.setFromMatrixColumn(e,2).length();return t[0]=n[0]*i,t[1]=n[1]*i,t[2]=n[2]*i,t[3]=0,t[4]=n[4]*s,t[5]=n[5]*s,t[6]=n[6]*s,t[7]=0,t[8]=n[8]*o,t[9]=n[9]*o,t[10]=n[10]*o,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,n=e.x,i=e.y,s=e.z,o=Math.cos(n),a=Math.sin(n),l=Math.cos(i),c=Math.sin(i),u=Math.cos(s),h=Math.sin(s);if(e.order==="XYZ"){const d=o*u,f=o*h,p=a*u,g=a*h;t[0]=l*u,t[4]=-l*h,t[8]=c,t[1]=f+p*c,t[5]=d-g*c,t[9]=-a*l,t[2]=g-d*c,t[6]=p+f*c,t[10]=o*l}else if(e.order==="YXZ"){const d=l*u,f=l*h,p=c*u,g=c*h;t[0]=d+g*a,t[4]=p*a-f,t[8]=o*c,t[1]=o*h,t[5]=o*u,t[9]=-a,t[2]=f*a-p,t[6]=g+d*a,t[10]=o*l}else if(e.order==="ZXY"){const d=l*u,f=l*h,p=c*u,g=c*h;t[0]=d-g*a,t[4]=-o*h,t[8]=p+f*a,t[1]=f+p*a,t[5]=o*u,t[9]=g-d*a,t[2]=-o*c,t[6]=a,t[10]=o*l}else if(e.order==="ZYX"){const d=o*u,f=o*h,p=a*u,g=a*h;t[0]=l*u,t[4]=p*c-f,t[8]=d*c+g,t[1]=l*h,t[5]=g*c+d,t[9]=f*c-p,t[2]=-c,t[6]=a*l,t[10]=o*l}else if(e.order==="YZX"){const d=o*l,f=o*c,p=a*l,g=a*c;t[0]=l*u,t[4]=g-d*h,t[8]=p*h+f,t[1]=h,t[5]=o*u,t[9]=-a*u,t[2]=-c*u,t[6]=f*h+p,t[10]=d-g*h}else if(e.order==="XZY"){const d=o*l,f=o*c,p=a*l,g=a*c;t[0]=l*u,t[4]=-h,t[8]=c*u,t[1]=d*h+g,t[5]=o*u,t[9]=f*h-p,t[2]=p*h-f,t[6]=a*u,t[10]=g*h+d}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(FS,e,IS)}lookAt(e,t,n){const i=this.elements;return pi.subVectors(e,t),pi.lengthSq()===0&&(pi.z=1),pi.normalize(),Qs.crossVectors(n,pi),Qs.lengthSq()===0&&(Math.abs(n.z)===1?pi.x+=1e-4:pi.z+=1e-4,pi.normalize(),Qs.crossVectors(n,pi)),Qs.normalize(),vc.crossVectors(pi,Qs),i[0]=Qs.x,i[4]=vc.x,i[8]=pi.x,i[1]=Qs.y,i[5]=vc.y,i[9]=pi.y,i[2]=Qs.z,i[6]=vc.z,i[10]=pi.z,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[4],l=n[8],c=n[12],u=n[1],h=n[5],d=n[9],f=n[13],p=n[2],g=n[6],m=n[10],_=n[14],x=n[3],v=n[7],S=n[11],E=n[15],T=i[0],A=i[4],y=i[8],R=i[12],P=i[1],N=i[5],U=i[9],G=i[13],V=i[2],L=i[6],B=i[10],H=i[14],ie=i[3],ce=i[7],ve=i[11],Ce=i[15];return s[0]=o*T+a*P+l*V+c*ie,s[4]=o*A+a*N+l*L+c*ce,s[8]=o*y+a*U+l*B+c*ve,s[12]=o*R+a*G+l*H+c*Ce,s[1]=u*T+h*P+d*V+f*ie,s[5]=u*A+h*N+d*L+f*ce,s[9]=u*y+h*U+d*B+f*ve,s[13]=u*R+h*G+d*H+f*Ce,s[2]=p*T+g*P+m*V+_*ie,s[6]=p*A+g*N+m*L+_*ce,s[10]=p*y+g*U+m*B+_*ve,s[14]=p*R+g*G+m*H+_*Ce,s[3]=x*T+v*P+S*V+E*ie,s[7]=x*A+v*N+S*L+E*ce,s[11]=x*y+v*U+S*B+E*ve,s[15]=x*R+v*G+S*H+E*Ce,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[4],i=e[8],s=e[12],o=e[1],a=e[5],l=e[9],c=e[13],u=e[2],h=e[6],d=e[10],f=e[14],p=e[3],g=e[7],m=e[11],_=e[15],x=l*f-c*d,v=a*f-c*h,S=a*d-l*h,E=o*f-c*u,T=o*d-l*u,A=o*h-a*u;return t*(g*x-m*v+_*S)-n*(p*x-m*E+_*T)+i*(p*v-g*E+_*A)-s*(p*S-g*T+m*A)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){const i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=t,i[14]=n),this}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=e[9],d=e[10],f=e[11],p=e[12],g=e[13],m=e[14],_=e[15],x=t*a-n*o,v=t*l-i*o,S=t*c-s*o,E=n*l-i*a,T=n*c-s*a,A=i*c-s*l,y=u*g-h*p,R=u*m-d*p,P=u*_-f*p,N=h*m-d*g,U=h*_-f*g,G=d*_-f*m,V=x*G-v*U+S*N+E*P-T*R+A*y;if(V===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const L=1/V;return e[0]=(a*G-l*U+c*N)*L,e[1]=(i*U-n*G-s*N)*L,e[2]=(g*A-m*T+_*E)*L,e[3]=(d*T-h*A-f*E)*L,e[4]=(l*P-o*G-c*R)*L,e[5]=(t*G-i*P+s*R)*L,e[6]=(m*S-p*A-_*v)*L,e[7]=(u*A-d*S+f*v)*L,e[8]=(o*U-a*P+c*y)*L,e[9]=(n*P-t*U-s*y)*L,e[10]=(p*T-g*S+_*x)*L,e[11]=(h*S-u*T-f*x)*L,e[12]=(a*R-o*N-l*y)*L,e[13]=(t*N-n*R+i*y)*L,e[14]=(g*v-p*E-m*x)*L,e[15]=(u*E-h*v+d*x)*L,this}scale(e){const t=this.elements,n=e.x,i=e.y,s=e.z;return t[0]*=n,t[4]*=i,t[8]*=s,t[1]*=n,t[5]*=i,t[9]*=s,t[2]*=n,t[6]*=i,t[10]*=s,t[3]*=n,t[7]*=i,t[11]*=s,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,i))}makeTranslation(e,t,n){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const n=Math.cos(t),i=Math.sin(t),s=1-n,o=e.x,a=e.y,l=e.z,c=s*o,u=s*a;return this.set(c*o+n,c*a-i*l,c*l+i*a,0,c*a+i*l,u*a+n,u*l-i*o,0,c*l-i*a,u*l+i*o,s*l*l+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,i,s,o){return this.set(1,n,s,0,e,1,o,0,t,i,1,0,0,0,0,1),this}compose(e,t,n){const i=this.elements,s=t._x,o=t._y,a=t._z,l=t._w,c=s+s,u=o+o,h=a+a,d=s*c,f=s*u,p=s*h,g=o*u,m=o*h,_=a*h,x=l*c,v=l*u,S=l*h,E=n.x,T=n.y,A=n.z;return i[0]=(1-(g+_))*E,i[1]=(f+S)*E,i[2]=(p-v)*E,i[3]=0,i[4]=(f-S)*T,i[5]=(1-(d+_))*T,i[6]=(m+x)*T,i[7]=0,i[8]=(p+v)*A,i[9]=(m-x)*A,i[10]=(1-(d+g))*A,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,t,n){const i=this.elements;e.x=i[12],e.y=i[13],e.z=i[14];const s=this.determinant();if(s===0)return n.set(1,1,1),t.identity(),this;let o=Ro.set(i[0],i[1],i[2]).length();const a=Ro.set(i[4],i[5],i[6]).length(),l=Ro.set(i[8],i[9],i[10]).length();s<0&&(o=-o),Bi.copy(this);const c=1/o,u=1/a,h=1/l;return Bi.elements[0]*=c,Bi.elements[1]*=c,Bi.elements[2]*=c,Bi.elements[4]*=u,Bi.elements[5]*=u,Bi.elements[6]*=u,Bi.elements[8]*=h,Bi.elements[9]*=h,Bi.elements[10]*=h,t.setFromRotationMatrix(Bi),n.x=o,n.y=a,n.z=l,this}makePerspective(e,t,n,i,s,o,a=ti,l=!1){const c=this.elements,u=2*s/(t-e),h=2*s/(n-i),d=(t+e)/(t-e),f=(n+i)/(n-i);let p,g;if(l)p=s/(o-s),g=o*s/(o-s);else if(a===ti)p=-(o+s)/(o-s),g=-2*o*s/(o-s);else if(a===xs)p=-o/(o-s),g=-o*s/(o-s);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);return c[0]=u,c[4]=0,c[8]=d,c[12]=0,c[1]=0,c[5]=h,c[9]=f,c[13]=0,c[2]=0,c[6]=0,c[10]=p,c[14]=g,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,n,i,s,o,a=ti,l=!1){const c=this.elements,u=2/(t-e),h=2/(n-i),d=-(t+e)/(t-e),f=-(n+i)/(n-i);let p,g;if(l)p=1/(o-s),g=o/(o-s);else if(a===ti)p=-2/(o-s),g=-(o+s)/(o-s);else if(a===xs)p=-1/(o-s),g=-s/(o-s);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);return c[0]=u,c[4]=0,c[8]=0,c[12]=d,c[1]=0,c[5]=h,c[9]=0,c[13]=f,c[2]=0,c[6]=0,c[10]=p,c[14]=g,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){const t=this.elements,n=e.elements;for(let i=0;i<16;i++)if(t[i]!==n[i])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}};ju.prototype.isMatrix4=!0;let dt=ju;const Ro=new C,Bi=new dt,FS=new C(0,0,0),IS=new C(1,1,1),Qs=new C,vc=new C,pi=new C,xm=new dt,ym=new Li;class ys{constructor(e=0,t=0,n=0,i=ys.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=n,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,n,i=this._order){return this._x=e,this._y=t,this._z=n,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){const i=e.elements,s=i[0],o=i[4],a=i[8],l=i[1],c=i[5],u=i[9],h=i[2],d=i[6],f=i[10];switch(t){case"XYZ":this._y=Math.asin(ot(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-u,f),this._z=Math.atan2(-o,s)):(this._x=Math.atan2(d,c),this._z=0);break;case"YXZ":this._x=Math.asin(-ot(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(a,f),this._z=Math.atan2(l,c)):(this._y=Math.atan2(-h,s),this._z=0);break;case"ZXY":this._x=Math.asin(ot(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-h,f),this._z=Math.atan2(-o,c)):(this._y=0,this._z=Math.atan2(l,s));break;case"ZYX":this._y=Math.asin(-ot(h,-1,1)),Math.abs(h)<.9999999?(this._x=Math.atan2(d,f),this._z=Math.atan2(l,s)):(this._x=0,this._z=Math.atan2(-o,c));break;case"YZX":this._z=Math.asin(ot(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-u,c),this._y=Math.atan2(-h,s)):(this._x=0,this._y=Math.atan2(a,f));break;case"XZY":this._z=Math.asin(-ot(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(d,c),this._y=Math.atan2(a,s)):(this._x=Math.atan2(-u,f),this._y=0);break;default:ee("Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,n===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return xm.makeRotationFromQuaternion(e),this.setFromRotationMatrix(xm,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return ym.setFromEuler(this),this.setFromQuaternion(ym,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}ys.DEFAULT_ORDER="XYZ";class rp{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return(this.mask&(1<<e|0))!==0}}let BS=0;const vm=new C,wo=new Li,As=new dt,Sc=new C,Za=new C,OS=new C,kS=new Li,Sm=new C(1,0,0),bm=new C(0,1,0),Tm=new C(0,0,1),Mm={type:"added"},GS={type:"removed"},Co={type:"childadded",child:null},Eh={type:"childremoved",child:null};class mn extends Ii{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:BS++}),this.uuid=Vs(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=mn.DEFAULT_UP.clone();const e=new C,t=new ys,n=new Li,i=new C(1,1,1);function s(){n.setFromEuler(t,!1)}function o(){t.setFromQuaternion(n,void 0,!1)}t._onChange(s),n._onChange(o),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:t},quaternion:{configurable:!0,enumerable:!0,value:n},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new dt},normalMatrix:{value:new Ke}}),this.matrix=new dt,this.matrixWorld=new dt,this.matrixAutoUpdate=mn.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=mn.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new rp,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.static=!1,this.userData={},this.pivot=null}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return wo.setFromAxisAngle(e,t),this.quaternion.multiply(wo),this}rotateOnWorldAxis(e,t){return wo.setFromAxisAngle(e,t),this.quaternion.premultiply(wo),this}rotateX(e){return this.rotateOnAxis(Sm,e)}rotateY(e){return this.rotateOnAxis(bm,e)}rotateZ(e){return this.rotateOnAxis(Tm,e)}translateOnAxis(e,t){return vm.copy(e).applyQuaternion(this.quaternion),this.position.add(vm.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(Sm,e)}translateY(e){return this.translateOnAxis(bm,e)}translateZ(e){return this.translateOnAxis(Tm,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(As.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?Sc.copy(e):Sc.set(e,t,n);const i=this.parent;this.updateWorldMatrix(!0,!1),Za.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?As.lookAt(Za,Sc,this.up):As.lookAt(Sc,Za,this.up),this.quaternion.setFromRotationMatrix(As),i&&(As.extractRotation(i.matrixWorld),wo.setFromRotationMatrix(As),this.quaternion.premultiply(wo.invert()))}add(e){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.add(arguments[t]);return this}return e===this?(ne("Object3D.add: object can't be added as a child of itself.",e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(Mm),Co.child=e,this.dispatchEvent(Co),Co.child=null):ne("Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let n=0;n<arguments.length;n++)this.remove(arguments[n]);return this}const t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(GS),Eh.child=e,this.dispatchEvent(Eh),Eh.child=null),this}removeFromParent(){const e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),As.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),As.multiply(e.parent.matrixWorld)),e.applyMatrix4(As),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(Mm),Co.child=e,this.dispatchEvent(Co),Co.child=null,this}getObjectById(e){return this.getObjectByProperty("id",e)}getObjectByName(e){return this.getObjectByProperty("name",e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let n=0,i=this.children.length;n<i;n++){const o=this.children[n].getObjectByProperty(e,t);if(o!==void 0)return o}}getObjectsByProperty(e,t,n=[]){this[e]===t&&n.push(this);const i=this.children;for(let s=0,o=i.length;s<o;s++)i[s].getObjectsByProperty(e,t,n);return n}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Za,e,OS),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Za,kS,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);const t=this.children;for(let n=0,i=t.length;n<i;n++)t[n].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);const t=this.children;for(let n=0,i=t.length;n<i;n++)t[n].traverseVisible(e)}traverseAncestors(e){const t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale);const e=this.pivot;if(e!==null){const t=e.x,n=e.y,i=e.z,s=this.matrix.elements;s[12]+=t-s[0]*t-s[4]*n-s[8]*i,s[13]+=n-s[1]*t-s[5]*n-s[9]*i,s[14]+=i-s[2]*t-s[6]*n-s[10]*i}this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);const t=this.children;for(let n=0,i=t.length;n<i;n++)t[n].updateMatrixWorld(e)}updateWorldMatrix(e,t){const n=this.parent;if(e===!0&&n!==null&&n.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),t===!0){const i=this.children;for(let s=0,o=i.length;s<o;s++)i[s].updateWorldMatrix(!1,!0)}}toJSON(e){const t=e===void 0||typeof e=="string",n={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});const i={};i.uuid=this.uuid,i.type=this.type,this.name!==""&&(i.name=this.name),this.castShadow===!0&&(i.castShadow=!0),this.receiveShadow===!0&&(i.receiveShadow=!0),this.visible===!1&&(i.visible=!1),this.frustumCulled===!1&&(i.frustumCulled=!1),this.renderOrder!==0&&(i.renderOrder=this.renderOrder),this.static!==!1&&(i.static=this.static),Object.keys(this.userData).length>0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),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;c<u;c++){const h=l[c];s(e.shapes,h)}else s(e.shapes,l)}}if(this.isSkinnedMesh&&(i.bindMode=this.bindMode,i.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(s(e.skeletons,this.skeleton),i.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){const a=[];for(let l=0,c=this.material.length;l<c;l++)a.push(s(e.materials,this.material[l]));i.material=a}else i.material=s(e.materials,this.material);if(this.children.length>0){i.children=[];for(let a=0;a<this.children.length;a++)i.children.push(this.children[a].toJSON(e).object)}if(this.animations.length>0){i.animations=[];for(let a=0;a<this.animations.length;a++){const l=this.animations[a];i.animations.push(s(e.animations,l))}}if(t){const a=o(e.geometries),l=o(e.materials),c=o(e.textures),u=o(e.images),h=o(e.shapes),d=o(e.skeletons),f=o(e.animations),p=o(e.nodes);a.length>0&&(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;n<e.children.length;n++){const i=e.children[n];this.add(i.clone())}return this}}mn.DEFAULT_UP=new C(0,1,0);mn.DEFAULT_MATRIX_AUTO_UPDATE=!0;mn.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;class Xo extends mn{constructor(){super(),this.isGroup=!0,this.type="Group"}}const VS={type:"move"};class Su{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new Xo,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new Xo,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new C,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new C),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new Xo,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new C,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new C,this._grip.eventsEnabled=!1),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const n of e.hand.values())this._getHandJoint(t,n)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,n){let i=null,s=null,o=null;const a=this._targetRay,l=this._grip,c=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(c&&e.hand){o=!0;for(const g of e.hand.values()){const m=t.getJointPose(g,n),_=this._getHandJoint(c,g);m!==null&&(_.matrix.fromArray(m.transform.matrix),_.matrix.decompose(_.position,_.rotation,_.scale),_.matrixWorldNeedsUpdate=!0,_.jointRadius=m.radius),_.visible=m!==null}const u=c.joints["index-finger-tip"],h=c.joints["thumb-tip"],d=u.position.distanceTo(h.position),f=.02,p=.005;c.inputState.pinching&&d>f+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+(i<s?6:0);break;case i:l=(s-n)/h+2;break;case s:l=(n-i)/h+4;break}l/=6}return e.h=l,e.s=c,e.l=u,e}getRGB(e,t=Xe.workingColorSpace){return Xe.workingToColorSpace(Vn.copy(this),t),e.r=Vn.r,e.g=Vn.g,e.b=Vn.b,e}getStyle(e=Qn){Xe.workingToColorSpace(Vn.copy(this),e);const t=Vn.r,n=Vn.g,i=Vn.b;return e!==Qn?`color(${e} ${t.toFixed(3)} ${n.toFixed(3)} ${i.toFixed(3)})`:`rgb(${Math.round(t*255)},${Math.round(n*255)},${Math.round(i*255)})`}offsetHSL(e,t,n){return this.getHSL(Js),this.setHSL(Js.h+e,Js.s+t,Js.l+n)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,n){return this.r=e.r+(t.r-e.r)*n,this.g=e.g+(t.g-e.g)*n,this.b=e.b+(t.b-e.b)*n,this}lerpHSL(e,t){this.getHSL(Js),e.getHSL(bc);const n=bl(Js.h,bc.h,t),i=bl(Js.s,bc.s,t),s=bl(Js.l,bc.l,t);return this.setHSL(n,i,s),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const t=this.r,n=this.g,i=this.b,s=e.elements;return this.r=s[0]*t+s[3]*n+s[6]*i,this.g=s[1]*t+s[4]*n+s[7]*i,this.b=s[2]*t+s[5]*n+s[8]*i,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}const Vn=new Ve;Ve.NAMES=Mx;class op extends mn{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new ys,this.environmentIntensity=1,this.environmentRotation=new ys,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(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<n;t+=3)this.expandByPoint(ki.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(ki.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){const n=ki.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(n),this.max.copy(e).add(n),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);const n=e.geometry;if(n!==void 0){const s=n.getAttribute("position");if(t===!0&&s!==void 0&&e.isInstancedMesh!==!0)for(let o=0,a=s.count;o<a;o++)e.isMesh===!0?e.getVertexPosition(o,ki):ki.fromBufferAttribute(s,o),ki.applyMatrix4(e.matrixWorld),this.expandByPoint(ki);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),Tc.copy(e.boundingBox)):(n.boundingBox===null&&n.computeBoundingBox(),Tc.copy(n.boundingBox)),Tc.applyMatrix4(e.matrixWorld),this.union(Tc)}const i=e.children;for(let s=0,o=i.length;s<o;s++)this.expandByObject(i[s],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,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;i<s;i++)this.array[e+i]=t.array[n+i];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,n=this.count;t<n;t++)Rc.fromBufferAttribute(this,t),Rc.applyMatrix3(e),this.setXY(t,Rc.x,Rc.y);else if(this.itemSize===3)for(let t=0,n=this.count;t<n;t++)fn.fromBufferAttribute(this,t),fn.applyMatrix3(e),this.setXYZ(t,fn.x,fn.y,fn.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)fn.fromBufferAttribute(this,t),fn.applyMatrix4(e),this.setXYZ(t,fn.x,fn.y,fn.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)fn.fromBufferAttribute(this,t),fn.applyNormalMatrix(e),this.setXYZ(t,fn.x,fn.y,fn.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)fn.fromBufferAttribute(this,t),fn.transformDirection(e),this.setXYZ(t,fn.x,fn.y,fn.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let n=this.array[e*this.itemSize+t];return this.normalized&&(n=ei(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=rt(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=ei(t,this.array)),t}setX(e,t){return this.normalized&&(t=rt(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=ei(t,this.array)),t}setY(e,t){return this.normalized&&(t=rt(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=ei(t,this.array)),t}setZ(e,t){return this.normalized&&(t=rt(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=ei(t,this.array)),t}setW(e,t){return this.normalized&&(t=rt(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=rt(t,this.array),n=rt(n,this.array)),this.array[e+0]=t,this.array[e+1]=n,this}setXYZ(e,t,n,i){return e*=this.itemSize,this.normalized&&(t=rt(t,this.array),n=rt(n,this.array),i=rt(i,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=i,this}setXYZW(e,t,n,i,s){return e*=this.itemSize,this.normalized&&(t=rt(t,this.array),n=rt(n,this.array),i=rt(i,this.array),s=rt(s,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=i,this.array[e+3]=s,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==""&&(e.name=this.name),this.usage!==Pa&&(e.usage=this.usage),e}dispose(){this.dispatchEvent({type:"dispose"})}}class ap extends In{constructor(e,t,n){super(new Uint16Array(e),t,n)}}class lp extends In{constructor(e,t,n){super(new Uint32Array(e),t,n)}}class Ex extends In{constructor(e,t,n){super(new Uint16Array(e),t,n),this.isFloat16BufferAttribute=!0}getX(e){let t=Ac(this.array[e*this.itemSize]);return this.normalized&&(t=ei(t,this.array)),t}setX(e,t){return this.normalized&&(t=rt(t,this.array)),this.array[e*this.itemSize]=mi(t),this}getY(e){let t=Ac(this.array[e*this.itemSize+1]);return this.normalized&&(t=ei(t,this.array)),t}setY(e,t){return this.normalized&&(t=rt(t,this.array)),this.array[e*this.itemSize+1]=mi(t),this}getZ(e){let t=Ac(this.array[e*this.itemSize+2]);return this.normalized&&(t=ei(t,this.array)),t}setZ(e,t){return this.normalized&&(t=rt(t,this.array)),this.array[e*this.itemSize+2]=mi(t),this}getW(e){let t=Ac(this.array[e*this.itemSize+3]);return this.normalized&&(t=ei(t,this.array)),t}setW(e,t){return this.normalized&&(t=rt(t,this.array)),this.array[e*this.itemSize+3]=mi(t),this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=rt(t,this.array),n=rt(n,this.array)),this.array[e+0]=mi(t),this.array[e+1]=mi(n),this}setXYZ(e,t,n,i){return e*=this.itemSize,this.normalized&&(t=rt(t,this.array),n=rt(n,this.array),i=rt(i,this.array)),this.array[e+0]=mi(t),this.array[e+1]=mi(n),this.array[e+2]=mi(i),this}setXYZW(e,t,n,i,s){return e*=this.itemSize,this.normalized&&(t=rt(t,this.array),n=rt(n,this.array),i=rt(i,this.array),s=rt(s,this.array)),this.array[e+0]=mi(t),this.array[e+1]=mi(n),this.array[e+2]=mi(i),this.array[e+3]=mi(s),this}}class sn extends In{constructor(e,t,n){super(new Float32Array(e),t,n)}}const WS=new xo,Ja=new C,Fh=new C;class ac{constructor(e=new C,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const n=this.center;t!==void 0?n.copy(t):WS.setFromPoints(e).getCenter(n);let i=0;for(let s=0,o=e.length;s<o;s++)i=Math.max(i,n.distanceToSquared(e[s]));return this.radius=Math.sqrt(i),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){const t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){const n=this.center.distanceToSquared(e);return t.copy(e),n>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;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;i<s;i++){const o=e[i];n.push(o.x,o.y,o.z||0)}this.setAttribute("position",new sn(n,3))}else{const n=Math.min(e.length,t.count);for(let i=0;i<n;i++){const s=e[i];t.setXYZ(i,s.x,s.y,s.z||0)}e.length>t.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;n<i;n++){const s=t[n];gi.setFromBufferAttribute(s),this.morphTargetsRelative?(En.addVectors(this.boundingBox.min,gi.min),this.boundingBox.expandByPoint(En),En.addVectors(this.boundingBox.max,gi.max),this.boundingBox.expandByPoint(En)):(this.boundingBox.expandByPoint(gi.min),this.boundingBox.expandByPoint(gi.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&ne('BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new ac);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){ne("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new C,1/0);return}if(e){const n=this.boundingSphere.center;if(gi.setFromBufferAttribute(e),t)for(let s=0,o=t.length;s<o;s++){const a=t[s];el.setFromBufferAttribute(a),this.morphTargetsRelative?(En.addVectors(gi.min,el.min),gi.expandByPoint(En),En.addVectors(gi.max,el.max),gi.expandByPoint(En)):(gi.expandByPoint(el.min),gi.expandByPoint(el.max))}gi.getCenter(n);let i=0;for(let s=0,o=e.count;s<o;s++)En.fromBufferAttribute(e,s),i=Math.max(i,n.distanceToSquared(En));if(t)for(let s=0,o=t.length;s<o;s++){const a=t[s],l=this.morphTargetsRelative;for(let c=0,u=a.count;c<u;c++)En.fromBufferAttribute(a,c),l&&(Fo.fromBufferAttribute(e,c),En.add(Fo)),i=Math.max(i,n.distanceToSquared(En))}this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius)&&ne('BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){ne("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}const n=t.position,i=t.normal,s=t.uv;this.hasAttribute("tangent")===!1&&this.setAttribute("tangent",new In(new Float32Array(4*n.count),4));const o=this.getAttribute("tangent"),a=[],l=[];for(let y=0;y<n.count;y++)a[y]=new C,l[y]=new C;const c=new C,u=new C,h=new C,d=new de,f=new de,p=new de,g=new C,m=new C;function _(y,R,P){c.fromBufferAttribute(n,y),u.fromBufferAttribute(n,R),h.fromBufferAttribute(n,P),d.fromBufferAttribute(s,y),f.fromBufferAttribute(s,R),p.fromBufferAttribute(s,P),u.sub(c),h.sub(c),f.sub(d),p.sub(d);const N=1/(f.x*p.y-p.x*f.y);isFinite(N)&&(g.copy(u).multiplyScalar(p.y).addScaledVector(h,-f.y).multiplyScalar(N),m.copy(h).multiplyScalar(f.x).addScaledVector(u,-p.x).multiplyScalar(N),a[y].add(g),a[R].add(g),a[P].add(g),l[y].add(m),l[R].add(m),l[P].add(m))}let x=this.groups;x.length===0&&(x=[{start:0,count:e.count}]);for(let y=0,R=x.length;y<R;++y){const P=x[y],N=P.start,U=P.count;for(let G=N,V=N+U;G<V;G+=3)_(e.getX(G+0),e.getX(G+1),e.getX(G+2))}const v=new C,S=new C,E=new C,T=new C;function A(y){E.fromBufferAttribute(i,y),T.copy(E);const R=a[y];v.copy(R),v.sub(E.multiplyScalar(E.dot(R))).normalize(),S.crossVectors(T,R);const N=S.dot(l[y])<0?-1:1;o.setXYZW(y,v.x,v.y,v.z,N)}for(let y=0,R=x.length;y<R;++y){const P=x[y],N=P.start,U=P.count;for(let G=N,V=N+U;G<V;G+=3)A(e.getX(G+0)),A(e.getX(G+1)),A(e.getX(G+2))}}computeVertexNormals(){const e=this.index,t=this.getAttribute("position");if(t!==void 0){let n=this.getAttribute("normal");if(n===void 0)n=new In(new Float32Array(t.count*3),3),this.setAttribute("normal",n);else for(let d=0,f=n.count;d<f;d++)n.setXYZ(d,0,0,0);const i=new C,s=new C,o=new C,a=new C,l=new C,c=new C,u=new C,h=new C;if(e)for(let d=0,f=e.count;d<f;d+=3){const p=e.getX(d+0),g=e.getX(d+1),m=e.getX(d+2);i.fromBufferAttribute(t,p),s.fromBufferAttribute(t,g),o.fromBufferAttribute(t,m),u.subVectors(o,s),h.subVectors(i,s),u.cross(h),a.fromBufferAttribute(n,p),l.fromBufferAttribute(n,g),c.fromBufferAttribute(n,m),a.add(u),l.add(u),c.add(u),n.setXYZ(p,a.x,a.y,a.z),n.setXYZ(g,l.x,l.y,l.z),n.setXYZ(m,c.x,c.y,c.z)}else for(let d=0,f=t.count;d<f;d+=3)i.fromBufferAttribute(t,d+0),s.fromBufferAttribute(t,d+1),o.fromBufferAttribute(t,d+2),u.subVectors(o,s),h.subVectors(i,s),u.cross(h),n.setXYZ(d+0,u.x,u.y,u.z),n.setXYZ(d+1,u.x,u.y,u.z),n.setXYZ(d+2,u.x,u.y,u.z);this.normalizeNormals(),n.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let t=0,n=e.count;t<n;t++)En.fromBufferAttribute(e,t),En.normalize(),e.setXYZ(t,En.x,En.y,En.z)}toNonIndexed(){function e(a,l){const c=a.array,u=a.itemSize,h=a.normalized,d=new c.constructor(l.length*u);let f=0,p=0;for(let g=0,m=l.length;g<m;g++){a.isInterleavedBufferAttribute?f=l[g]*a.data.stride+a.offset:f=l[g]*u;for(let _=0;_<u;_++)d[p++]=c[f++]}return new In(d,u,h)}if(this.index===null)return ee("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new Pn,n=this.index.array,i=this.attributes;for(const a in i){const l=i[a],c=e(l,n);t.setAttribute(a,c)}const s=this.morphAttributes;for(const a in s){const l=[],c=s[a];for(let u=0,h=c.length;u<h;u++){const d=c[u],f=e(d,n);l.push(f)}t.morphAttributes[a]=l}t.morphTargetsRelative=this.morphTargetsRelative;const o=this.groups;for(let a=0,l=o.length;a<l;a++){const c=o[a];t.addGroup(c.start,c.count,c.materialIndex)}return t}toJSON(){const e={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(e.uuid=this.uuid,e.type=this.type,this.name!==""&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),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;h<d;h++){const f=c[h];u.push(f.toJSON(e.data))}u.length>0&&(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;d<f;d++)u.push(h[d].clone(t));this.morphAttributes[c]=u}this.morphTargetsRelative=e.morphTargetsRelative;const o=e.groups;for(let c=0,u=o.length;c<u;c++){const h=o[c];this.addGroup(h.start,h.count,h.materialIndex)}const a=e.boundingBox;a!==null&&(this.boundingBox=a.clone());const l=e.boundingSphere;return l!==null&&(this.boundingSphere=l.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}}class Ax{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e!==void 0?e.length/t:0,this.usage=Pa,this.updateRanges=[],this.version=0,this.uuid=Vs()}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.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,n){e*=this.stride,n*=t.stride;for(let i=0,s=this.stride;i<s;i++)this.array[e+i]=t.array[n+i];return this}set(e,t=0){return this.array.set(e,t),this}clone(e){e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=Vs()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);const t=new this.array.constructor(e.arrayBuffers[this.array.buffer._uuid]),n=new this.constructor(t,this.stride);return n.setUsage(this.usage),n}onUpload(e){return this.onUploadCallback=e,this}toJSON(e){return e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=Vs()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer))),{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}}const Yn=new C;class cp{constructor(e,t,n,i=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=e,this.itemSize=t,this.offset=n,this.normalized=i}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate(e){this.data.needsUpdate=e}applyMatrix4(e){for(let t=0,n=this.data.count;t<n;t++)Yn.fromBufferAttribute(this,t),Yn.applyMatrix4(e),this.setXYZ(t,Yn.x,Yn.y,Yn.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)Yn.fromBufferAttribute(this,t),Yn.applyNormalMatrix(e),this.setXYZ(t,Yn.x,Yn.y,Yn.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)Yn.fromBufferAttribute(this,t),Yn.transformDirection(e),this.setXYZ(t,Yn.x,Yn.y,Yn.z);return this}getComponent(e,t){let n=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(n=ei(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=rt(n,this.array)),this.data.array[e*this.data.stride+this.offset+t]=n,this}setX(e,t){return this.normalized&&(t=rt(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=rt(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=rt(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=rt(t,this.array)),this.data.array[e*this.data.stride+this.offset+3]=t,this}getX(e){let t=this.data.array[e*this.data.stride+this.offset];return this.normalized&&(t=ei(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=ei(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=ei(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=ei(t,this.array)),t}setXY(e,t,n){return e=e*this.data.stride+this.offset,this.normalized&&(t=rt(t,this.array),n=rt(n,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this}setXYZ(e,t,n,i){return e=e*this.data.stride+this.offset,this.normalized&&(t=rt(t,this.array),n=rt(n,this.array),i=rt(i,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=i,this}setXYZW(e,t,n,i,s){return e=e*this.data.stride+this.offset,this.normalized&&(t=rt(t,this.array),n=rt(n,this.array),i=rt(i,this.array),s=rt(s,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=n,this.data.array[e+2]=i,this.data.array[e+3]=s,this}clone(e){if(e===void 0){Kl("InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");const t=[];for(let n=0;n<this.count;n++){const i=n*this.data.stride+this.offset;for(let s=0;s<this.itemSize;s++)t.push(this.data.array[i+s])}return new In(new this.array.constructor(t),this.itemSize,this.normalized)}else return e.interleavedBuffers===void 0&&(e.interleavedBuffers={}),e.interleavedBuffers[this.data.uuid]===void 0&&(e.interleavedBuffers[this.data.uuid]=this.data.clone(e)),new cp(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(e===void 0){Kl("InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");const t=[];for(let n=0;n<this.count;n++){const i=n*this.data.stride+this.offset;for(let s=0;s<this.itemSize;s++)t.push(this.data.array[i+s])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:t,normalized:this.normalized}}else return e.interleavedBuffers===void 0&&(e.interleavedBuffers={}),e.interleavedBuffers[this.data.uuid]===void 0&&(e.interleavedBuffers[this.data.uuid]=this.data.toJSON(e)),{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}}let XS=0;class qn extends Ii{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:XS++}),this.uuid=Vs(),this.name="",this.type="Material",this.blending=Jn,this.side=ni,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=Ul,this.blendDst=Fl,this.blendEquation=Wn,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new Ve(0,0,0),this.blendAlpha=0,this.depthFunc=Ar,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=tf,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=$r,this.stencilZFail=$r,this.stencilZPass=$r,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(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<i||isNaN(i))&&(i=o),h>=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<i||i!==i)&&(i=l),i<0)?null:this.at(n>=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<o;s++){const a=i[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=s}}}}getVertexPosition(e,t){const n=this.geometry,i=n.attributes.position,s=n.morphAttributes.position,o=n.morphTargetsRelative;t.fromBufferAttribute(i,e);const a=this.morphTargetInfluences;if(s&&a){Uc.set(0,0,0);for(let l=0,c=s.length;l<c;l++){const u=a[l],h=s[l];u!==0&&(Gh.fromBufferAttribute(h,e),o?Uc.addScaledVector(Gh,u):Uc.addScaledVector(Gh.sub(t),u))}t.add(Uc)}return t}raycast(e,t){const n=this.geometry,i=this.material,s=this.matrixWorld;i!==void 0&&(n.boundingSphere===null&&n.computeBoundingSphere(),Nc.copy(n.boundingSphere),Nc.applyMatrix4(s),kr.copy(e.ray).recast(e.near),!(Nc.containsPoint(kr.origin)===!1&&(kr.intersectSphere(Nc,Rm)===null||kr.origin.distanceToSquared(Rm)>(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;p<g;p++){const m=d[p],_=o[m.materialIndex],x=Math.max(m.start,f.start),v=Math.min(a.count,Math.min(m.start+m.count,f.start+f.count));for(let S=x,E=v;S<E;S+=3){const T=a.getX(S),A=a.getX(S+1),y=a.getX(S+2);i=Ic(this,_,e,n,c,u,h,T,A,y),i&&(i.faceIndex=Math.floor(S/3),i.face.materialIndex=m.materialIndex,t.push(i))}}else{const p=Math.max(0,f.start),g=Math.min(a.count,f.start+f.count);for(let m=p,_=g;m<_;m+=3){const x=a.getX(m),v=a.getX(m+1),S=a.getX(m+2);i=Ic(this,o,e,n,c,u,h,x,v,S),i&&(i.faceIndex=Math.floor(m/3),t.push(i))}}else if(l!==void 0)if(Array.isArray(o))for(let p=0,g=d.length;p<g;p++){const m=d[p],_=o[m.materialIndex],x=Math.max(m.start,f.start),v=Math.min(l.count,Math.min(m.start+m.count,f.start+f.count));for(let S=x,E=v;S<E;S+=3){const T=S,A=S+1,y=S+2;i=Ic(this,_,e,n,c,u,h,T,A,y),i&&(i.faceIndex=Math.floor(S/3),i.face.materialIndex=m.materialIndex,t.push(i))}}else{const p=Math.max(0,f.start),g=Math.min(l.count,f.start+f.count);for(let m=p,_=g;m<_;m+=3){const x=m,v=m+1,S=m+2;i=Ic(this,o,e,n,c,u,h,x,v,S),i&&(i.faceIndex=Math.floor(m/3),t.push(i))}}}}function jS(r,e,t,n,i,s,o,a){let l;if(e.side===Pt?l=n.intersectTriangle(o,s,i,!0,a):l=n.intersectTriangle(i,s,o,e.side===ni,a),l===null)return null;Fc.copy(a),Fc.applyMatrix4(r.matrixWorld);const c=t.ray.origin.distanceTo(Fc);return c<t.near||c>t.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)<i)return!1;return!0}intersectsBox(e){const t=this.planes;for(let n=0;n<6;n++){const i=t[n];if(Bc.x=i.normal.x>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;n<t.cameras.length;n++){const i=t.cameras[n];if(Yi.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Ki.setFromProjectionMatrix(Yi,i.coordinateSystem,i.reversedDepth),Ki.intersectsObject(e))return!0}return!1}intersectsSprite(e,t){if(!t||!t.cameras||t.cameras.length===0)return!1;for(let n=0;n<t.cameras.length;n++){const i=t.cameras[n];if(Yi.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Ki.setFromProjectionMatrix(Yi,i.coordinateSystem,i.reversedDepth),Ki.intersectsSprite(e))return!0}return!1}intersectsSphere(e,t){if(!t||!t.cameras||t.cameras.length===0)return!1;for(let n=0;n<t.cameras.length;n++){const i=t.cameras[n];if(Yi.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Ki.setFromProjectionMatrix(Yi,i.coordinateSystem,i.reversedDepth),Ki.intersectsSphere(e))return!0}return!1}intersectsBox(e,t){if(!t||!t.cameras||t.cameras.length===0)return!1;for(let n=0;n<t.cameras.length;n++){const i=t.cameras[n];if(Yi.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Ki.setFromProjectionMatrix(Yi,i.coordinateSystem,i.reversedDepth),Ki.intersectsBox(e))return!0}return!1}containsPoint(e,t){if(!t||!t.cameras||t.cameras.length===0)return!1;for(let n=0;n<t.cameras.length;n++){const i=t.cameras[n];if(Yi.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),Ki.setFromProjectionMatrix(Yi,i.coordinateSystem,i.reversedDepth),Ki.containsPoint(e))return!0}return!1}clone(){return new hp}}class Qu extends qn{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new Ve(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}}const Lu=new C,Uu=new C,Cm=new dt,tl=new Zu,Oc=new ac,zh=new C,Nm=new C;class JS extends mn{constructor(e=new Pn,t=new Qu){super(),this.isLine=!0,this.type="Line",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}computeLineDistances(){const e=this.geometry;if(e.index===null){const t=e.attributes.position,n=[0];for(let i=1,s=t.count;i<s;i++)Lu.fromBufferAttribute(t,i-1),Uu.fromBufferAttribute(t,i),n[i]=n[i-1],n[i]+=Lu.distanceTo(Uu);e.setAttribute("lineDistance",new sn(n,1))}else ee("Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast(e,t){const n=this.geometry,i=this.matrixWorld,s=e.params.Line.threshold,o=n.drawRange;if(n.boundingSphere===null&&n.computeBoundingSphere(),Oc.copy(n.boundingSphere),Oc.applyMatrix4(i),Oc.radius+=s,e.ray.intersectsSphere(Oc)===!1)return;Cm.copy(i).invert(),tl.copy(e.ray).applyMatrix4(Cm);const a=s/((this.scale.x+this.scale.y+this.scale.z)/3),l=a*a,c=this.isLineSegments?2:1,u=n.index,d=n.attributes.position;if(u!==null){const f=Math.max(0,o.start),p=Math.min(u.count,o.start+o.count);for(let g=f,m=p-1;g<m;g+=c){const _=u.getX(g),x=u.getX(g+1),v=kc(this,e,tl,l,_,x,g);v&&t.push(v)}if(this.isLineLoop){const g=u.getX(p-1),m=u.getX(f),_=kc(this,e,tl,l,g,m,p-1);_&&t.push(_)}}else{const f=Math.max(0,o.start),p=Math.min(d.count,o.start+o.count);for(let g=f,m=p-1;g<m;g+=c){const _=kc(this,e,tl,l,g,g+1,g);_&&t.push(_)}if(this.isLineLoop){const g=kc(this,e,tl,l,p-1,f,p-1);g&&t.push(g)}}}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<o;s++){const a=i[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=s}}}}}function kc(r,e,t,n,i,s,o){const a=r.geometry.attributes.position;if(Lu.fromBufferAttribute(a,i),Uu.fromBufferAttribute(a,s),t.distanceSqToSegment(Lu,Uu,zh,Nm)>n)return;zh.applyMatrix4(r.matrixWorld);const c=e.ray.origin.distanceTo(zh);if(!(c<e.near||c>e.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;ve<B;ve++){const Ce=ve*N-G;for(let ke=0;ke<L;ke++){const ut=ke*P-U;ce[g]=ut*x,ce[m]=Ce*v,ce[_]=V,c.push(ce.x,ce.y,ce.z),ce[g]=0,ce[m]=0,ce[_]=T>0?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;ve<y;ve++)for(let Ce=0;Ce<A;Ce++){const ke=d+Ce+L*ve,ut=d+Ce+L*(ve+1),Mt=d+(Ce+1)+L*(ve+1),oe=d+(Ce+1)+L*ve;l.push(ke,ut,oe),l.push(ut,Mt,oe),ie+=6}a.addGroup(f,ie,R),f+=ie,d+=H}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new yo(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}class cc extends Pn{constructor(e=1,t=1,n=1,i=32,s=1,o=!1,a=0,l=Math.PI*2){super(),this.type="CylinderGeometry",this.parameters={radiusTop:e,radiusBottom:t,height:n,radialSegments:i,heightSegments:s,openEnded:o,thetaStart:a,thetaLength:l};const c=this;i=Math.floor(i),s=Math.floor(s);const u=[],h=[],d=[],f=[];let p=0;const g=[],m=n/2;let _=0;x(),o===!1&&(e>0&&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;y<i;y++)for(let R=0;R<s;R++){const P=g[R][y],N=g[R+1][y],U=g[R+1][y+1],G=g[R][y+1];(e>0||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;U<i;U++){const G=E+U,V=N+U;S===!0?u.push(V,V+1,G):u.push(V+1,V,G),y+=3}c.addGroup(_,y,S===!0?1:2),_+=y}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new cc(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class dp extends cc{constructor(e=1,t=1,n=32,i=1,s=!1,o=0,a=Math.PI*2){super(0,e,t,n,i,s,o,a),this.type="ConeGeometry",this.parameters={radius:e,height:t,radialSegments:n,heightSegments:i,openEnded:s,thetaStart:o,thetaLength:a}}static fromJSON(e){return new dp(e.radius,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class qs{constructor(){this.type="Curve",this.arcLengthDivisions=200,this.needsUpdate=!1,this.cacheArcLengths=null}getPoint(){ee("Curve: .getPoint() not implemented.")}getPointAt(e,t){const n=this.getUtoTmapping(e);return this.getPoint(n,t)}getPoints(e=5){const t=[];for(let n=0;n<=e;n++)t.push(this.getPoint(n/e));return t}getSpacedPoints(e=5){const t=[];for(let n=0;n<=e;n++)t.push(this.getPointAt(n/e));return t}getLength(){const e=this.getLengths();return e[e.length-1]}getLengths(e=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;const t=[];let n,i=this.getPoint(0),s=0;t.push(0);for(let o=1;o<=e;o++)n=this.getPoint(o/e),s+=n.distanceTo(i),t.push(s),i=n;return this.cacheArcLengths=t,t}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(e,t=null){const n=this.getLengths();let i=0;const s=n.length;let o;t?o=t:o=e*n[s-1];let a=0,l=s-1,c;for(;a<=l;)if(i=Math.floor(a+(l-a)/2),c=n[i]-o,c<0)a=i+1;else if(c>0)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)<Number.EPSILON;for(;s<0;)s+=i;for(;s>i;)s-=i;s<Number.EPSILON&&(o?s=0:s=i),this.aClockwise===!0&&!o&&(s===i?s=-i:s=s-i);const a=this.aStartAngle+e*s;let l=this.aX+this.xRadius*Math.cos(a),c=this.aY+this.yRadius*Math.sin(a);if(this.aRotation!==0){const u=Math.cos(this.aRotation),h=Math.sin(this.aRotation),d=l-this.aX,f=c-this.aY;l=d*u-f*h+this.aX,c=d*h+f*u+this.aY}return n.set(l,c)}copy(e){return super.copy(e),this.aX=e.aX,this.aY=e.aY,this.xRadius=e.xRadius,this.yRadius=e.yRadius,this.aStartAngle=e.aStartAngle,this.aEndAngle=e.aEndAngle,this.aClockwise=e.aClockwise,this.aRotation=e.aRotation,this}toJSON(){const e=super.toJSON();return e.aX=this.aX,e.aY=this.aY,e.xRadius=this.xRadius,e.yRadius=this.yRadius,e.aStartAngle=this.aStartAngle,e.aEndAngle=this.aEndAngle,e.aClockwise=this.aClockwise,e.aRotation=this.aRotation,e}fromJSON(e){return super.fromJSON(e),this.aX=e.aX,this.aY=e.aY,this.xRadius=e.xRadius,this.yRadius=e.yRadius,this.aStartAngle=e.aStartAngle,this.aEndAngle=e.aEndAngle,this.aClockwise=e.aClockwise,this.aRotation=e.aRotation,this}}class tb extends Nx{constructor(e,t,n,i,s,o){super(e,t,n,n,i,s,o),this.isArcCurve=!0,this.type="ArcCurve"}}function fp(){let r=0,e=0,t=0,n=0;function i(s,o,a,l){r=s,e=a,t=-3*s+3*o-2*a-l,n=2*s-2*o+a+l}return{initCatmullRom:function(s,o,a,l,c){i(o,a,c*(a-s),c*(l-o))},initNonuniformCatmullRom:function(s,o,a,l,c,u,h){let d=(o-s)/c-(a-s)/(c+u)+(a-o)/u,f=(a-o)/u-(l-o)/(u+h)+(l-a)/h;d*=u,f*=u,i(o,a,d,f)},calc:function(s){const o=s*s,a=o*s;return r+e*s+t*o+n*a}}}const Pm=new C,Dm=new C,Hh=new fp,Wh=new fp,$h=new fp;class nb extends qs{constructor(e=[],t=!1,n="centripetal",i=.5){super(),this.isCatmullRomCurve3=!0,this.type="CatmullRomCurve3",this.points=e,this.closed=t,this.curveType=n,this.tension=i}getPoint(e,t=new C){const n=t,i=this.points,s=i.length,o=(s-(this.closed?0:1))*e;let a=Math.floor(o),l=o-a;this.closed?a+=a>0?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+2<s?u=i[(a+2)%s]:(Pm.subVectors(i[s-1],i[s-2]).add(i[s-1]),u=Pm),this.curveType==="centripetal"||this.curveType==="chordal"){const f=this.curveType==="chordal"?.5:.25;let p=Math.pow(c.distanceToSquared(h),f),g=Math.pow(h.distanceToSquared(d),f),m=Math.pow(d.distanceToSquared(u),f);g<1e-4&&(g=1),p<1e-4&&(p=g),m<1e-4&&(m=g),Hh.initNonuniformCatmullRom(c.x,h.x,d.x,u.x,p,g,m),Wh.initNonuniformCatmullRom(c.y,h.y,d.y,u.y,p,g,m),$h.initNonuniformCatmullRom(c.z,h.z,d.z,u.z,p,g,m)}else this.curveType==="catmullrom"&&(Hh.initCatmullRom(c.x,h.x,d.x,u.x,this.tension),Wh.initCatmullRom(c.y,h.y,d.y,u.y,this.tension),$h.initCatmullRom(c.z,h.z,d.z,u.z,this.tension));return n.set(Hh.calc(l),Wh.calc(l),$h.calc(l)),n}copy(e){super.copy(e),this.points=[];for(let t=0,n=e.points.length;t<n;t++){const i=e.points[t];this.points.push(i.clone())}return this.closed=e.closed,this.curveType=e.curveType,this.tension=e.tension,this}toJSON(){const e=super.toJSON();e.points=[];for(let t=0,n=this.points.length;t<n;t++){const i=this.points[t];e.points.push(i.toArray())}return e.closed=this.closed,e.curveType=this.curveType,e.tension=this.tension,e}fromJSON(e){super.fromJSON(e),this.points=[];for(let t=0,n=e.points.length;t<n;t++){const i=e.points[t];this.points.push(new C().fromArray(i))}return this.closed=e.closed,this.curveType=e.curveType,this.tension=e.tension,this}}function Lm(r,e,t,n,i){const s=(n-e)*.5,o=(i-t)*.5,a=r*r,l=r*a;return(2*t-2*n+s+o)*l+(-3*t+3*n-2*s-o)*a+s*r+t}function ib(r,e){const t=1-r;return t*t*e}function sb(r,e){return 2*(1-r)*r*e}function rb(r,e){return r*r*e}function Tl(r,e,t,n){return ib(r,e)+sb(r,t)+rb(r,n)}function ob(r,e){const t=1-r;return t*t*t*e}function ab(r,e){const t=1-r;return 3*t*t*r*e}function lb(r,e){return 3*(1-r)*r*r*e}function cb(r,e){return r*r*r*e}function Ml(r,e,t,n,i){return ob(r,e)+ab(r,t)+lb(r,n)+cb(r,i)}class ub extends qs{constructor(e=new de,t=new de,n=new de,i=new de){super(),this.isCubicBezierCurve=!0,this.type="CubicBezierCurve",this.v0=e,this.v1=t,this.v2=n,this.v3=i}getPoint(e,t=new de){const n=t,i=this.v0,s=this.v1,o=this.v2,a=this.v3;return n.set(Ml(e,i.x,s.x,o.x,a.x),Ml(e,i.y,s.y,o.y,a.y)),n}copy(e){return super.copy(e),this.v0.copy(e.v0),this.v1.copy(e.v1),this.v2.copy(e.v2),this.v3.copy(e.v3),this}toJSON(){const e=super.toJSON();return e.v0=this.v0.toArray(),e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e.v3=this.v3.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v0.fromArray(e.v0),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this.v3.fromArray(e.v3),this}}class Px extends qs{constructor(e=new C,t=new C,n=new C,i=new C){super(),this.isCubicBezierCurve3=!0,this.type="CubicBezierCurve3",this.v0=e,this.v1=t,this.v2=n,this.v3=i}getPoint(e,t=new C){const n=t,i=this.v0,s=this.v1,o=this.v2,a=this.v3;return n.set(Ml(e,i.x,s.x,o.x,a.x),Ml(e,i.y,s.y,o.y,a.y),Ml(e,i.z,s.z,o.z,a.z)),n}copy(e){return super.copy(e),this.v0.copy(e.v0),this.v1.copy(e.v1),this.v2.copy(e.v2),this.v3.copy(e.v3),this}toJSON(){const e=super.toJSON();return e.v0=this.v0.toArray(),e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e.v3=this.v3.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v0.fromArray(e.v0),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this.v3.fromArray(e.v3),this}}class hb extends qs{constructor(e=new de,t=new de){super(),this.isLineCurve=!0,this.type="LineCurve",this.v1=e,this.v2=t}getPoint(e,t=new de){const n=t;return e===1?n.copy(this.v2):(n.copy(this.v2).sub(this.v1),n.multiplyScalar(e).add(this.v1)),n}getPointAt(e,t){return this.getPoint(e,t)}getTangent(e,t=new de){return t.subVectors(this.v2,this.v1).normalize()}getTangentAt(e,t){return this.getTangent(e,t)}copy(e){return super.copy(e),this.v1.copy(e.v1),this.v2.copy(e.v2),this}toJSON(){const e=super.toJSON();return e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this}}class db extends qs{constructor(e=new C,t=new C){super(),this.isLineCurve3=!0,this.type="LineCurve3",this.v1=e,this.v2=t}getPoint(e,t=new C){const n=t;return e===1?n.copy(this.v2):(n.copy(this.v2).sub(this.v1),n.multiplyScalar(e).add(this.v1)),n}getPointAt(e,t){return this.getPoint(e,t)}getTangent(e,t=new C){return t.subVectors(this.v2,this.v1).normalize()}getTangentAt(e,t){return this.getTangent(e,t)}copy(e){return super.copy(e),this.v1.copy(e.v1),this.v2.copy(e.v2),this}toJSON(){const e=super.toJSON();return e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this}}class fb extends qs{constructor(e=new de,t=new de,n=new de){super(),this.isQuadraticBezierCurve=!0,this.type="QuadraticBezierCurve",this.v0=e,this.v1=t,this.v2=n}getPoint(e,t=new de){const n=t,i=this.v0,s=this.v1,o=this.v2;return n.set(Tl(e,i.x,s.x,o.x),Tl(e,i.y,s.y,o.y)),n}copy(e){return super.copy(e),this.v0.copy(e.v0),this.v1.copy(e.v1),this.v2.copy(e.v2),this}toJSON(){const e=super.toJSON();return e.v0=this.v0.toArray(),e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v0.fromArray(e.v0),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this}}class pp extends qs{constructor(e=new C,t=new C,n=new C){super(),this.isQuadraticBezierCurve3=!0,this.type="QuadraticBezierCurve3",this.v0=e,this.v1=t,this.v2=n}getPoint(e,t=new C){const n=t,i=this.v0,s=this.v1,o=this.v2;return n.set(Tl(e,i.x,s.x,o.x),Tl(e,i.y,s.y,o.y),Tl(e,i.z,s.z,o.z)),n}copy(e){return super.copy(e),this.v0.copy(e.v0),this.v1.copy(e.v1),this.v2.copy(e.v2),this}toJSON(){const e=super.toJSON();return e.v0=this.v0.toArray(),e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v0.fromArray(e.v0),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this}}class pb extends qs{constructor(e=[]){super(),this.isSplineCurve=!0,this.type="SplineCurve",this.points=e}getPoint(e,t=new de){const n=t,i=this.points,s=(i.length-1)*e,o=Math.floor(s),a=s-o,l=i[o===0?o:o-1],c=i[o],u=i[o>i.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;t<n;t++){const i=e.points[t];this.points.push(i.clone())}return this}toJSON(){const e=super.toJSON();e.points=[];for(let t=0,n=this.points.length;t<n;t++){const i=this.points[t];e.points.push(i.toArray())}return e}fromJSON(e){super.fromJSON(e),this.points=[];for(let t=0,n=e.points.length;t<n;t++){const i=e.points[t];this.points.push(new de().fromArray(i))}return this}}var mb=Object.freeze({__proto__:null,ArcCurve:tb,CatmullRomCurve3:nb,CubicBezierCurve:ub,CubicBezierCurve3:Px,EllipseCurve:Nx,LineCurve:hb,LineCurve3:db,QuadraticBezierCurve:fb,QuadraticBezierCurve3:pp,SplineCurve:pb});class uc extends Pn{constructor(e=1,t=1,n=1,i=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:n,heightSegments:i};const s=e/2,o=t/2,a=Math.floor(n),l=Math.floor(i),c=a+1,u=l+1,h=e/a,d=t/l,f=[],p=[],g=[],m=[];for(let _=0;_<u;_++){const x=_*d-o;for(let v=0;v<c;v++){const S=v*h-s;p.push(S,-x,0),g.push(0,0,1),m.push(v/a),m.push(1-_/l)}}for(let _=0;_<l;_++)for(let x=0;x<a;x++){const v=x+c*_,S=x+c*(_+1),E=x+1+c*(_+1),T=x+1+c*_;f.push(v,S,T),f.push(S,E,T)}this.setIndex(f),this.setAttribute("position",new sn(p,3)),this.setAttribute("normal",new sn(g,3)),this.setAttribute("uv",new sn(m,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new uc(e.width,e.height,e.widthSegments,e.heightSegments)}}class hc extends Pn{constructor(e=1,t=32,n=16,i=0,s=Math.PI*2,o=0,a=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:e,widthSegments:t,heightSegments:n,phiStart:i,phiLength:s,thetaStart:o,thetaLength:a},t=Math.max(3,Math.floor(t)),n=Math.max(2,Math.floor(n));const l=Math.min(o+a,Math.PI);let c=0;const u=[],h=new C,d=new C,f=[],p=[],g=[],m=[];for(let _=0;_<=n;_++){const x=[],v=_/n;let S=0;_===0&&o===0?S=.5/t:_===n&&l===Math.PI&&(S=-.5/t);for(let E=0;E<=t;E++){const T=E/t;h.x=-e*Math.cos(i+T*s)*Math.sin(o+v*a),h.y=e*Math.cos(o+v*a),h.z=e*Math.sin(i+T*s)*Math.sin(o+v*a),p.push(h.x,h.y,h.z),d.copy(h).normalize(),g.push(d.x,d.y,d.z),m.push(T+S,1-v),x.push(c++)}u.push(x)}for(let _=0;_<n;_++)for(let x=0;x<t;x++){const v=u[_][x+1],S=u[_][x],E=u[_+1][x],T=u[_+1][x+1];(_!==0||o>0)&&f.push(v,S,T),(_!==n-1||l<Math.PI)&&f.push(S,E,T)}this.setIndex(f),this.setAttribute("position",new sn(p,3)),this.setAttribute("normal",new sn(g,3)),this.setAttribute("uv",new sn(m,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new hc(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}}class mp extends Pn{constructor(e=new pp(new C(-1,-1,0),new C(-1,1,0),new C(1,1,0)),t=64,n=1,i=8,s=!1){super(),this.type="TubeGeometry",this.parameters={path:e,tubularSegments:t,radius:n,radialSegments:i,closed:s};const o=e.computeFrenetFrames(t,s);this.tangents=o.tangents,this.normals=o.normals,this.binormals=o.binormals;const a=new C,l=new C,c=new de;let u=new C;const h=[],d=[],f=[],p=[];g(),this.setIndex(p),this.setAttribute("position",new sn(h,3)),this.setAttribute("normal",new sn(d,3)),this.setAttribute("uv",new sn(f,2));function g(){for(let v=0;v<t;v++)m(v);m(s===!1?t:0),x(),_()}function m(v){u=e.getPointAt(v/t,u);const S=o.normals[v],E=o.binormals[v];for(let T=0;T<=i;T++){const A=T/i*Math.PI*2,y=Math.sin(A),R=-Math.cos(A);l.x=R*S.x+y*E.x,l.y=R*S.y+y*E.y,l.z=R*S.z+y*E.z,l.normalize(),d.push(l.x,l.y,l.z),a.x=u.x+n*l.x,a.y=u.y+n*l.y,a.z=u.z+n*l.z,h.push(a.x,a.y,a.z)}}function _(){for(let v=1;v<=t;v++)for(let S=1;S<=i;S++){const E=(i+1)*(v-1)+(S-1),T=(i+1)*v+(S-1),A=(i+1)*v+S,y=(i+1)*(v-1)+S;p.push(E,T,y),p.push(T,A,y)}}function x(){for(let v=0;v<=t;v++)for(let S=0;S<=i;S++)c.x=v/t,c.y=S/i,f.push(c.x,c.y)}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}toJSON(){const e=super.toJSON();return e.path=this.parameters.path.toJSON(),e}static fromJSON(e){return new mp(new mb[e.path.type]().fromJSON(e.path),e.tubularSegments,e.radius,e.radialSegments,e.closed)}}class gb extends qn{constructor(e){super(),this.isShadowMaterial=!0,this.type="ShadowMaterial",this.color=new Ve(0),this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.fog=e.fog,this}}function Da(r){const e={};for(const t in r){e[t]={};for(const n in r[t]){const i=r[t][n];if(Um(i))i.isRenderTargetTexture?(ee("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[t][n]=null):e[t][n]=i.clone();else if(Array.isArray(i))if(Um(i[0])){const s=[];for(let o=0,a=i.length;o<a;o++)s[o]=i[o].clone();e[t][n]=s}else e[t][n]=i.slice();else e[t][n]=i}}return e}function Kn(r){const e={};for(let t=0;t<r.length;t++){const n=Da(r[t]);for(const i in n)e[i]=n[i]}return e}function Um(r){return r&&(r.isColor||r.isMatrix3||r.isMatrix4||r.isVector2||r.isVector3||r.isVector4||r.isTexture||r.isQuaternion)}function _b(r){const e=[];for(let t=0;t<r.length;t++)e.push(r[t].clone());return e}function Dx(r){const e=r.getRenderTarget();return e===null?r.outputColorSpace:e.isXRRenderTarget===!0?e.texture.colorSpace:Xe.workingColorSpace}const Lx={clone:Da,merge:Kn};var xb=`void main() {
|
|
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
|
}`,yb=`void main() {
|
|
gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
|
|
}`;class Ui extends qn{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=xb,this.fragmentShader=yb,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,e!==void 0&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=Da(e.uniforms),this.uniformsGroups=_b(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this.defaultAttributeValues=Object.assign({},e.defaultAttributeValues),this.index0AttributeName=e.index0AttributeName,this.uniformsNeedUpdate=e.uniformsNeedUpdate,this}toJSON(e){const t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(const i in this.uniforms){const o=this.uniforms[i].value;o&&o.isTexture?t.uniforms[i]={type:"t",value:o.toJSON(e).uuid}:o&&o.isColor?t.uniforms[i]={type:"c",value:o.getHex()}:o&&o.isVector2?t.uniforms[i]={type:"v2",value:o.toArray()}:o&&o.isVector3?t.uniforms[i]={type:"v3",value:o.toArray()}:o&&o.isVector4?t.uniforms[i]={type:"v4",value:o.toArray()}:o&&o.isMatrix3?t.uniforms[i]={type:"m3",value:o.toArray()}:o&&o.isMatrix4?t.uniforms[i]={type:"m4",value:o.toArray()}:t.uniforms[i]={value:o}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const n={};for(const 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;h<d;h+=2){const f=c[h],p=c[h+1];if(f.global&&(f.lastIndex=0),f.test(u))return p}return null},this.abort=function(){return this.abortController.abort(),this._abortController=null,this}}get abortController(){return this._abortController||(this._abortController=new AbortController),this._abortController}}const Nb=new Cb;class gp{constructor(e){this.manager=e!==void 0?e:Nb,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}load(){}loadAsync(e,t){const n=this;return new Promise(function(i,s){n.load(e,i,t,s)})}parse(){}setCrossOrigin(e){return this.crossOrigin=e,this}setWithCredentials(e){return this.withCredentials=e,this}setPath(e){return this.path=e,this}setResourcePath(e){return this.resourcePath=e,this}setRequestHeader(e){return this.requestHeader=e,this}abort(){return this}}gp.DEFAULT_MATERIAL_NAME="__DEFAULT";const Io=new WeakMap;class Pb extends gp{constructor(e){super(e)}load(e,t,n,i){this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);const s=this,o=Xh.get(`image:${e}`);if(o!==void 0){if(o.complete===!0)s.manager.itemStart(e),setTimeout(function(){t&&t(o),s.manager.itemEnd(e)},0);else{let h=Io.get(o);h===void 0&&(h=[],Io.set(o,h)),h.push({onLoad:t,onError:i})}return o}const a=Yl("img");function l(){u(),t&&t(this);const h=Io.get(this)||[];for(let d=0;d<h.length;d++){const f=h[d];f.onLoad&&f.onLoad(this)}Io.delete(this),s.manager.itemEnd(e)}function c(h){u(),i&&i(h),Xh.remove(`image:${e}`);const d=Io.get(this)||[];for(let f=0;f<d.length;f++){const p=d[f];p.onError&&p.onError(h)}Io.delete(this),s.manager.itemError(e),s.manager.itemEnd(e)}function u(){a.removeEventListener("load",l,!1),a.removeEventListener("error",c,!1)}return a.addEventListener("load",l,!1),a.addEventListener("error",c,!1),e.slice(0,5)!=="data:"&&this.crossOrigin!==void 0&&(a.crossOrigin=this.crossOrigin),Xh.add(`image:${e}`,a),s.manager.itemStart(e),a.src=e,a}}class Db extends gp{constructor(e){super(e)}load(e,t,n,i){const s=new pn,o=new Pb(this.manager);return o.setCrossOrigin(this.crossOrigin),o.setPath(this.path),o.load(e,function(a){s.image=a,s.needsUpdate=!0,t!==void 0&&t(s)},n,i),s}}class vo extends mn{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new Ve(e),this.intensity=t}dispose(){this.dispatchEvent({type:"dispose"})}copy(e,t){return super.copy(e,t),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){const t=super.toJSON(e);return t.object.color=this.color.getHex(),t.object.intensity=this.intensity,t}}class Lb extends vo{constructor(e,t,n){super(e,n),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(mn.DEFAULT_UP),this.updateMatrix(),this.groundColor=new Ve(t)}copy(e,t){return super.copy(e,t),this.groundColor.copy(e.groundColor),this}toJSON(e){const t=super.toJSON(e);return t.object.groundColor=this.groundColor.getHex(),t}}const qh=new dt,Im=new C,Bm=new C;class _p{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.biasNode=null,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new de(512,512),this.mapType=$t,this.map=null,this.mapPass=null,this.matrix=new dt,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new lc,this._frameExtents=new de(1,1),this._viewportCount=1,this._viewports=[new tt(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const t=this.camera,n=this.matrix;Im.setFromMatrixPosition(e.matrixWorld),t.position.copy(Im),Bm.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(Bm),t.updateMatrixWorld(),qh.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(qh,t.coordinateSystem,t.reversedDepth),t.coordinateSystem===xs||t.reversedDepth?n.set(.5,0,0,.5,0,.5,0,.5,0,0,1,0,0,0,0,1):n.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),n.multiply(qh)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(e){return this.camera=e.camera.clone(),this.intensity=e.intensity,this.bias=e.bias,this.radius=e.radius,this.autoUpdate=e.autoUpdate,this.needsUpdate=e.needsUpdate,this.normalBias=e.normalBias,this.blurSamples=e.blurSamples,this.mapSize.copy(e.mapSize),this.biasNode=e.biasNode,this}clone(){return new this.constructor().copy(this)}toJSON(){const e={};return this.intensity!==1&&(e.intensity=this.intensity),this.bias!==0&&(e.bias=this.bias),this.normalBias!==0&&(e.normalBias=this.normalBias),this.radius!==1&&(e.radius=this.radius),(this.mapSize.x!==512||this.mapSize.y!==512)&&(e.mapSize=this.mapSize.toArray()),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}}const Gc=new C,Vc=new Li,Zi=new C;class Ix extends mn{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new dt,this.projectionMatrix=new dt,this.projectionMatrixInverse=new dt,this.coordinateSystem=ti,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorld.decompose(Gc,Vc,Zi),Zi.x===1&&Zi.y===1&&Zi.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(Gc,Vc,Zi.set(1,1,1)).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorld.decompose(Gc,Vc,Zi),Zi.x===1&&Zi.y===1&&Zi.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(Gc,Vc,Zi.set(1,1,1)).invert()}clone(){return new this.constructor().copy(this)}}const ir=new C,Om=new de,km=new de;class Rn extends Ix{constructor(e=50,t=1,n=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=n,this.far=i,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=ao*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(Sl*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return ao*2*Math.atan(Math.tan(Sl*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,n){ir.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(ir.x,ir.y).multiplyScalar(-e/ir.z),ir.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(ir.x,ir.y).multiplyScalar(-e/ir.z)}getViewSize(e,t){return this.getViewBounds(e,Om,km),t.subVectors(km,Om)}setViewOffset(e,t,n,i,s,o){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=i,this.view.width=s,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(Sl*.5*this.fov)/this.zoom,n=2*t,i=this.aspect*n,s=-.5*i;const o=this.view;if(this.view!==null&&this.view.enabled){const l=o.fullWidth,c=o.fullHeight;s+=o.offsetX*i/l,t-=o.offsetY*n/c,i*=o.width/l,n*=o.height/c}const a=this.filmOffset;a!==0&&(s+=e*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(s,s+i,t,t-n,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}class Ub extends _p{constructor(){super(new Rn(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1,this.aspect=1}updateMatrices(e){const t=this.camera,n=ao*2*e.angle*this.focus,i=this.mapSize.width/this.mapSize.height*this.aspect,s=e.distance||t.far;(n!==t.fov||i!==t.aspect||s!==t.far)&&(t.fov=n,t.aspect=i,t.far=s,t.updateProjectionMatrix()),super.updateMatrices(e)}copy(e){return super.copy(e),this.focus=e.focus,this}}class xp extends vo{constructor(e,t,n=0,i=Math.PI/3,s=0,o=2){super(e,t),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(mn.DEFAULT_UP),this.updateMatrix(),this.target=new mn,this.distance=n,this.angle=i,this.penumbra=s,this.decay=o,this.map=null,this.shadow=new Ub}get power(){return this.intensity*Math.PI}set power(e){this.intensity=e/Math.PI}dispose(){super.dispose(),this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.angle=e.angle,this.penumbra=e.penumbra,this.decay=e.decay,this.target=e.target.clone(),this.map=e.map,this.shadow=e.shadow.clone(),this}toJSON(e){const t=super.toJSON(e);return t.object.distance=this.distance,t.object.angle=this.angle,t.object.decay=this.decay,t.object.penumbra=this.penumbra,t.object.target=this.target.uuid,this.map&&this.map.isTexture&&(t.object.map=this.map.toJSON(e).uuid),t.object.shadow=this.shadow.toJSON(),t}}class Fb extends _p{constructor(){super(new Rn(90,1,.5,500)),this.isPointLightShadow=!0}}class Ib extends vo{constructor(e,t,n=0,i=2){super(e,t),this.isPointLight=!0,this.type="PointLight",this.distance=n,this.decay=i,this.shadow=new Fb}get power(){return this.intensity*4*Math.PI}set power(e){this.intensity=e/(4*Math.PI)}dispose(){super.dispose(),this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.decay=e.decay,this.shadow=e.shadow.clone(),this}toJSON(e){const t=super.toJSON(e);return t.object.distance=this.distance,t.object.decay=this.decay,t.object.shadow=this.shadow.toJSON(),t}}class Va extends Ix{constructor(e=-1,t=1,n=1,i=-1,s=.1,o=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=n,this.bottom=i,this.near=s,this.far=o,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,n,i,s,o){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=i,this.view.width=s,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,i=(this.top+this.bottom)/2;let s=n-e,o=n+e,a=i+t,l=i-t;if(this.view!==null&&this.view.enabled){const c=(this.right-this.left)/this.view.fullWidth/this.zoom,u=(this.top-this.bottom)/this.view.fullHeight/this.zoom;s+=c*this.view.offsetX,o=s+c*this.view.width,a-=u*this.view.offsetY,l=a-u*this.view.height}this.projectionMatrix.makeOrthographic(s,o,a,l,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}}class Bb extends _p{constructor(){super(new Va(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class Bx extends vo{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(mn.DEFAULT_UP),this.updateMatrix(),this.target=new mn,this.shadow=new Bb}dispose(){super.dispose(),this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}toJSON(e){const t=super.toJSON(e);return t.object.shadow=this.shadow.toJSON(),t.object.target=this.target.uuid,t}}class Ox extends vo{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type="AmbientLight"}}class Ob extends vo{constructor(e,t,n=10,i=10){super(e,t),this.isRectAreaLight=!0,this.type="RectAreaLight",this.width=n,this.height=i}get power(){return this.intensity*this.width*this.height*Math.PI}set power(e){this.intensity=e/(this.width*this.height*Math.PI)}copy(e){return super.copy(e),this.width=e.width,this.height=e.height,this}toJSON(e){const t=super.toJSON(e);return t.object.width=this.width,t.object.height=this.height,t}}class kb{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let e=0;e<9;e++)this.coefficients.push(new C)}set(e){for(let t=0;t<9;t++)this.coefficients[t].copy(e[t]);return this}zero(){for(let e=0;e<9;e++)this.coefficients[e].set(0,0,0);return this}getAt(e,t){const n=e.x,i=e.y,s=e.z,o=this.coefficients;return t.copy(o[0]).multiplyScalar(.282095),t.addScaledVector(o[1],.488603*i),t.addScaledVector(o[2],.488603*s),t.addScaledVector(o[3],.488603*n),t.addScaledVector(o[4],1.092548*(n*i)),t.addScaledVector(o[5],1.092548*(i*s)),t.addScaledVector(o[6],.315392*(3*s*s-1)),t.addScaledVector(o[7],1.092548*(n*s)),t.addScaledVector(o[8],.546274*(n*n-i*i)),t}getIrradianceAt(e,t){const n=e.x,i=e.y,s=e.z,o=this.coefficients;return t.copy(o[0]).multiplyScalar(.886227),t.addScaledVector(o[1],2*.511664*i),t.addScaledVector(o[2],2*.511664*s),t.addScaledVector(o[3],2*.511664*n),t.addScaledVector(o[4],2*.429043*n*i),t.addScaledVector(o[5],2*.429043*i*s),t.addScaledVector(o[6],.743125*s*s-.247708),t.addScaledVector(o[7],2*.429043*n*s),t.addScaledVector(o[8],.429043*(n*n-i*i)),t}add(e){for(let t=0;t<9;t++)this.coefficients[t].add(e.coefficients[t]);return this}addScaledSH(e,t){for(let n=0;n<9;n++)this.coefficients[n].addScaledVector(e.coefficients[n],t);return this}scale(e){for(let t=0;t<9;t++)this.coefficients[t].multiplyScalar(e);return this}lerp(e,t){for(let n=0;n<9;n++)this.coefficients[n].lerp(e.coefficients[n],t);return this}equals(e){for(let t=0;t<9;t++)if(!this.coefficients[t].equals(e.coefficients[t]))return!1;return!0}copy(e){return this.set(e.coefficients)}clone(){return new this.constructor().copy(this)}fromArray(e,t=0){const n=this.coefficients;for(let i=0;i<9;i++)n[i].fromArray(e,t+i*3);return this}toArray(e=[],t=0){const n=this.coefficients;for(let i=0;i<9;i++)n[i].toArray(e,t+i*3);return e}static getBasisAt(e,t){const n=e.x,i=e.y,s=e.z;t[0]=.282095,t[1]=.488603*i,t[2]=.488603*s,t[3]=.488603*n,t[4]=1.092548*n*i,t[5]=1.092548*i*s,t[6]=.315392*(3*s*s-1),t[7]=1.092548*n*s,t[8]=.546274*(n*n-i*i)}}class Gb extends vo{constructor(e=new kb,t=1){super(void 0,t),this.isLightProbe=!0,this.sh=e}copy(e){return super.copy(e),this.sh.copy(e.sh),this}toJSON(e){const t=super.toJSON(e);return t.object.sh=this.sh.toArray(),t}}const Bo=-90,Oo=1;class kx extends mn{constructor(e,t,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new Rn(Bo,Oo,e,t);i.layers=this.layers,this.add(i);const s=new Rn(Bo,Oo,e,t);s.layers=this.layers,this.add(s);const o=new Rn(Bo,Oo,e,t);o.layers=this.layers,this.add(o);const a=new Rn(Bo,Oo,e,t);a.layers=this.layers,this.add(a);const l=new Rn(Bo,Oo,e,t);l.layers=this.layers,this.add(l);const c=new Rn(Bo,Oo,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[n,i,s,o,a,l]=t;for(const c of t)this.remove(c);if(e===ti)n.up.set(0,1,0),n.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),s.up.set(0,0,-1),s.lookAt(0,1,0),o.up.set(0,0,1),o.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),l.up.set(0,1,0),l.lookAt(0,0,-1);else if(e===xs)n.up.set(0,-1,0),n.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),s.up.set(0,0,1),s.lookAt(0,1,0),o.up.set(0,0,-1),o.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),l.up.set(0,-1,0),l.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const c of t)this.add(c),c.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();const{renderTarget:n,activeMipmapLevel:i}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[s,o,a,l,c,u]=this.children,h=e.getRenderTarget(),d=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;const g=n.texture.generateMipmaps;n.texture.generateMipmaps=!1;let m=!1;e.isWebGLRenderer===!0?m=e.state.buffers.depth.getReversed():m=e.reversedDepthBuffer,e.setRenderTarget(n,0,i),m&&e.autoClear===!1&&e.clearDepth(),e.render(t,s),e.setRenderTarget(n,1,i),m&&e.autoClear===!1&&e.clearDepth(),e.render(t,o),e.setRenderTarget(n,2,i),m&&e.autoClear===!1&&e.clearDepth(),e.render(t,a),e.setRenderTarget(n,3,i),m&&e.autoClear===!1&&e.clearDepth(),e.render(t,l),e.setRenderTarget(n,4,i),m&&e.autoClear===!1&&e.clearDepth(),e.render(t,c),n.texture.generateMipmaps=g,e.setRenderTarget(n,5,i),m&&e.autoClear===!1&&e.clearDepth(),e.render(t,u),e.setRenderTarget(h,d,f),e.xr.enabled=p,n.texture.needsPMREMUpdate=!0}}class Gx extends Rn{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class Vx{constructor(){this._previousTime=0,this._currentTime=0,this._startTime=performance.now(),this._delta=0,this._elapsed=0,this._timescale=1,this._document=null,this._pageVisibilityHandler=null}connect(e){this._document=e,e.hidden!==void 0&&(this._pageVisibilityHandler=Vb.bind(this),e.addEventListener("visibilitychange",this._pageVisibilityHandler,!1))}disconnect(){this._pageVisibilityHandler!==null&&(this._document.removeEventListener("visibilitychange",this._pageVisibilityHandler),this._pageVisibilityHandler=null),this._document=null}getDelta(){return this._delta/1e3}getElapsed(){return this._elapsed/1e3}getTimescale(){return this._timescale}setTimescale(e){return this._timescale=e,this}reset(){return this._currentTime=performance.now()-this._startTime,this}dispose(){this.disconnect()}update(e){return this._pageVisibilityHandler!==null&&this._document.hidden===!0?this._delta=0:(this._previousTime=this._currentTime,this._currentTime=(e!==void 0?e:performance.now())-this._startTime,this._delta=(this._currentTime-this._previousTime)*this._timescale,this._elapsed+=this._delta),this}}function Vb(){this._document.hidden===!1&&this.reset()}class zb extends Ax{constructor(e,t,n=1){super(e,t),this.isInstancedInterleavedBuffer=!0,this.meshPerAttribute=n}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}clone(e){const t=super.clone(e);return t.meshPerAttribute=this.meshPerAttribute,t}toJSON(e){const t=super.toJSON(e);return t.isInstancedInterleavedBuffer=!0,t.meshPerAttribute=this.meshPerAttribute,t}}const Gm=new dt;class zx{constructor(e,t,n=0,i=1/0){this.ray=new Zu(e,t),this.near=n,this.far=i,this.camera=null,this.layers=new rp,this.params={Mesh:{},Line:{threshold:1},LOD:{},Points:{threshold:1},Sprite:{}}}set(e,t){this.ray.set(e,t)}setFromCamera(e,t){t.isPerspectiveCamera?(this.ray.origin.setFromMatrixPosition(t.matrixWorld),this.ray.direction.set(e.x,e.y,.5).unproject(t).sub(this.ray.origin).normalize(),this.camera=t):t.isOrthographicCamera?(this.ray.origin.set(e.x,e.y,(t.near+t.far)/(t.near-t.far)).unproject(t),this.ray.direction.set(0,0,-1).transformDirection(t.matrixWorld),this.camera=t):ne("Raycaster: Unsupported camera type: "+t.type)}setFromXRController(e){return Gm.identity().extractRotation(e.matrixWorld),this.ray.origin.setFromMatrixPosition(e.matrixWorld),this.ray.direction.set(0,0,-1).applyMatrix4(Gm),this}intersectObject(e,t=!0,n=[]){return nf(e,this,n,t),n.sort(Vm),n}intersectObjects(e,t=!0,n=[]){for(let i=0,s=e.length;i<s;i++)nf(e[i],this,n,t);return n.sort(Vm),n}}function Vm(r,e){return r.distance-e.distance}function nf(r,e,t,n){let i=!0;if(r.layers.test(e.layers)&&r.raycast(e,t)===!1&&(i=!1),i===!0&&n===!0){const s=r.children;for(let o=0,a=s.length;o<a;o++)nf(s[o],e,t,!0)}}class zm{constructor(e=1,t=0,n=0){this.radius=e,this.phi=t,this.theta=n}set(e,t,n){return this.radius=e,this.phi=t,this.theta=n,this}copy(e){return this.radius=e.radius,this.phi=e.phi,this.theta=e.theta,this}makeSafe(){return this.phi=ot(this.phi,1e-6,Math.PI-1e-6),this}setFromVector3(e){return this.setFromCartesianCoords(e.x,e.y,e.z)}setFromCartesianCoords(e,t,n){return this.radius=Math.sqrt(e*e+t*t+n*n),this.radius===0?(this.theta=0,this.phi=0):(this.theta=Math.atan2(e,n),this.phi=Math.acos(ot(t/this.radius,-1,1))),this}clone(){return new this.constructor().copy(this)}}const tm=class tm{constructor(e,t,n,i){this.elements=[1,0,0,1],e!==void 0&&this.set(e,t,n,i)}identity(){return this.set(1,0,0,1),this}fromArray(e,t=0){for(let n=0;n<4;n++)this.elements[n]=e[n+t];return this}set(e,t,n,i){const s=this.elements;return s[0]=e,s[2]=t,s[1]=n,s[3]=i,this}};tm.prototype.isMatrix2=!0;let Fu=tm;class Ju extends Ii{constructor(e,t=null){super(),this.object=e,this.domElement=t,this.enabled=!0,this.state=-1,this.keys={},this.mouseButtons={LEFT:null,MIDDLE:null,RIGHT:null},this.touches={ONE:null,TWO:null}}connect(e){if(e===void 0){ee("Controls: connect() now requires an element.");return}this.domElement!==null&&this.disconnect(),this.domElement=e}disconnect(){}dispose(){}update(){}}function sf(r,e,t,n){const i=Hb(n);switch(t){case Yu:return r*e;case Oa:return r*e/i.components*i.byteLength;case mo:return r*e/i.components*i.byteLength;case Fn:return r*e*2/i.components*i.byteLength;case go:return r*e*2/i.components*i.byteLength;case Ba:return r*e*3/i.components*i.byteLength;case an:return r*e*4/i.components*i.byteLength;case ka:return r*e*4/i.components*i.byteLength;case yr:case vr:return Math.floor((r+3)/4)*Math.floor((e+3)/4)*8;case Sr:case br:return Math.floor((r+3)/4)*Math.floor((e+3)/4)*16;case Wl:case Xl:return Math.max(r,16)*Math.max(e,8)/4;case Hl:case $l:return Math.max(r,8)*Math.max(e,8)/2;case oa:case aa:case ca:case ua:return Math.floor((r+3)/4)*Math.floor((e+3)/4)*8;case la:case Rr:case ha:return Math.floor((r+3)/4)*Math.floor((e+3)/4)*16;case da:return Math.floor((r+3)/4)*Math.floor((e+3)/4)*16;case fa:return Math.floor((r+4)/5)*Math.floor((e+3)/4)*16;case pa:return Math.floor((r+4)/5)*Math.floor((e+4)/5)*16;case ma:return Math.floor((r+5)/6)*Math.floor((e+4)/5)*16;case ga:return Math.floor((r+5)/6)*Math.floor((e+5)/6)*16;case _a:return Math.floor((r+7)/8)*Math.floor((e+4)/5)*16;case xa:return Math.floor((r+7)/8)*Math.floor((e+5)/6)*16;case ya:return Math.floor((r+7)/8)*Math.floor((e+7)/8)*16;case va:return Math.floor((r+9)/10)*Math.floor((e+4)/5)*16;case Sa:return Math.floor((r+9)/10)*Math.floor((e+5)/6)*16;case ba:return Math.floor((r+9)/10)*Math.floor((e+7)/8)*16;case Ta:return Math.floor((r+9)/10)*Math.floor((e+9)/10)*16;case Ma:return Math.floor((r+11)/12)*Math.floor((e+9)/10)*16;case Ea:return Math.floor((r+11)/12)*Math.floor((e+11)/12)*16;case Aa:case Jd:case ef:return Math.ceil(r/4)*Math.ceil(e/4)*16;case Ra:case wa:return Math.ceil(r/4)*Math.ceil(e/4)*8;case wr:case Ca:return Math.ceil(r/4)*Math.ceil(e/4)*16}throw new Error(`Unable to determine texture byte length for ${t} format.`)}function Hb(r){switch(r){case $t:case _r:return{byteLength:1,components:1};case Ci:case xr:case en:return{byteLength:2,components:1};case ic:case sc:return{byteLength:2,components:4};case wt:case Sn:case Zt:return{byteLength:4,components:1};case rc:case oc:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${r}.`)}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:po}}));typeof window<"u"&&(window.__THREE__?ee("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=po);/**
|
|
* @license
|
|
* Copyright 2010-2026 Three.js Authors
|
|
* SPDX-License-Identifier: MIT
|
|
*/function Hx(){let r=null,e=!1,t=null,n=null;function i(s,o){t(s,o),n=r.requestAnimationFrame(i)}return{start:function(){e!==!0&&t!==null&&r!==null&&(n=r.requestAnimationFrame(i),e=!0)},stop:function(){r!==null&&r.cancelAnimationFrame(n),e=!1},setAnimationLoop:function(s){t=s},setContext:function(s){r=s}}}function Wb(r){const e=new WeakMap;function t(a,l){const c=a.array,u=a.usage,h=c.byteLength,d=r.createBuffer();r.bindBuffer(l,d),r.bufferData(l,c,u),a.onUploadCallback();let f;if(c instanceof Float32Array)f=r.FLOAT;else if(typeof Float16Array<"u"&&c instanceof Float16Array)f=r.HALF_FLOAT;else if(c instanceof Uint16Array)a.isFloat16BufferAttribute?f=r.HALF_FLOAT:f=r.UNSIGNED_SHORT;else if(c instanceof Int16Array)f=r.SHORT;else if(c instanceof Uint32Array)f=r.UNSIGNED_INT;else if(c instanceof Int32Array)f=r.INT;else if(c instanceof Int8Array)f=r.BYTE;else if(c instanceof Uint8Array)f=r.UNSIGNED_BYTE;else if(c instanceof Uint8ClampedArray)f=r.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+c);return{buffer:d,type:f,bytesPerElement:c.BYTES_PER_ELEMENT,version:a.version,size:h}}function n(a,l,c){const u=l.array,h=l.updateRanges;if(r.bindBuffer(c,a),h.length===0)r.bufferSubData(c,0,u);else{h.sort((f,p)=>f.start-p.start);let d=0;for(let f=1;f<h.length;f++){const p=h[d],g=h[f];g.start<=p.start+p.count+1?p.count=Math.max(p.count,g.start+g.count-p.start):(++d,h[d]=g)}h.length=d+1;for(let f=0,p=h.length;f<p;f++){const g=h[f];r.bufferSubData(c,g.start*u.BYTES_PER_ELEMENT,u,g.start,g.count)}l.clearUpdateRanges()}l.onUploadCallback()}function i(a){return a.isInterleavedBufferAttribute&&(a=a.data),e.get(a)}function s(a){a.isInterleavedBufferAttribute&&(a=a.data);const l=e.get(a);l&&(r.deleteBuffer(l.buffer),e.delete(a))}function o(a,l){if(a.isInterleavedBufferAttribute&&(a=a.data),a.isGLBufferAttribute){const u=e.get(a);(!u||u.version<a.version)&&e.set(a,{buffer:a.buffer,type:a.type,bytesPerElement:a.elementSize,version:a.version});return}const c=e.get(a);if(c===void 0)e.set(a,t(a,l));else if(c.version<a.version){if(c.size!==a.array.byteLength)throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.");n(c.buffer,a,l),c.version=a.version}}return{get:i,remove:s,update:o}}var $b=`#ifdef USE_ALPHAHASH
|
|
if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;
|
|
#endif`,Xb=`#ifdef USE_ALPHAHASH
|
|
const float ALPHA_HASH_SCALE = 0.05;
|
|
float hash2D( vec2 value ) {
|
|
return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );
|
|
}
|
|
float hash3D( vec3 value ) {
|
|
return hash2D( vec2( hash2D( value.xy ), value.z ) );
|
|
}
|
|
float getAlphaHashThreshold( vec3 position ) {
|
|
float maxDeriv = max(
|
|
length( dFdx( position.xyz ) ),
|
|
length( dFdy( position.xyz ) )
|
|
);
|
|
float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );
|
|
vec2 pixScales = vec2(
|
|
exp2( floor( log2( pixScale ) ) ),
|
|
exp2( ceil( log2( pixScale ) ) )
|
|
);
|
|
vec2 alpha = vec2(
|
|
hash3D( floor( pixScales.x * position.xyz ) ),
|
|
hash3D( floor( pixScales.y * position.xyz ) )
|
|
);
|
|
float lerpFactor = fract( log2( pixScale ) );
|
|
float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;
|
|
float a = min( lerpFactor, 1.0 - lerpFactor );
|
|
vec3 cases = vec3(
|
|
x * x / ( 2.0 * a * ( 1.0 - a ) ),
|
|
( x - 0.5 * a ) / ( 1.0 - a ),
|
|
1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )
|
|
);
|
|
float threshold = ( x < ( 1.0 - a ) )
|
|
? ( ( x < a ) ? cases.x : cases.y )
|
|
: cases.z;
|
|
return clamp( threshold , 1.0e-6, 1.0 );
|
|
}
|
|
#endif`,qb=`#ifdef USE_ALPHAMAP
|
|
diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;
|
|
#endif`,jb=`#ifdef USE_ALPHAMAP
|
|
uniform sampler2D alphaMap;
|
|
#endif`,Yb=`#ifdef USE_ALPHATEST
|
|
#ifdef ALPHA_TO_COVERAGE
|
|
diffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );
|
|
if ( diffuseColor.a == 0.0 ) discard;
|
|
#else
|
|
if ( diffuseColor.a < alphaTest ) discard;
|
|
#endif
|
|
#endif`,Kb=`#ifdef USE_ALPHATEST
|
|
uniform float alphaTest;
|
|
#endif`,Zb=`#ifdef USE_AOMAP
|
|
float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;
|
|
reflectedLight.indirectDiffuse *= ambientOcclusion;
|
|
#if defined( USE_CLEARCOAT )
|
|
clearcoatSpecularIndirect *= ambientOcclusion;
|
|
#endif
|
|
#if defined( USE_SHEEN )
|
|
sheenSpecularIndirect *= ambientOcclusion;
|
|
#endif
|
|
#if defined( USE_ENVMAP ) && defined( STANDARD )
|
|
float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );
|
|
reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );
|
|
#endif
|
|
#endif`,Qb=`#ifdef USE_AOMAP
|
|
uniform sampler2D aoMap;
|
|
uniform float aoMapIntensity;
|
|
#endif`,Jb=`#ifdef USE_BATCHING
|
|
#if ! defined( GL_ANGLE_multi_draw )
|
|
#define gl_DrawID _gl_DrawID
|
|
uniform int _gl_DrawID;
|
|
#endif
|
|
uniform highp sampler2D batchingTexture;
|
|
uniform highp usampler2D batchingIdTexture;
|
|
mat4 getBatchingMatrix( const in float i ) {
|
|
int size = textureSize( batchingTexture, 0 ).x;
|
|
int j = int( i ) * 4;
|
|
int x = j % size;
|
|
int y = j / size;
|
|
vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );
|
|
vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );
|
|
vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );
|
|
vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );
|
|
return mat4( v1, v2, v3, v4 );
|
|
}
|
|
float getIndirectIndex( const in int i ) {
|
|
int size = textureSize( batchingIdTexture, 0 ).x;
|
|
int x = i % size;
|
|
int y = i / size;
|
|
return float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r );
|
|
}
|
|
#endif
|
|
#ifdef USE_BATCHING_COLOR
|
|
uniform sampler2D batchingColorTexture;
|
|
vec4 getBatchingColor( const in float i ) {
|
|
int size = textureSize( batchingColorTexture, 0 ).x;
|
|
int j = int( i );
|
|
int x = j % size;
|
|
int y = j / size;
|
|
return texelFetch( batchingColorTexture, ivec2( x, y ), 0 );
|
|
}
|
|
#endif`,eT=`#ifdef USE_BATCHING
|
|
mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );
|
|
#endif`,tT=`vec3 transformed = vec3( position );
|
|
#ifdef USE_ALPHAHASH
|
|
vPosition = vec3( position );
|
|
#endif`,nT=`vec3 objectNormal = vec3( normal );
|
|
#ifdef USE_TANGENT
|
|
vec3 objectTangent = vec3( tangent.xyz );
|
|
#endif`,iT=`float G_BlinnPhong_Implicit( ) {
|
|
return 0.25;
|
|
}
|
|
float D_BlinnPhong( const in float shininess, const in float dotNH ) {
|
|
return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );
|
|
}
|
|
vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {
|
|
vec3 halfDir = normalize( lightDir + viewDir );
|
|
float dotNH = saturate( dot( normal, halfDir ) );
|
|
float dotVH = saturate( dot( viewDir, halfDir ) );
|
|
vec3 F = F_Schlick( specularColor, 1.0, dotVH );
|
|
float G = G_BlinnPhong_Implicit( );
|
|
float D = D_BlinnPhong( shininess, dotNH );
|
|
return F * ( G * D );
|
|
} // validated`,sT=`#ifdef USE_IRIDESCENCE
|
|
const mat3 XYZ_TO_REC709 = mat3(
|
|
3.2404542, -0.9692660, 0.0556434,
|
|
-1.5371385, 1.8760108, -0.2040259,
|
|
-0.4985314, 0.0415560, 1.0572252
|
|
);
|
|
vec3 Fresnel0ToIor( vec3 fresnel0 ) {
|
|
vec3 sqrtF0 = sqrt( fresnel0 );
|
|
return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );
|
|
}
|
|
vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {
|
|
return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );
|
|
}
|
|
float IorToFresnel0( float transmittedIor, float incidentIor ) {
|
|
return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));
|
|
}
|
|
vec3 evalSensitivity( float OPD, vec3 shift ) {
|
|
float phase = 2.0 * PI * OPD * 1.0e-9;
|
|
vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
|
|
vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
|
|
vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
|
|
vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );
|
|
xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );
|
|
xyz /= 1.0685e-7;
|
|
vec3 rgb = XYZ_TO_REC709 * xyz;
|
|
return rgb;
|
|
}
|
|
vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {
|
|
vec3 I;
|
|
float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
|
|
float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );
|
|
float cosTheta2Sq = 1.0 - sinTheta2Sq;
|
|
if ( cosTheta2Sq < 0.0 ) {
|
|
return vec3( 1.0 );
|
|
}
|
|
float cosTheta2 = sqrt( cosTheta2Sq );
|
|
float R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
|
|
float R12 = F_Schlick( R0, 1.0, cosTheta1 );
|
|
float T121 = 1.0 - R12;
|
|
float phi12 = 0.0;
|
|
if ( iridescenceIOR < outsideIOR ) phi12 = PI;
|
|
float phi21 = PI - phi12;
|
|
vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) ); vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );
|
|
vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );
|
|
vec3 phi23 = vec3( 0.0 );
|
|
if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;
|
|
if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;
|
|
if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;
|
|
float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;
|
|
vec3 phi = vec3( phi21 ) + phi23;
|
|
vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );
|
|
vec3 r123 = sqrt( R123 );
|
|
vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );
|
|
vec3 C0 = R12 + Rs;
|
|
I = C0;
|
|
vec3 Cm = Rs - T121;
|
|
for ( int m = 1; m <= 2; ++ m ) {
|
|
Cm *= r123;
|
|
vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );
|
|
I += Cm * Sm;
|
|
}
|
|
return max( I, vec3( 0.0 ) );
|
|
}
|
|
#endif`,rT=`#ifdef USE_BUMPMAP
|
|
uniform sampler2D bumpMap;
|
|
uniform float bumpScale;
|
|
vec2 dHdxy_fwd() {
|
|
vec2 dSTdx = dFdx( vBumpMapUv );
|
|
vec2 dSTdy = dFdy( vBumpMapUv );
|
|
float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;
|
|
float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;
|
|
float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;
|
|
return vec2( dBx, dBy );
|
|
}
|
|
vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {
|
|
vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );
|
|
vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );
|
|
vec3 vN = surf_norm;
|
|
vec3 R1 = cross( vSigmaY, vN );
|
|
vec3 R2 = cross( vN, vSigmaX );
|
|
float fDet = dot( vSigmaX, R1 ) * faceDirection;
|
|
vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );
|
|
return normalize( abs( fDet ) * surf_norm - vGrad );
|
|
}
|
|
#endif`,oT=`#if NUM_CLIPPING_PLANES > 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 <lightprobes_pars_fragment>`,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 <tonemapping_fragment>
|
|
#include <colorspace_fragment>
|
|
}`,qM=`varying vec3 vWorldDirection;
|
|
#include <common>
|
|
void main() {
|
|
vWorldDirection = transformDirection( position, modelMatrix );
|
|
#include <begin_vertex>
|
|
#include <project_vertex>
|
|
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 <cube_uv_reflection_fragment>
|
|
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 <tonemapping_fragment>
|
|
#include <colorspace_fragment>
|
|
}`,YM=`varying vec3 vWorldDirection;
|
|
#include <common>
|
|
void main() {
|
|
vWorldDirection = transformDirection( position, modelMatrix );
|
|
#include <begin_vertex>
|
|
#include <project_vertex>
|
|
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 <tonemapping_fragment>
|
|
#include <colorspace_fragment>
|
|
}`,ZM=`#include <common>
|
|
#include <batching_pars_vertex>
|
|
#include <uv_pars_vertex>
|
|
#include <displacementmap_pars_vertex>
|
|
#include <morphtarget_pars_vertex>
|
|
#include <skinning_pars_vertex>
|
|
#include <logdepthbuf_pars_vertex>
|
|
#include <clipping_planes_pars_vertex>
|
|
varying vec2 vHighPrecisionZW;
|
|
void main() {
|
|
#include <uv_vertex>
|
|
#include <batching_vertex>
|
|
#include <skinbase_vertex>
|
|
#include <morphinstance_vertex>
|
|
#ifdef USE_DISPLACEMENTMAP
|
|
#include <beginnormal_vertex>
|
|
#include <morphnormal_vertex>
|
|
#include <skinnormal_vertex>
|
|
#endif
|
|
#include <begin_vertex>
|
|
#include <morphtarget_vertex>
|
|
#include <skinning_vertex>
|
|
#include <displacementmap_vertex>
|
|
#include <project_vertex>
|
|
#include <logdepthbuf_vertex>
|
|
#include <clipping_planes_vertex>
|
|
vHighPrecisionZW = gl_Position.zw;
|
|
}`,QM=`#if DEPTH_PACKING == 3200
|
|
uniform float opacity;
|
|
#endif
|
|
#include <common>
|
|
#include <packing>
|
|
#include <uv_pars_fragment>
|
|
#include <map_pars_fragment>
|
|
#include <alphamap_pars_fragment>
|
|
#include <alphatest_pars_fragment>
|
|
#include <alphahash_pars_fragment>
|
|
#include <logdepthbuf_pars_fragment>
|
|
#include <clipping_planes_pars_fragment>
|
|
varying vec2 vHighPrecisionZW;
|
|
void main() {
|
|
vec4 diffuseColor = vec4( 1.0 );
|
|
#include <clipping_planes_fragment>
|
|
#if DEPTH_PACKING == 3200
|
|
diffuseColor.a = opacity;
|
|
#endif
|
|
#include <map_fragment>
|
|
#include <alphamap_fragment>
|
|
#include <alphatest_fragment>
|
|
#include <alphahash_fragment>
|
|
#include <logdepthbuf_fragment>
|
|
#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 <common>
|
|
#include <batching_pars_vertex>
|
|
#include <uv_pars_vertex>
|
|
#include <displacementmap_pars_vertex>
|
|
#include <morphtarget_pars_vertex>
|
|
#include <skinning_pars_vertex>
|
|
#include <clipping_planes_pars_vertex>
|
|
void main() {
|
|
#include <uv_vertex>
|
|
#include <batching_vertex>
|
|
#include <skinbase_vertex>
|
|
#include <morphinstance_vertex>
|
|
#ifdef USE_DISPLACEMENTMAP
|
|
#include <beginnormal_vertex>
|
|
#include <morphnormal_vertex>
|
|
#include <skinnormal_vertex>
|
|
#endif
|
|
#include <begin_vertex>
|
|
#include <morphtarget_vertex>
|
|
#include <skinning_vertex>
|
|
#include <displacementmap_vertex>
|
|
#include <project_vertex>
|
|
#include <worldpos_vertex>
|
|
#include <clipping_planes_vertex>
|
|
vWorldPosition = worldPosition.xyz;
|
|
}`,eE=`#define DISTANCE
|
|
uniform vec3 referencePosition;
|
|
uniform float nearDistance;
|
|
uniform float farDistance;
|
|
varying vec3 vWorldPosition;
|
|
#include <common>
|
|
#include <uv_pars_fragment>
|
|
#include <map_pars_fragment>
|
|
#include <alphamap_pars_fragment>
|
|
#include <alphatest_pars_fragment>
|
|
#include <alphahash_pars_fragment>
|
|
#include <clipping_planes_pars_fragment>
|
|
void main () {
|
|
vec4 diffuseColor = vec4( 1.0 );
|
|
#include <clipping_planes_fragment>
|
|
#include <map_fragment>
|
|
#include <alphamap_fragment>
|
|
#include <alphatest_fragment>
|
|
#include <alphahash_fragment>
|
|
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 <common>
|
|
void main() {
|
|
vWorldDirection = transformDirection( position, modelMatrix );
|
|
#include <begin_vertex>
|
|
#include <project_vertex>
|
|
}`,nE=`uniform sampler2D tEquirect;
|
|
varying vec3 vWorldDirection;
|
|
#include <common>
|
|
void main() {
|
|
vec3 direction = normalize( vWorldDirection );
|
|
vec2 sampleUV = equirectUv( direction );
|
|
gl_FragColor = texture2D( tEquirect, sampleUV );
|
|
#include <tonemapping_fragment>
|
|
#include <colorspace_fragment>
|
|
}`,iE=`uniform float scale;
|
|
attribute float lineDistance;
|
|
varying float vLineDistance;
|
|
#include <common>
|
|
#include <uv_pars_vertex>
|
|
#include <color_pars_vertex>
|
|
#include <fog_pars_vertex>
|
|
#include <morphtarget_pars_vertex>
|
|
#include <logdepthbuf_pars_vertex>
|
|
#include <clipping_planes_pars_vertex>
|
|
void main() {
|
|
vLineDistance = scale * lineDistance;
|
|
#include <uv_vertex>
|
|
#include <color_vertex>
|
|
#include <morphinstance_vertex>
|
|
#include <morphcolor_vertex>
|
|
#include <begin_vertex>
|
|
#include <morphtarget_vertex>
|
|
#include <project_vertex>
|
|
#include <logdepthbuf_vertex>
|
|
#include <clipping_planes_vertex>
|
|
#include <fog_vertex>
|
|
}`,sE=`uniform vec3 diffuse;
|
|
uniform float opacity;
|
|
uniform float dashSize;
|
|
uniform float totalSize;
|
|
varying float vLineDistance;
|
|
#include <common>
|
|
#include <color_pars_fragment>
|
|
#include <uv_pars_fragment>
|
|
#include <map_pars_fragment>
|
|
#include <fog_pars_fragment>
|
|
#include <logdepthbuf_pars_fragment>
|
|
#include <clipping_planes_pars_fragment>
|
|
void main() {
|
|
vec4 diffuseColor = vec4( diffuse, opacity );
|
|
#include <clipping_planes_fragment>
|
|
if ( mod( vLineDistance, totalSize ) > dashSize ) {
|
|
discard;
|
|
}
|
|
vec3 outgoingLight = vec3( 0.0 );
|
|
#include <logdepthbuf_fragment>
|
|
#include <map_fragment>
|
|
#include <color_fragment>
|
|
outgoingLight = diffuseColor.rgb;
|
|
#include <opaque_fragment>
|
|
#include <tonemapping_fragment>
|
|
#include <colorspace_fragment>
|
|
#include <fog_fragment>
|
|
#include <premultiplied_alpha_fragment>
|
|
}`,rE=`#include <common>
|
|
#include <batching_pars_vertex>
|
|
#include <uv_pars_vertex>
|
|
#include <envmap_pars_vertex>
|
|
#include <color_pars_vertex>
|
|
#include <fog_pars_vertex>
|
|
#include <morphtarget_pars_vertex>
|
|
#include <skinning_pars_vertex>
|
|
#include <logdepthbuf_pars_vertex>
|
|
#include <clipping_planes_pars_vertex>
|
|
void main() {
|
|
#include <uv_vertex>
|
|
#include <color_vertex>
|
|
#include <morphinstance_vertex>
|
|
#include <morphcolor_vertex>
|
|
#include <batching_vertex>
|
|
#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )
|
|
#include <beginnormal_vertex>
|
|
#include <morphnormal_vertex>
|
|
#include <skinbase_vertex>
|
|
#include <skinnormal_vertex>
|
|
#include <defaultnormal_vertex>
|
|
#endif
|
|
#include <begin_vertex>
|
|
#include <morphtarget_vertex>
|
|
#include <skinning_vertex>
|
|
#include <project_vertex>
|
|
#include <logdepthbuf_vertex>
|
|
#include <clipping_planes_vertex>
|
|
#include <worldpos_vertex>
|
|
#include <envmap_vertex>
|
|
#include <fog_vertex>
|
|
}`,oE=`uniform vec3 diffuse;
|
|
uniform float opacity;
|
|
#ifndef FLAT_SHADED
|
|
varying vec3 vNormal;
|
|
#endif
|
|
#include <common>
|
|
#include <dithering_pars_fragment>
|
|
#include <color_pars_fragment>
|
|
#include <uv_pars_fragment>
|
|
#include <map_pars_fragment>
|
|
#include <alphamap_pars_fragment>
|
|
#include <alphatest_pars_fragment>
|
|
#include <alphahash_pars_fragment>
|
|
#include <aomap_pars_fragment>
|
|
#include <lightmap_pars_fragment>
|
|
#include <envmap_common_pars_fragment>
|
|
#include <envmap_pars_fragment>
|
|
#include <fog_pars_fragment>
|
|
#include <specularmap_pars_fragment>
|
|
#include <logdepthbuf_pars_fragment>
|
|
#include <clipping_planes_pars_fragment>
|
|
void main() {
|
|
vec4 diffuseColor = vec4( diffuse, opacity );
|
|
#include <clipping_planes_fragment>
|
|
#include <logdepthbuf_fragment>
|
|
#include <map_fragment>
|
|
#include <color_fragment>
|
|
#include <alphamap_fragment>
|
|
#include <alphatest_fragment>
|
|
#include <alphahash_fragment>
|
|
#include <specularmap_fragment>
|
|
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 <aomap_fragment>
|
|
reflectedLight.indirectDiffuse *= diffuseColor.rgb;
|
|
vec3 outgoingLight = reflectedLight.indirectDiffuse;
|
|
#include <envmap_fragment>
|
|
#include <opaque_fragment>
|
|
#include <tonemapping_fragment>
|
|
#include <colorspace_fragment>
|
|
#include <fog_fragment>
|
|
#include <premultiplied_alpha_fragment>
|
|
#include <dithering_fragment>
|
|
}`,aE=`#define LAMBERT
|
|
varying vec3 vViewPosition;
|
|
#include <common>
|
|
#include <batching_pars_vertex>
|
|
#include <uv_pars_vertex>
|
|
#include <displacementmap_pars_vertex>
|
|
#include <envmap_pars_vertex>
|
|
#include <color_pars_vertex>
|
|
#include <fog_pars_vertex>
|
|
#include <normal_pars_vertex>
|
|
#include <morphtarget_pars_vertex>
|
|
#include <skinning_pars_vertex>
|
|
#include <shadowmap_pars_vertex>
|
|
#include <logdepthbuf_pars_vertex>
|
|
#include <clipping_planes_pars_vertex>
|
|
void main() {
|
|
#include <uv_vertex>
|
|
#include <color_vertex>
|
|
#include <morphinstance_vertex>
|
|
#include <morphcolor_vertex>
|
|
#include <batching_vertex>
|
|
#include <beginnormal_vertex>
|
|
#include <morphnormal_vertex>
|
|
#include <skinbase_vertex>
|
|
#include <skinnormal_vertex>
|
|
#include <defaultnormal_vertex>
|
|
#include <normal_vertex>
|
|
#include <begin_vertex>
|
|
#include <morphtarget_vertex>
|
|
#include <skinning_vertex>
|
|
#include <displacementmap_vertex>
|
|
#include <project_vertex>
|
|
#include <logdepthbuf_vertex>
|
|
#include <clipping_planes_vertex>
|
|
vViewPosition = - mvPosition.xyz;
|
|
#include <worldpos_vertex>
|
|
#include <envmap_vertex>
|
|
#include <shadowmap_vertex>
|
|
#include <fog_vertex>
|
|
}`,lE=`#define LAMBERT
|
|
uniform vec3 diffuse;
|
|
uniform vec3 emissive;
|
|
uniform float opacity;
|
|
#include <common>
|
|
#include <dithering_pars_fragment>
|
|
#include <color_pars_fragment>
|
|
#include <uv_pars_fragment>
|
|
#include <map_pars_fragment>
|
|
#include <alphamap_pars_fragment>
|
|
#include <alphatest_pars_fragment>
|
|
#include <alphahash_pars_fragment>
|
|
#include <aomap_pars_fragment>
|
|
#include <lightmap_pars_fragment>
|
|
#include <emissivemap_pars_fragment>
|
|
#include <cube_uv_reflection_fragment>
|
|
#include <envmap_common_pars_fragment>
|
|
#include <envmap_pars_fragment>
|
|
#include <envmap_physical_pars_fragment>
|
|
#include <fog_pars_fragment>
|
|
#include <bsdfs>
|
|
#include <lights_pars_begin>
|
|
#include <normal_pars_fragment>
|
|
#include <lights_lambert_pars_fragment>
|
|
#include <shadowmap_pars_fragment>
|
|
#include <bumpmap_pars_fragment>
|
|
#include <normalmap_pars_fragment>
|
|
#include <specularmap_pars_fragment>
|
|
#include <logdepthbuf_pars_fragment>
|
|
#include <clipping_planes_pars_fragment>
|
|
void main() {
|
|
vec4 diffuseColor = vec4( diffuse, opacity );
|
|
#include <clipping_planes_fragment>
|
|
ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
|
|
vec3 totalEmissiveRadiance = emissive;
|
|
#include <logdepthbuf_fragment>
|
|
#include <map_fragment>
|
|
#include <color_fragment>
|
|
#include <alphamap_fragment>
|
|
#include <alphatest_fragment>
|
|
#include <alphahash_fragment>
|
|
#include <specularmap_fragment>
|
|
#include <normal_fragment_begin>
|
|
#include <normal_fragment_maps>
|
|
#include <emissivemap_fragment>
|
|
#include <lights_lambert_fragment>
|
|
#include <lights_fragment_begin>
|
|
#include <lights_fragment_maps>
|
|
#include <lights_fragment_end>
|
|
#include <aomap_fragment>
|
|
vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
|
|
#include <envmap_fragment>
|
|
#include <opaque_fragment>
|
|
#include <tonemapping_fragment>
|
|
#include <colorspace_fragment>
|
|
#include <fog_fragment>
|
|
#include <premultiplied_alpha_fragment>
|
|
#include <dithering_fragment>
|
|
}`,cE=`#define MATCAP
|
|
varying vec3 vViewPosition;
|
|
#include <common>
|
|
#include <batching_pars_vertex>
|
|
#include <uv_pars_vertex>
|
|
#include <color_pars_vertex>
|
|
#include <displacementmap_pars_vertex>
|
|
#include <fog_pars_vertex>
|
|
#include <normal_pars_vertex>
|
|
#include <morphtarget_pars_vertex>
|
|
#include <skinning_pars_vertex>
|
|
#include <logdepthbuf_pars_vertex>
|
|
#include <clipping_planes_pars_vertex>
|
|
void main() {
|
|
#include <uv_vertex>
|
|
#include <color_vertex>
|
|
#include <morphinstance_vertex>
|
|
#include <morphcolor_vertex>
|
|
#include <batching_vertex>
|
|
#include <beginnormal_vertex>
|
|
#include <morphnormal_vertex>
|
|
#include <skinbase_vertex>
|
|
#include <skinnormal_vertex>
|
|
#include <defaultnormal_vertex>
|
|
#include <normal_vertex>
|
|
#include <begin_vertex>
|
|
#include <morphtarget_vertex>
|
|
#include <skinning_vertex>
|
|
#include <displacementmap_vertex>
|
|
#include <project_vertex>
|
|
#include <logdepthbuf_vertex>
|
|
#include <clipping_planes_vertex>
|
|
#include <fog_vertex>
|
|
vViewPosition = - mvPosition.xyz;
|
|
}`,uE=`#define MATCAP
|
|
uniform vec3 diffuse;
|
|
uniform float opacity;
|
|
uniform sampler2D matcap;
|
|
varying vec3 vViewPosition;
|
|
#include <common>
|
|
#include <dithering_pars_fragment>
|
|
#include <color_pars_fragment>
|
|
#include <uv_pars_fragment>
|
|
#include <map_pars_fragment>
|
|
#include <alphamap_pars_fragment>
|
|
#include <alphatest_pars_fragment>
|
|
#include <alphahash_pars_fragment>
|
|
#include <fog_pars_fragment>
|
|
#include <normal_pars_fragment>
|
|
#include <bumpmap_pars_fragment>
|
|
#include <normalmap_pars_fragment>
|
|
#include <logdepthbuf_pars_fragment>
|
|
#include <clipping_planes_pars_fragment>
|
|
void main() {
|
|
vec4 diffuseColor = vec4( diffuse, opacity );
|
|
#include <clipping_planes_fragment>
|
|
#include <logdepthbuf_fragment>
|
|
#include <map_fragment>
|
|
#include <color_fragment>
|
|
#include <alphamap_fragment>
|
|
#include <alphatest_fragment>
|
|
#include <alphahash_fragment>
|
|
#include <normal_fragment_begin>
|
|
#include <normal_fragment_maps>
|
|
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 <opaque_fragment>
|
|
#include <tonemapping_fragment>
|
|
#include <colorspace_fragment>
|
|
#include <fog_fragment>
|
|
#include <premultiplied_alpha_fragment>
|
|
#include <dithering_fragment>
|
|
}`,hE=`#define NORMAL
|
|
#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
|
|
varying vec3 vViewPosition;
|
|
#endif
|
|
#include <common>
|
|
#include <batching_pars_vertex>
|
|
#include <uv_pars_vertex>
|
|
#include <displacementmap_pars_vertex>
|
|
#include <normal_pars_vertex>
|
|
#include <morphtarget_pars_vertex>
|
|
#include <skinning_pars_vertex>
|
|
#include <logdepthbuf_pars_vertex>
|
|
#include <clipping_planes_pars_vertex>
|
|
void main() {
|
|
#include <uv_vertex>
|
|
#include <batching_vertex>
|
|
#include <beginnormal_vertex>
|
|
#include <morphinstance_vertex>
|
|
#include <morphnormal_vertex>
|
|
#include <skinbase_vertex>
|
|
#include <skinnormal_vertex>
|
|
#include <defaultnormal_vertex>
|
|
#include <normal_vertex>
|
|
#include <begin_vertex>
|
|
#include <morphtarget_vertex>
|
|
#include <skinning_vertex>
|
|
#include <displacementmap_vertex>
|
|
#include <project_vertex>
|
|
#include <logdepthbuf_vertex>
|
|
#include <clipping_planes_vertex>
|
|
#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 <uv_pars_fragment>
|
|
#include <normal_pars_fragment>
|
|
#include <bumpmap_pars_fragment>
|
|
#include <normalmap_pars_fragment>
|
|
#include <logdepthbuf_pars_fragment>
|
|
#include <clipping_planes_pars_fragment>
|
|
void main() {
|
|
vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );
|
|
#include <clipping_planes_fragment>
|
|
#include <logdepthbuf_fragment>
|
|
#include <normal_fragment_begin>
|
|
#include <normal_fragment_maps>
|
|
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 <common>
|
|
#include <batching_pars_vertex>
|
|
#include <uv_pars_vertex>
|
|
#include <displacementmap_pars_vertex>
|
|
#include <envmap_pars_vertex>
|
|
#include <color_pars_vertex>
|
|
#include <fog_pars_vertex>
|
|
#include <normal_pars_vertex>
|
|
#include <morphtarget_pars_vertex>
|
|
#include <skinning_pars_vertex>
|
|
#include <shadowmap_pars_vertex>
|
|
#include <logdepthbuf_pars_vertex>
|
|
#include <clipping_planes_pars_vertex>
|
|
void main() {
|
|
#include <uv_vertex>
|
|
#include <color_vertex>
|
|
#include <morphcolor_vertex>
|
|
#include <batching_vertex>
|
|
#include <beginnormal_vertex>
|
|
#include <morphinstance_vertex>
|
|
#include <morphnormal_vertex>
|
|
#include <skinbase_vertex>
|
|
#include <skinnormal_vertex>
|
|
#include <defaultnormal_vertex>
|
|
#include <normal_vertex>
|
|
#include <begin_vertex>
|
|
#include <morphtarget_vertex>
|
|
#include <skinning_vertex>
|
|
#include <displacementmap_vertex>
|
|
#include <project_vertex>
|
|
#include <logdepthbuf_vertex>
|
|
#include <clipping_planes_vertex>
|
|
vViewPosition = - mvPosition.xyz;
|
|
#include <worldpos_vertex>
|
|
#include <envmap_vertex>
|
|
#include <shadowmap_vertex>
|
|
#include <fog_vertex>
|
|
}`,pE=`#define PHONG
|
|
uniform vec3 diffuse;
|
|
uniform vec3 emissive;
|
|
uniform vec3 specular;
|
|
uniform float shininess;
|
|
uniform float opacity;
|
|
#include <common>
|
|
#include <dithering_pars_fragment>
|
|
#include <color_pars_fragment>
|
|
#include <uv_pars_fragment>
|
|
#include <map_pars_fragment>
|
|
#include <alphamap_pars_fragment>
|
|
#include <alphatest_pars_fragment>
|
|
#include <alphahash_pars_fragment>
|
|
#include <aomap_pars_fragment>
|
|
#include <lightmap_pars_fragment>
|
|
#include <emissivemap_pars_fragment>
|
|
#include <cube_uv_reflection_fragment>
|
|
#include <envmap_common_pars_fragment>
|
|
#include <envmap_pars_fragment>
|
|
#include <envmap_physical_pars_fragment>
|
|
#include <fog_pars_fragment>
|
|
#include <bsdfs>
|
|
#include <lights_pars_begin>
|
|
#include <normal_pars_fragment>
|
|
#include <lights_phong_pars_fragment>
|
|
#include <shadowmap_pars_fragment>
|
|
#include <bumpmap_pars_fragment>
|
|
#include <normalmap_pars_fragment>
|
|
#include <specularmap_pars_fragment>
|
|
#include <logdepthbuf_pars_fragment>
|
|
#include <clipping_planes_pars_fragment>
|
|
void main() {
|
|
vec4 diffuseColor = vec4( diffuse, opacity );
|
|
#include <clipping_planes_fragment>
|
|
ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
|
|
vec3 totalEmissiveRadiance = emissive;
|
|
#include <logdepthbuf_fragment>
|
|
#include <map_fragment>
|
|
#include <color_fragment>
|
|
#include <alphamap_fragment>
|
|
#include <alphatest_fragment>
|
|
#include <alphahash_fragment>
|
|
#include <specularmap_fragment>
|
|
#include <normal_fragment_begin>
|
|
#include <normal_fragment_maps>
|
|
#include <emissivemap_fragment>
|
|
#include <lights_phong_fragment>
|
|
#include <lights_fragment_begin>
|
|
#include <lights_fragment_maps>
|
|
#include <lights_fragment_end>
|
|
#include <aomap_fragment>
|
|
vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;
|
|
#include <envmap_fragment>
|
|
#include <opaque_fragment>
|
|
#include <tonemapping_fragment>
|
|
#include <colorspace_fragment>
|
|
#include <fog_fragment>
|
|
#include <premultiplied_alpha_fragment>
|
|
#include <dithering_fragment>
|
|
}`,mE=`#define STANDARD
|
|
varying vec3 vViewPosition;
|
|
#ifdef USE_TRANSMISSION
|
|
varying vec3 vWorldPosition;
|
|
#endif
|
|
#include <common>
|
|
#include <batching_pars_vertex>
|
|
#include <uv_pars_vertex>
|
|
#include <displacementmap_pars_vertex>
|
|
#include <color_pars_vertex>
|
|
#include <fog_pars_vertex>
|
|
#include <normal_pars_vertex>
|
|
#include <morphtarget_pars_vertex>
|
|
#include <skinning_pars_vertex>
|
|
#include <shadowmap_pars_vertex>
|
|
#include <logdepthbuf_pars_vertex>
|
|
#include <clipping_planes_pars_vertex>
|
|
void main() {
|
|
#include <uv_vertex>
|
|
#include <color_vertex>
|
|
#include <morphinstance_vertex>
|
|
#include <morphcolor_vertex>
|
|
#include <batching_vertex>
|
|
#include <beginnormal_vertex>
|
|
#include <morphnormal_vertex>
|
|
#include <skinbase_vertex>
|
|
#include <skinnormal_vertex>
|
|
#include <defaultnormal_vertex>
|
|
#include <normal_vertex>
|
|
#include <begin_vertex>
|
|
#include <morphtarget_vertex>
|
|
#include <skinning_vertex>
|
|
#include <displacementmap_vertex>
|
|
#include <project_vertex>
|
|
#include <logdepthbuf_vertex>
|
|
#include <clipping_planes_vertex>
|
|
vViewPosition = - mvPosition.xyz;
|
|
#include <worldpos_vertex>
|
|
#include <shadowmap_vertex>
|
|
#include <fog_vertex>
|
|
#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 <common>
|
|
#include <dithering_pars_fragment>
|
|
#include <color_pars_fragment>
|
|
#include <uv_pars_fragment>
|
|
#include <map_pars_fragment>
|
|
#include <alphamap_pars_fragment>
|
|
#include <alphatest_pars_fragment>
|
|
#include <alphahash_pars_fragment>
|
|
#include <aomap_pars_fragment>
|
|
#include <lightmap_pars_fragment>
|
|
#include <emissivemap_pars_fragment>
|
|
#include <iridescence_fragment>
|
|
#include <cube_uv_reflection_fragment>
|
|
#include <envmap_common_pars_fragment>
|
|
#include <envmap_physical_pars_fragment>
|
|
#include <fog_pars_fragment>
|
|
#include <lights_pars_begin>
|
|
#include <normal_pars_fragment>
|
|
#include <lights_physical_pars_fragment>
|
|
#include <transmission_pars_fragment>
|
|
#include <shadowmap_pars_fragment>
|
|
#include <bumpmap_pars_fragment>
|
|
#include <normalmap_pars_fragment>
|
|
#include <clearcoat_pars_fragment>
|
|
#include <iridescence_pars_fragment>
|
|
#include <roughnessmap_pars_fragment>
|
|
#include <metalnessmap_pars_fragment>
|
|
#include <logdepthbuf_pars_fragment>
|
|
#include <clipping_planes_pars_fragment>
|
|
void main() {
|
|
vec4 diffuseColor = vec4( diffuse, opacity );
|
|
#include <clipping_planes_fragment>
|
|
ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
|
|
vec3 totalEmissiveRadiance = emissive;
|
|
#include <logdepthbuf_fragment>
|
|
#include <map_fragment>
|
|
#include <color_fragment>
|
|
#include <alphamap_fragment>
|
|
#include <alphatest_fragment>
|
|
#include <alphahash_fragment>
|
|
#include <roughnessmap_fragment>
|
|
#include <metalnessmap_fragment>
|
|
#include <normal_fragment_begin>
|
|
#include <normal_fragment_maps>
|
|
#include <clearcoat_normal_fragment_begin>
|
|
#include <clearcoat_normal_fragment_maps>
|
|
#include <emissivemap_fragment>
|
|
#include <lights_physical_fragment>
|
|
#include <lights_fragment_begin>
|
|
#include <lights_fragment_maps>
|
|
#include <lights_fragment_end>
|
|
#include <aomap_fragment>
|
|
vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;
|
|
vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;
|
|
#include <transmission_fragment>
|
|
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 <opaque_fragment>
|
|
#include <tonemapping_fragment>
|
|
#include <colorspace_fragment>
|
|
#include <fog_fragment>
|
|
#include <premultiplied_alpha_fragment>
|
|
#include <dithering_fragment>
|
|
}`,_E=`#define TOON
|
|
varying vec3 vViewPosition;
|
|
#include <common>
|
|
#include <batching_pars_vertex>
|
|
#include <uv_pars_vertex>
|
|
#include <displacementmap_pars_vertex>
|
|
#include <color_pars_vertex>
|
|
#include <fog_pars_vertex>
|
|
#include <normal_pars_vertex>
|
|
#include <morphtarget_pars_vertex>
|
|
#include <skinning_pars_vertex>
|
|
#include <shadowmap_pars_vertex>
|
|
#include <logdepthbuf_pars_vertex>
|
|
#include <clipping_planes_pars_vertex>
|
|
void main() {
|
|
#include <uv_vertex>
|
|
#include <color_vertex>
|
|
#include <morphinstance_vertex>
|
|
#include <morphcolor_vertex>
|
|
#include <batching_vertex>
|
|
#include <beginnormal_vertex>
|
|
#include <morphnormal_vertex>
|
|
#include <skinbase_vertex>
|
|
#include <skinnormal_vertex>
|
|
#include <defaultnormal_vertex>
|
|
#include <normal_vertex>
|
|
#include <begin_vertex>
|
|
#include <morphtarget_vertex>
|
|
#include <skinning_vertex>
|
|
#include <displacementmap_vertex>
|
|
#include <project_vertex>
|
|
#include <logdepthbuf_vertex>
|
|
#include <clipping_planes_vertex>
|
|
vViewPosition = - mvPosition.xyz;
|
|
#include <worldpos_vertex>
|
|
#include <shadowmap_vertex>
|
|
#include <fog_vertex>
|
|
}`,xE=`#define TOON
|
|
uniform vec3 diffuse;
|
|
uniform vec3 emissive;
|
|
uniform float opacity;
|
|
#include <common>
|
|
#include <dithering_pars_fragment>
|
|
#include <color_pars_fragment>
|
|
#include <uv_pars_fragment>
|
|
#include <map_pars_fragment>
|
|
#include <alphamap_pars_fragment>
|
|
#include <alphatest_pars_fragment>
|
|
#include <alphahash_pars_fragment>
|
|
#include <aomap_pars_fragment>
|
|
#include <lightmap_pars_fragment>
|
|
#include <emissivemap_pars_fragment>
|
|
#include <gradientmap_pars_fragment>
|
|
#include <fog_pars_fragment>
|
|
#include <bsdfs>
|
|
#include <lights_pars_begin>
|
|
#include <normal_pars_fragment>
|
|
#include <lights_toon_pars_fragment>
|
|
#include <shadowmap_pars_fragment>
|
|
#include <bumpmap_pars_fragment>
|
|
#include <normalmap_pars_fragment>
|
|
#include <logdepthbuf_pars_fragment>
|
|
#include <clipping_planes_pars_fragment>
|
|
void main() {
|
|
vec4 diffuseColor = vec4( diffuse, opacity );
|
|
#include <clipping_planes_fragment>
|
|
ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
|
|
vec3 totalEmissiveRadiance = emissive;
|
|
#include <logdepthbuf_fragment>
|
|
#include <map_fragment>
|
|
#include <color_fragment>
|
|
#include <alphamap_fragment>
|
|
#include <alphatest_fragment>
|
|
#include <alphahash_fragment>
|
|
#include <normal_fragment_begin>
|
|
#include <normal_fragment_maps>
|
|
#include <emissivemap_fragment>
|
|
#include <lights_toon_fragment>
|
|
#include <lights_fragment_begin>
|
|
#include <lights_fragment_maps>
|
|
#include <lights_fragment_end>
|
|
#include <aomap_fragment>
|
|
vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
|
|
#include <opaque_fragment>
|
|
#include <tonemapping_fragment>
|
|
#include <colorspace_fragment>
|
|
#include <fog_fragment>
|
|
#include <premultiplied_alpha_fragment>
|
|
#include <dithering_fragment>
|
|
}`,yE=`uniform float size;
|
|
uniform float scale;
|
|
#include <common>
|
|
#include <color_pars_vertex>
|
|
#include <fog_pars_vertex>
|
|
#include <morphtarget_pars_vertex>
|
|
#include <logdepthbuf_pars_vertex>
|
|
#include <clipping_planes_pars_vertex>
|
|
#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 <color_vertex>
|
|
#include <morphinstance_vertex>
|
|
#include <morphcolor_vertex>
|
|
#include <begin_vertex>
|
|
#include <morphtarget_vertex>
|
|
#include <project_vertex>
|
|
gl_PointSize = size;
|
|
#ifdef USE_SIZEATTENUATION
|
|
bool isPerspective = isPerspectiveMatrix( projectionMatrix );
|
|
if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );
|
|
#endif
|
|
#include <logdepthbuf_vertex>
|
|
#include <clipping_planes_vertex>
|
|
#include <worldpos_vertex>
|
|
#include <fog_vertex>
|
|
}`,vE=`uniform vec3 diffuse;
|
|
uniform float opacity;
|
|
#include <common>
|
|
#include <color_pars_fragment>
|
|
#include <map_particle_pars_fragment>
|
|
#include <alphatest_pars_fragment>
|
|
#include <alphahash_pars_fragment>
|
|
#include <fog_pars_fragment>
|
|
#include <logdepthbuf_pars_fragment>
|
|
#include <clipping_planes_pars_fragment>
|
|
void main() {
|
|
vec4 diffuseColor = vec4( diffuse, opacity );
|
|
#include <clipping_planes_fragment>
|
|
vec3 outgoingLight = vec3( 0.0 );
|
|
#include <logdepthbuf_fragment>
|
|
#include <map_particle_fragment>
|
|
#include <color_fragment>
|
|
#include <alphatest_fragment>
|
|
#include <alphahash_fragment>
|
|
outgoingLight = diffuseColor.rgb;
|
|
#include <opaque_fragment>
|
|
#include <tonemapping_fragment>
|
|
#include <colorspace_fragment>
|
|
#include <fog_fragment>
|
|
#include <premultiplied_alpha_fragment>
|
|
}`,SE=`#include <common>
|
|
#include <batching_pars_vertex>
|
|
#include <fog_pars_vertex>
|
|
#include <morphtarget_pars_vertex>
|
|
#include <skinning_pars_vertex>
|
|
#include <logdepthbuf_pars_vertex>
|
|
#include <shadowmap_pars_vertex>
|
|
void main() {
|
|
#include <batching_vertex>
|
|
#include <beginnormal_vertex>
|
|
#include <morphinstance_vertex>
|
|
#include <morphnormal_vertex>
|
|
#include <skinbase_vertex>
|
|
#include <skinnormal_vertex>
|
|
#include <defaultnormal_vertex>
|
|
#include <begin_vertex>
|
|
#include <morphtarget_vertex>
|
|
#include <skinning_vertex>
|
|
#include <project_vertex>
|
|
#include <logdepthbuf_vertex>
|
|
#include <worldpos_vertex>
|
|
#include <shadowmap_vertex>
|
|
#include <fog_vertex>
|
|
}`,bE=`uniform vec3 color;
|
|
uniform float opacity;
|
|
#include <common>
|
|
#include <fog_pars_fragment>
|
|
#include <bsdfs>
|
|
#include <lights_pars_begin>
|
|
#include <logdepthbuf_pars_fragment>
|
|
#include <shadowmap_pars_fragment>
|
|
#include <shadowmask_pars_fragment>
|
|
void main() {
|
|
#include <logdepthbuf_fragment>
|
|
gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );
|
|
#include <tonemapping_fragment>
|
|
#include <colorspace_fragment>
|
|
#include <fog_fragment>
|
|
#include <premultiplied_alpha_fragment>
|
|
}`,TE=`uniform float rotation;
|
|
uniform vec2 center;
|
|
#include <common>
|
|
#include <uv_pars_vertex>
|
|
#include <fog_pars_vertex>
|
|
#include <logdepthbuf_pars_vertex>
|
|
#include <clipping_planes_pars_vertex>
|
|
void main() {
|
|
#include <uv_vertex>
|
|
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 <logdepthbuf_vertex>
|
|
#include <clipping_planes_vertex>
|
|
#include <fog_vertex>
|
|
}`,ME=`uniform vec3 diffuse;
|
|
uniform float opacity;
|
|
#include <common>
|
|
#include <uv_pars_fragment>
|
|
#include <map_pars_fragment>
|
|
#include <alphamap_pars_fragment>
|
|
#include <alphatest_pars_fragment>
|
|
#include <alphahash_pars_fragment>
|
|
#include <fog_pars_fragment>
|
|
#include <logdepthbuf_pars_fragment>
|
|
#include <clipping_planes_pars_fragment>
|
|
void main() {
|
|
vec4 diffuseColor = vec4( diffuse, opacity );
|
|
#include <clipping_planes_fragment>
|
|
vec3 outgoingLight = vec3( 0.0 );
|
|
#include <logdepthbuf_fragment>
|
|
#include <map_fragment>
|
|
#include <alphamap_fragment>
|
|
#include <alphatest_fragment>
|
|
#include <alphahash_fragment>
|
|
outgoingLight = diffuseColor.rgb;
|
|
#include <opaque_fragment>
|
|
#include <tonemapping_fragment>
|
|
#include <colorspace_fragment>
|
|
#include <fog_fragment>
|
|
}`,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<t;L++)U[L]=0,G[L]=0,V[L]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:U,enabledAttributes:G,attributeDivisors:V,object:N,attributes:{},index:null}}function f(N,U,G,V){const L=s.attributes,B=U.attributes;let H=0;const ie=G.getAttributes();for(const ce in ie)if(ie[ce].location>=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<G;U++)N[U]=0}function m(N){_(N,0)}function _(N,U){const G=s.newAttributes,V=s.enabledAttributes,L=s.attributeDivisors;G[N]=1,V[N]===0&&(r.enableVertexAttribArray(N),V[N]=1),L[N]!==U&&(r.vertexAttribDivisor(N,U),L[N]=U)}function x(){const N=s.newAttributes,U=s.enabledAttributes;for(let G=0,V=U.length;G<V;G++)U[G]!==N[G]&&(r.disableVertexAttribArray(G),U[G]=0)}function v(N,U,G,V,L,B,H){H===!0?r.vertexAttribIPointer(N,U,G,L,B):r.vertexAttribPointer(N,U,G,V,L,B)}function S(N,U,G,V){g();const L=V.attributes,B=G.getAttributes(),H=U.defaultAttributeValues;for(const ie in B){const ce=B[ie];if(ce.location>=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;we<ce.locationSize;we++)_(ce.location+we,le.meshPerAttribute);N.isInstancedMesh!==!0&&V._maxInstanceCount===void 0&&(V._maxInstanceCount=le.meshPerAttribute*le.count)}else for(let we=0;we<ce.locationSize;we++)m(ce.location+we);r.bindBuffer(r.ARRAY_BUFFER,Mt);for(let we=0;we<ce.locationSize;we++)v(ce.location+we,ke/ce.locationSize,oe,Ce,Ne*W,(Le+ke/ce.locationSize*we)*W,se)}else{if(ve.isInstancedBufferAttribute){for(let le=0;le<ce.locationSize;le++)_(ce.location+le,ve.meshPerAttribute);N.isInstancedMesh!==!0&&V._maxInstanceCount===void 0&&(V._maxInstanceCount=ve.meshPerAttribute*ve.count)}else for(let le=0;le<ce.locationSize;le++)m(ce.location+le);r.bindBuffer(r.ARRAY_BUFFER,Mt);for(let le=0;le<ce.locationSize;le++)v(ce.location+le,ke/ce.locationSize,oe,Ce,ke*W,ke/ce.locationSize*le*W,se)}}else if(H!==void 0){const Ce=H[ie];if(Ce!==void 0)switch(Ce.length){case 2:r.vertexAttrib2fv(ce.location,Ce);break;case 3:r.vertexAttrib3fv(ce.location,Ce);break;case 4:r.vertexAttrib4fv(ce.location,Ce);break;default:r.vertexAttrib1fv(ce.location,Ce)}}}}x()}function E(){R();for(const N in n){const U=n[N];for(const G in U){const V=U[G];for(const L in V){const B=V[L];for(const H in B)u(B[H].object),delete B[H];delete V[L]}}delete n[N]}}function T(N){if(n[N.id]===void 0)return;const U=n[N.id];for(const G in U){const V=U[G];for(const L in V){const B=V[L];for(const H in B)u(B[H].object),delete B[H];delete V[L]}}delete n[N.id]}function A(N){for(const U in n){const G=n[U];for(const V in G){const L=G[V];if(L[N.id]===void 0)continue;const B=L[N.id];for(const H in B)u(B[H].object),delete B[H];delete L[N.id]}}}function y(N){for(const U in n){const G=n[U],V=N.isInstancedMesh===!0?N.id:0,L=G[V];if(L!==void 0){for(const B in L){const H=L[B];for(const ie in H)u(H[ie].object),delete H[ie];delete L[B]}delete G[V],Object.keys(G).length===0&&delete n[U]}}}function R(){P(),o=!0,s!==i&&(s=i,c(s.object))}function P(){i.geometry=null,i.program=null,i.wireframe=!1}return{setup:a,reset:R,resetDefaultState:P,dispose:E,releaseStatesOfGeometry:T,releaseStatesOfObject:y,releaseStatesOfProgram:A,initAttributes:g,enableAttribute:m,disableUnusedAttributes:x}}function wE(r,e,t){let n;function i(l){n=l}function s(l,c){r.drawArrays(n,l,c),t.update(c,n,1)}function o(l,c,u){u!==0&&(r.drawArraysInstanced(n,l,c,u),t.update(c,n,u))}function a(l,c,u){if(u===0)return;e.get("WEBGL_multi_draw").multiDrawArraysWEBGL(n,l,0,c,0,u);let d=0;for(let f=0;f<u;f++)d+=c[f];t.update(d,n,1)}this.setMode=i,this.render=s,this.renderInstances=o,this.renderMultiDraw=a}function CE(r,e,t,n){let i;function s(){if(i!==void 0)return i;if(e.has("EXT_texture_filter_anisotropic")===!0){const A=e.get("EXT_texture_filter_anisotropic");i=r.getParameter(A.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else i=0;return i}function o(A){return!(A!==an&&n.convert(A)!==r.getParameter(r.IMPLEMENTATION_COLOR_READ_FORMAT))}function a(A){const y=A===en&&(e.has("EXT_color_buffer_half_float")||e.has("EXT_color_buffer_float"));return!(A!==$t&&n.convert(A)!==r.getParameter(r.IMPLEMENTATION_COLOR_READ_TYPE)&&A!==Zt&&!y)}function l(A){if(A==="highp"){if(r.getShaderPrecisionFormat(r.VERTEX_SHADER,r.HIGH_FLOAT).precision>0&&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;e<this._lodMeshes.length;e++)this._lodMeshes[e].geometry.dispose()}_cleanup(e){this._renderer.setRenderTarget(jh,Yh,Kh),this._renderer.xr.enabled=Zh,e.scissorTest=!1,ko(e,0,0,e.width,e.height)}_fromTexture(e,t){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),jh=this._renderer.getRenderTarget(),Yh=this._renderer.getActiveCubeFace(),Kh=this._renderer.getActiveMipmapLevel(),Zh=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;const n=t||this._allocateTargets();return this._textureToCubeUV(e,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTargets(){const e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize,n={magFilter:Ut,minFilter:Ut,generateMipmaps:!1,type:en,format:an,colorSpace:ql,depthBuffer:!1},i=Xm(e,t,n);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=Xm(e,t,n);const{_lodMax:s}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=LE(s)),this._blurMaterial=FE(s,e,t),this._ggxMaterial=UE(s,e,t)}return i}_compileMaterial(e){const t=new gn(new Pn,e);this._renderer.compile(t,nl)}_sceneToCubeUV(e,t,n,i,s){const l=new Rn(90,1,t,n),c=[1,-1,1,1,1,1],u=[1,1,1,-1,-1,-1],h=this._renderer,d=h.autoClear,f=h.toneMapping;h.getClearColor(Wm),h.toneMapping=Un,h.autoClear=!1,h.state.buffers.depth.getReversed()&&(h.setRenderTarget(i),h.clearDepth(),h.setRenderTarget(null)),this._backgroundBox===null&&(this._backgroundBox=new gn(new yo,new us({name:"PMREM.Background",side:Pt,depthWrite:!1,depthTest:!1})));const g=this._backgroundBox,m=g.material;let _=!1;const x=e.background;x?x.isColor&&(m.color.copy(x),e.background=null,_=!0):(m.color.copy(Wm),_=!0);for(let v=0;v<6;v++){const S=v%3;S===0?(l.up.set(0,c[v],0),l.position.set(s.x,s.y,s.z),l.lookAt(s.x+u[v],s.y,s.z)):S===1?(l.up.set(0,0,c[v]),l.position.set(s.x,s.y,s.z),l.lookAt(s.x,s.y+u[v],s.z)):(l.up.set(0,c[v],0),l.position.set(s.x,s.y,s.z),l.lookAt(s.x,s.y,s.z+u[v]));const E=this._cubeSize;ko(i,S*E,v>2?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;s<i;s++)this._applyGGXFilter(e,s-1,s);t.autoClear=n}_applyGGXFilter(e,t,n){const i=this._renderer,s=this._pingPongRenderTarget,o=this._ggxMaterial,a=this._lodMeshes[n];a.material=o;const l=o.uniforms,c=n/(this._lodMeshes.length-1),u=t/(this._lodMeshes.length-1),h=Math.sqrt(c*c-u*u),d=0+c*1.25,f=h*d,{_lodMax:p}=this,g=this._sizeLods[n],m=3*g*(n>p-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;A<qr;++A){const y=A/g,R=Math.exp(-y*y/2);_.push(R),A===0?x+=R:A<m&&(x+=2*R)}for(let A=0;A<_.length;A++)_[A]=_[A]/x;d.envMap.value=e.texture,d.samples.value=m,d.weights.value=_,d.latitudinal.value=o==="latitudinal",a&&(d.poleAxis.value=a);const{_lodMax:v}=this;d.dTheta.value=p,d.mipInt.value=v-n;const S=this._sizeLods[i],E=3*S*(i>v-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;o<s;o++){const a=Math.pow(2,i);e.push(a);let l=1/a;o>r-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;T<f;T++){const A=T%3*2/3-1,y=T>2?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 <cube_uv_reflection_fragment>
|
|
|
|
#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 <cube_uv_reflection_fragment>
|
|
|
|
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 <common>
|
|
|
|
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 <begin_vertex>
|
|
#include <project_vertex>
|
|
|
|
}
|
|
`,fragmentShader:`
|
|
|
|
uniform sampler2D tEquirect;
|
|
|
|
varying vec3 vWorldDirection;
|
|
|
|
#include <common>
|
|
|
|
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<p;g++)d[g]!==void 0&&f++;return f===p}function c(d){const f=d.target;f.removeEventListener("dispose",c);const p=e.get(f);p!==void 0&&(e.delete(f),p.dispose())}function u(d){const f=d.target;f.removeEventListener("dispose",u);const p=t.get(f);p!==void 0&&(t.delete(f),p.dispose())}function h(){e=new WeakMap,t=new WeakMap,n!==null&&(n.dispose(),n=null)}return{get:i,dispose:h}}function BE(r){const e={};function t(n){if(e[n]!==void 0)return e[n];const i=r.getExtension(n);return e[n]=i,i}return{has:function(n){return t(n)!==null},init:function(){t("EXT_color_buffer_float"),t("WEBGL_clip_cull_distance"),t("OES_texture_float_linear"),t("EXT_color_buffer_half_float"),t("WEBGL_multisampled_render_to_texture"),t("WEBGL_render_shared_exponent")},get:function(n){const i=t(n);return i===null&&Yt("WebGLRenderer: "+n+" extension not supported."),i}}}function OE(r,e,t,n){const i={},s=new WeakMap;function o(h){const d=h.target;d.index!==null&&e.remove(d.index);for(const p in d.attributes)e.remove(d.attributes[p]);d.removeEventListener("dispose",o),delete i[d.id];const f=s.get(d);f&&(e.remove(f),s.delete(d)),n.releaseStatesOfGeometry(d),d.isInstancedBufferGeometry===!0&&delete d._maxInstanceCount,t.memory.geometries--}function a(h,d){return i[d.id]===!0||(d.addEventListener("dispose",o),i[d.id]=!0,t.memory.geometries++),d}function l(h){const d=h.attributes;for(const f in d)e.update(d[f],r.ARRAY_BUFFER)}function c(h){const d=[],f=h.index,p=h.attributes.position;let g=0;if(p===void 0)return;if(f!==null){const x=f.array;g=f.version;for(let v=0,S=x.length;v<S;v+=3){const E=x[v+0],T=x[v+1],A=x[v+2];d.push(E,T,T,A,A,E)}}else{const x=p.array;g=p.version;for(let v=0,S=x.length/3-1;v<S;v+=3){const E=v+0,T=v+1,A=v+2;d.push(E,T,T,A,A,E)}}const m=new(p.count>=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.version<f.version&&c(h)}else c(h);return s.get(h)}return{get:a,update:l,getWireframeAttribute:u}}function kE(r,e,t){let n;function i(h){n=h}let s,o;function a(h){s=h.type,o=h.bytesPerElement}function l(h,d){r.drawElements(n,d,s,h*o),t.update(d,n,1)}function c(h,d,f){f!==0&&(r.drawElementsInstanced(n,d,s,h*o,f),t.update(d,n,f))}function u(h,d,f){if(f===0)return;e.get("WEBGL_multi_draw").multiDrawElementsWEBGL(n,d,0,s,h,0,f);let g=0;for(let m=0;m<f;m++)g+=d[m];t.update(g,n,1)}this.setMode=i,this.setIndex=a,this.render=l,this.renderInstances=c,this.renderMultiDraw=u}function GE(r){const e={geometries:0,textures:0},t={frame:0,calls:0,triangles:0,points:0,lines:0};function n(s,o,a){switch(t.calls++,o){case r.TRIANGLES:t.triangles+=a*(s/3);break;case r.LINES:t.lines+=a*(s/2);break;case r.LINE_STRIP:t.lines+=a*(s-1);break;case r.LINE_LOOP:t.lines+=a*s;break;case r.POINTS:t.points+=a*s;break;default:ne("WebGLInfo: Unknown draw mode:",o);break}}function i(){t.calls=0,t.triangles=0,t.points=0,t.lines=0}return{memory:e,render:t,programs:null,autoReset:!0,reset:i,update:n}}function VE(r,e,t){const n=new WeakMap,i=new tt;function s(o,a,l){const c=o.morphTargetInfluences,u=a.morphAttributes.position||a.morphAttributes.normal||a.morphAttributes.color,h=u!==void 0?u.length:0;let d=n.get(a);if(d===void 0||d.count!==h){let R=function(){A.dispose(),n.delete(a),a.removeEventListener("dispose",R)};d!==void 0&&d.texture.dispose();const f=a.morphAttributes.position!==void 0,p=a.morphAttributes.normal!==void 0,g=a.morphAttributes.color!==void 0,m=a.morphAttributes.position||[],_=a.morphAttributes.normal||[],x=a.morphAttributes.color||[];let v=0;f===!0&&(v=1),p===!0&&(v=2),g===!0&&(v=3);let S=a.attributes.position.count*v,E=1;S>e.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<h;P++){const N=m[P],U=_[P],G=x[P],V=S*E*4*P;for(let L=0;L<N.count;L++){const B=L*y;f===!0&&(i.fromBufferAttribute(N,L),T[V+B+0]=i.x,T[V+B+1]=i.y,T[V+B+2]=i.z,T[V+B+3]=0),p===!0&&(i.fromBufferAttribute(U,L),T[V+B+4]=i.x,T[V+B+5]=i.y,T[V+B+6]=i.z,T[V+B+7]=0),g===!0&&(i.fromBufferAttribute(G,L),T[V+B+8]=i.x,T[V+B+9]=i.y,T[V+B+10]=i.z,T[V+B+11]=G.itemSize===4?i.w:1)}}d={count:h,texture:A,size:new de(S,E)},n.set(a,d),a.addEventListener("dispose",R)}if(o.isInstancedMesh===!0&&o.morphTexture!==null)l.getUniforms().setValue(r,"morphTexture",o.morphTexture,t);else{let f=0;for(let g=0;g<c.length;g++)f+=c[g];const p=a.morphTargetsRelative?1:1-f;l.getUniforms().setValue(r,"morphTargetBaseInfluence",p),l.getUniforms().setValue(r,"morphTargetInfluences",c)}l.getUniforms().setValue(r,"morphTargetsTexture",d.texture,t),l.getUniforms().setValue(r,"morphTargetsTextureSize",d.size)}return{update:s}}function zE(r,e,t,n,i){let s=new WeakMap;function o(c){const u=i.render.frame,h=c.geometry,d=e.get(c,h);if(s.get(d)!==u&&(e.update(d),s.set(d,u)),c.isInstancedMesh&&(c.hasEventListener("dispose",l)===!1&&c.addEventListener("dispose",l),s.get(c)!==u&&(t.update(c.instanceMatrix,r.ARRAY_BUFFER),c.instanceColor!==null&&t.update(c.instanceColor,r.ARRAY_BUFFER),s.set(c,u))),c.isSkinnedMesh){const f=c.skeleton;s.get(f)!==u&&(f.update(),s.set(f,u))}return d}function a(){s=new WeakMap}function l(c){const u=c.target;u.removeEventListener("dispose",l),n.releaseStatesOfObject(u),t.remove(u.instanceMatrix),u.instanceColor!==null&&t.remove(u.instanceColor)}return{update:o,dispose:a}}const HE={[Hf]:"LINEAR_TONE_MAPPING",[Wf]:"REINHARD_TONE_MAPPING",[$f]:"CINEON_TONE_MAPPING",[Xf]:"ACES_FILMIC_TONE_MAPPING",[qf]:"AGX_TONE_MAPPING",[jf]:"NEUTRAL_TONE_MAPPING",[_x]:"CUSTOM_TONE_MAPPING"};function WE(r,e,t,n,i){const s=new $i(e,t,{type:r,depthBuffer:n,stencilBuffer:i,depthTexture:n?new Xn(e,t):void 0}),o=new $i(e,t,{type:en,depthBuffer:!1,stencilBuffer:!1}),a=new Pn;a.setAttribute("position",new sn([-1,3,0,-1,-1,0,3,-1,0],3)),a.setAttribute("uv",new sn([0,2,0,0,2,0],2));const l=new vb({uniforms:{tDiffuse:{value:null}},vertexShader:`
|
|
precision highp float;
|
|
|
|
uniform mat4 modelViewMatrix;
|
|
uniform mat4 projectionMatrix;
|
|
|
|
attribute vec3 position;
|
|
attribute vec2 uv;
|
|
|
|
varying vec2 vUv;
|
|
|
|
void main() {
|
|
vUv = uv;
|
|
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
|
}`,fragmentShader:`
|
|
precision highp float;
|
|
|
|
uniform sampler2D tDiffuse;
|
|
|
|
varying vec2 vUv;
|
|
|
|
#include <tonemapping_pars_fragment>
|
|
#include <colorspace_pars_fragment>
|
|
|
|
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;S<m.length;S++){const E=m[S];E.setSize&&E.setSize(x,v)}},this.setEffects=function(x){m=x,_=m.length>0&&m[0].isRenderPass===!0;const v=s.width,S=s.height;for(let E=0;E<m.length;E++){const T=m[E];T.setSize&&T.setSize(v,S)}},this.begin=function(x,v){if(f||x.toneMapping===Un&&m.length===0)return!1;if(g=v,v!==null){const S=v.width,E=v.height;(s.width!==S||s.height!==E)&&this.setSize(S,E)}return _===!1&&x.setRenderTarget(s),p=x.toneMapping,x.toneMapping=Un,!0},this.hasRenderPass=function(){return _},this.end=function(x,v){x.toneMapping=p,f=!0;let S=s,E=o;for(let T=0;T<m.length;T++){const A=m[T];if(A.enabled!==!1&&(A.render(x,E,S,v),A.needsSwap!==!1)){const y=S;S=E,E=y}}if(h!==x.outputColorSpace||d!==x.toneMapping){h=x.outputColorSpace,d=x.toneMapping,l.defines={},Xe.getTransfer(h)===Ee&&(l.defines.SRGB_TRANSFER="");const T=HE[d];T&&(l.defines[T]=""),l.needsUpdate=!0}l.uniforms.tDiffuse.value=S.texture,x.setRenderTarget(g),x.render(c,u),g=null,f=!1},this.isCompositing=function(){return f},this.dispose=function(){s.depthTexture&&s.depthTexture.dispose(),s.dispose(),o.dispose(),a.dispose(),l.dispose()}}const Xx=new pn,rf=new Xn(1,1),qx=new sp,jx=new US,Yx=new Ga,Ym=[],Km=[],Zm=new Float32Array(16),Qm=new Float32Array(9),Jm=new Float32Array(4);function za(r,e,t){const n=r[0];if(n<=0||n>0)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;t<n;t++)if(r[t]!==e[t])return!1;return!0}function Mn(r,e){for(let t=0,n=e.length;t<n;t++)r[t]=e[t]}function th(r,e){let t=Km[e];t===void 0&&(t=new Int32Array(e),Km[e]=t);for(let n=0;n!==e;++n)t[n]=r.allocateTextureUnit();return t}function $E(r,e){const t=this.cache;t[0]!==e&&(r.uniform1f(this.addr,e),t[0]=e)}function XE(r,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(r.uniform2f(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(Tn(t,e))return;r.uniform2fv(this.addr,e),Mn(t,e)}}function qE(r,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(r.uniform3f(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else if(e.r!==void 0)(t[0]!==e.r||t[1]!==e.g||t[2]!==e.b)&&(r.uniform3f(this.addr,e.r,e.g,e.b),t[0]=e.r,t[1]=e.g,t[2]=e.b);else{if(Tn(t,e))return;r.uniform3fv(this.addr,e),Mn(t,e)}}function jE(r,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(r.uniform4f(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(Tn(t,e))return;r.uniform4fv(this.addr,e),Mn(t,e)}}function YE(r,e){const t=this.cache,n=e.elements;if(n===void 0){if(Tn(t,e))return;r.uniformMatrix2fv(this.addr,!1,e),Mn(t,e)}else{if(Tn(t,n))return;Jm.set(n),r.uniformMatrix2fv(this.addr,!1,Jm),Mn(t,n)}}function KE(r,e){const t=this.cache,n=e.elements;if(n===void 0){if(Tn(t,e))return;r.uniformMatrix3fv(this.addr,!1,e),Mn(t,e)}else{if(Tn(t,n))return;Qm.set(n),r.uniformMatrix3fv(this.addr,!1,Qm),Mn(t,n)}}function ZE(r,e){const t=this.cache,n=e.elements;if(n===void 0){if(Tn(t,e))return;r.uniformMatrix4fv(this.addr,!1,e),Mn(t,e)}else{if(Tn(t,n))return;Zm.set(n),r.uniformMatrix4fv(this.addr,!1,Zm),Mn(t,n)}}function QE(r,e){const t=this.cache;t[0]!==e&&(r.uniform1i(this.addr,e),t[0]=e)}function JE(r,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(r.uniform2i(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(Tn(t,e))return;r.uniform2iv(this.addr,e),Mn(t,e)}}function eA(r,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(r.uniform3i(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(Tn(t,e))return;r.uniform3iv(this.addr,e),Mn(t,e)}}function tA(r,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(r.uniform4i(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(Tn(t,e))return;r.uniform4iv(this.addr,e),Mn(t,e)}}function nA(r,e){const t=this.cache;t[0]!==e&&(r.uniform1ui(this.addr,e),t[0]=e)}function iA(r,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(r.uniform2ui(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(Tn(t,e))return;r.uniform2uiv(this.addr,e),Mn(t,e)}}function sA(r,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(r.uniform3ui(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(Tn(t,e))return;r.uniform3uiv(this.addr,e),Mn(t,e)}}function rA(r,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(r.uniform4ui(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(Tn(t,e))return;r.uniform4uiv(this.addr,e),Mn(t,e)}}function oA(r,e,t){const n=this.cache,i=t.allocateTextureUnit();n[0]!==i&&(r.uniform1i(this.addr,i),n[0]=i);let s;this.type===r.SAMPLER_2D_SHADOW?(rf.compareFunction=t.isReversedDepthBuffer()?$s:Dr,s=rf):s=Xx,t.setTexture2D(e||s,i)}function aA(r,e,t){const n=this.cache,i=t.allocateTextureUnit();n[0]!==i&&(r.uniform1i(this.addr,i),n[0]=i),t.setTexture3D(e||jx,i)}function lA(r,e,t){const n=this.cache,i=t.allocateTextureUnit();n[0]!==i&&(r.uniform1i(this.addr,i),n[0]=i),t.setTextureCube(e||Yx,i)}function cA(r,e,t){const n=this.cache,i=t.allocateTextureUnit();n[0]!==i&&(r.uniform1i(this.addr,i),n[0]=i),t.setTexture2DArray(e||qx,i)}function uA(r){switch(r){case 5126:return $E;case 35664:return XE;case 35665:return qE;case 35666:return jE;case 35674:return YE;case 35675:return KE;case 35676:return ZE;case 5124:case 35670:return QE;case 35667:case 35671:return JE;case 35668:case 35672:return eA;case 35669:case 35673:return tA;case 5125:return nA;case 36294:return iA;case 36295:return sA;case 36296:return rA;case 35678:case 36198:case 36298:case 36306:case 35682:return oA;case 35679:case 36299:case 36307:return aA;case 35680:case 36300:case 36308:case 36293:return lA;case 36289:case 36303:case 36311:case 36292:return cA}}function hA(r,e){r.uniform1fv(this.addr,e)}function dA(r,e){const t=za(e,this.size,2);r.uniform2fv(this.addr,t)}function fA(r,e){const t=za(e,this.size,3);r.uniform3fv(this.addr,t)}function pA(r,e){const t=za(e,this.size,4);r.uniform4fv(this.addr,t)}function mA(r,e){const t=za(e,this.size,4);r.uniformMatrix2fv(this.addr,!1,t)}function gA(r,e){const t=za(e,this.size,9);r.uniformMatrix3fv(this.addr,!1,t)}function _A(r,e){const t=za(e,this.size,16);r.uniformMatrix4fv(this.addr,!1,t)}function xA(r,e){r.uniform1iv(this.addr,e)}function yA(r,e){r.uniform2iv(this.addr,e)}function vA(r,e){r.uniform3iv(this.addr,e)}function SA(r,e){r.uniform4iv(this.addr,e)}function bA(r,e){r.uniform1uiv(this.addr,e)}function TA(r,e){r.uniform2uiv(this.addr,e)}function MA(r,e){r.uniform3uiv(this.addr,e)}function EA(r,e){r.uniform4uiv(this.addr,e)}function AA(r,e,t){const n=this.cache,i=e.length,s=th(t,i);Tn(n,s)||(r.uniform1iv(this.addr,s),Mn(n,s));let o;this.type===r.SAMPLER_2D_SHADOW?o=rf:o=Xx;for(let a=0;a!==i;++a)t.setTexture2D(e[a]||o,s[a])}function RA(r,e,t){const n=this.cache,i=e.length,s=th(t,i);Tn(n,s)||(r.uniform1iv(this.addr,s),Mn(n,s));for(let o=0;o!==i;++o)t.setTexture3D(e[o]||jx,s[o])}function wA(r,e,t){const n=this.cache,i=e.length,s=th(t,i);Tn(n,s)||(r.uniform1iv(this.addr,s),Mn(n,s));for(let o=0;o!==i;++o)t.setTextureCube(e[o]||Yx,s[o])}function CA(r,e,t){const n=this.cache,i=e.length,s=th(t,i);Tn(n,s)||(r.uniform1iv(this.addr,s),Mn(n,s));for(let o=0;o!==i;++o)t.setTexture2DArray(e[o]||qx,s[o])}function NA(r){switch(r){case 5126:return hA;case 35664:return dA;case 35665:return fA;case 35666:return pA;case 35674:return mA;case 35675:return gA;case 35676:return _A;case 5124:case 35670:return xA;case 35667:case 35671:return yA;case 35668:case 35672:return vA;case 35669:case 35673:return SA;case 5125:return bA;case 36294:return TA;case 36295:return MA;case 36296:return EA;case 35678:case 36198:case 36298:case 36306:case 35682:return AA;case 35679:case 36299:case 36307:return RA;case 35680:case 36300:case 36308:case 36293:return wA;case 36289:case 36303:case 36311:case 36292:return CA}}class PA{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.setValue=uA(t.type)}}class DA{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=NA(t.type)}}class LA{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,n){const i=this.seq;for(let s=0,o=i.length;s!==o;++s){const a=i[s];a.setValue(e,t[a.id],n)}}}const Qh=/(\w+)(\])?(\[|\.)?/g;function eg(r,e){r.seq.push(e),r.map[e.id]=e}function UA(r,e,t){const n=r.name,i=n.length;for(Qh.lastIndex=0;;){const s=Qh.exec(n),o=Qh.lastIndex;let a=s[1];const l=s[2]==="]",c=s[3];if(l&&(a=a|0),c===void 0||c==="["&&o+2===i){eg(t,c===void 0?new PA(a,r,e):new DA(a,r,e));break}else{let h=t.map[a];h===void 0&&(h=new LA(a),eg(t,h)),t=h}}}class bu{constructor(e,t){this.seq=[],this.map={};const n=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let o=0;o<n;++o){const a=e.getActiveUniform(t,o),l=e.getUniformLocation(t,a.name);UA(a,l,this)}const i=[],s=[];for(const o of this.seq)o.type===e.SAMPLER_2D_SHADOW||o.type===e.SAMPLER_CUBE_SHADOW||o.type===e.SAMPLER_2D_ARRAY_SHADOW?i.push(o):s.push(o);i.length>0&&(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<s;o++){const a=o+1;n.push(`${a===e?">":" "} ${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<n;i++){const s=r.getActiveAttrib(e,i),o=s.name;let a=1;s.type===r.FLOAT_MAT2&&(a=2),s.type===r.FLOAT_MAT3&&(a=3),s.type===r.FLOAT_MAT4&&(a=4),t[o]={type:s.type,location:r.getAttribLocation(e,o),locationSize:a}}return t}function _l(r){return r!==""}function sg(r,e){const t=e.numSpotLightShadows+e.numSpotLightMaps-e.numSpotLightShadowsWithMaps;return r.replace(/NUM_DIR_LIGHTS/g,e.numDirLights).replace(/NUM_SPOT_LIGHTS/g,e.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,e.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,t).replace(/NUM_RECT_AREA_LIGHTS/g,e.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,e.numPointLights).replace(/NUM_HEMI_LIGHTS/g,e.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,e.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,e.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,e.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,e.numPointLightShadows)}function rg(r,e){return r.replace(/NUM_CLIPPING_PLANES/g,e.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,e.numClippingPlanes-e.numClipIntersection)}const XA=/^[ \t]*#include +<([\w\d./]+)>/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);s<parseInt(t);s++)i+=n.replace(/\[\s*i\s*\]/g,"[ "+s+" ]").replace(/UNROLLED_LOOP_INDEX/g,s);return i}function ag(r){let e=`precision ${r.precision} float;
|
|
precision ${r.precision} int;
|
|
precision ${r.precision} sampler2D;
|
|
precision ${r.precision} samplerCube;
|
|
precision ${r.precision} sampler3D;
|
|
precision ${r.precision} sampler2DArray;
|
|
precision ${r.precision} sampler2DShadow;
|
|
precision ${r.precision} samplerCubeShadow;
|
|
precision ${r.precision} sampler2DArrayShadow;
|
|
precision ${r.precision} isampler2D;
|
|
precision ${r.precision} isampler3D;
|
|
precision ${r.precision} isamplerCube;
|
|
precision ${r.precision} isampler2DArray;
|
|
precision ${r.precision} usampler2D;
|
|
precision ${r.precision} usampler3D;
|
|
precision ${r.precision} usamplerCube;
|
|
precision ${r.precision} usampler2DArray;
|
|
`;return r.precision==="highp"?e+=`
|
|
#define HIGH_PRECISION`:r.precision==="mediump"?e+=`
|
|
#define MEDIUM_PRECISION`:r.precision==="lowp"&&(e+=`
|
|
#define LOW_PRECISION`),e}const ZA={[Yo]:"SHADOWMAP_TYPE_PCF",[fs]:"SHADOWMAP_TYPE_VSM"};function QA(r){return ZA[r.shadowMapType]||"SHADOWMAP_TYPE_BASIC"}const JA={[Xi]:"ENVMAP_TYPE_CUBE",[_s]:"ENVMAP_TYPE_CUBE",[so]:"ENVMAP_TYPE_CUBE_UV"};function eR(r){return r.envMap===!1?"ENVMAP_TYPE_CUBE":JA[r.envMapMode]||"ENVMAP_TYPE_CUBE"}const tR={[_s]:"ENVMAP_MODE_REFRACTION"};function nR(r){return r.envMap===!1?"ENVMAP_MODE_REFLECTION":tR[r.envMapMode]||"ENVMAP_MODE_REFLECTION"}const iR={[nc]:"ENVMAP_BLENDING_MULTIPLY",[mx]:"ENVMAP_BLENDING_MIX",[gx]:"ENVMAP_BLENDING_ADD"};function sR(r){return r.envMap===!1?"ENVMAP_BLENDING_NONE":iR[r.combine]||"ENVMAP_BLENDING_NONE"}function rR(r){const e=r.envMapCubeUVHeight;if(e===null)return null;const t=Math.log2(e)-2,n=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,t),7*16)),texelHeight:n,maxMip:t}}function oR(r,e,t,n){const i=r.getContext(),s=t.defines;let o=t.vertexShader,a=t.fragmentShader;const l=QA(t),c=eR(t),u=nR(t),h=sR(t),d=rR(t),f=HA(t),p=WA(s),g=i.createProgram();let m,_,x=t.glslVersion?"#version "+t.glslVersion+`
|
|
`:"";t.isRawShaderMaterial?(m=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,p].filter(_l).join(`
|
|
`),m.length>0&&(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<f;d++){const p=r[d];if(p.id===null)break;p.id=null,p.object=null,p.geometry=null,p.material=null,p.group=null}}return{opaque:t,transmissive:n,transparent:i,init:s,push:l,unshift:c,finish:h,sort:u}}function pR(){let r=new WeakMap;function e(n,i){const s=r.get(n);let o;return s===void 0?(o=new cg,r.set(n,[o])):i>=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;R<P;R++){const N=c[R],U=N.color,G=N.intensity,V=N.distance;let L=null;if(N.shadow&&N.shadow.map&&(N.shadow.map.texture.format===Fn?L=N.shadow.map.texture:L=N.shadow.map.depthTexture||N.shadow.map.texture),N.isAmbientLight)u+=U.r*G,h+=U.g*G,d+=U.b*G;else if(N.isLightProbe){for(let B=0;B<9;B++)n.probe[B].addScaledVector(N.sh.coefficients[B],G);A++}else if(N.isDirectionalLight){const B=e.get(N);if(B.color.copy(N.color).multiplyScalar(N.intensity),N.castShadow){const H=N.shadow,ie=t.get(N);ie.shadowIntensity=H.intensity,ie.shadowBias=H.bias,ie.shadowNormalBias=H.normalBias,ie.shadowRadius=H.radius,ie.shadowMapSize=H.mapSize,n.directionalShadow[f]=ie,n.directionalShadowMap[f]=L,n.directionalShadowMatrix[f]=N.shadow.matrix,x++}n.directional[f]=B,f++}else if(N.isSpotLight){const B=e.get(N);B.position.setFromMatrixPosition(N.matrixWorld),B.color.copy(U).multiplyScalar(G),B.distance=V,B.coneCos=Math.cos(N.angle),B.penumbraCos=Math.cos(N.angle*(1-N.penumbra)),B.decay=N.decay,n.spot[g]=B;const H=N.shadow;if(N.map&&(n.spotLightMap[E]=N.map,E++,H.updateMatrices(N),N.castShadow&&T++),n.spotLightMatrix[g]=H.matrix,N.castShadow){const ie=t.get(N);ie.shadowIntensity=H.intensity,ie.shadowBias=H.bias,ie.shadowNormalBias=H.normalBias,ie.shadowRadius=H.radius,ie.shadowMapSize=H.mapSize,n.spotShadow[g]=ie,n.spotShadowMap[g]=L,S++}g++}else if(N.isRectAreaLight){const B=e.get(N);B.color.copy(U).multiplyScalar(G),B.halfWidth.set(N.width*.5,0,0),B.halfHeight.set(0,N.height*.5,0),n.rectArea[m]=B,m++}else if(N.isPointLight){const B=e.get(N);if(B.color.copy(N.color).multiplyScalar(N.intensity),B.distance=N.distance,B.decay=N.decay,N.castShadow){const H=N.shadow,ie=t.get(N);ie.shadowIntensity=H.intensity,ie.shadowBias=H.bias,ie.shadowNormalBias=H.normalBias,ie.shadowRadius=H.radius,ie.shadowMapSize=H.mapSize,ie.shadowCameraNear=H.camera.near,ie.shadowCameraFar=H.camera.far,n.pointShadow[p]=ie,n.pointShadowMap[p]=L,n.pointShadowMatrix[p]=N.shadow.matrix,v++}n.point[p]=B,p++}else if(N.isHemisphereLight){const B=e.get(N);B.skyColor.copy(N.color).multiplyScalar(G),B.groundColor.copy(N.groundColor).multiplyScalar(G),n.hemi[_]=B,_++}}m>0&&(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;_<x;_++){const v=c[_];if(v.isDirectionalLight){const S=n.directional[h];S.direction.setFromMatrixPosition(v.matrixWorld),i.setFromMatrixPosition(v.target.matrixWorld),S.direction.sub(i),S.direction.transformDirection(m),h++}else if(v.isSpotLight){const S=n.spot[f];S.position.setFromMatrixPosition(v.matrixWorld),S.position.applyMatrix4(m),S.direction.setFromMatrixPosition(v.matrixWorld),i.setFromMatrixPosition(v.target.matrixWorld),S.direction.sub(i),S.direction.transformDirection(m),f++}else if(v.isRectAreaLight){const S=n.rectArea[p];S.position.setFromMatrixPosition(v.matrixWorld),S.position.applyMatrix4(m),o.identity(),s.copy(v.matrixWorld),s.premultiply(m),o.extractRotation(s),S.halfWidth.set(v.width*.5,0,0),S.halfHeight.set(0,v.height*.5,0),S.halfWidth.applyMatrix4(o),S.halfHeight.applyMatrix4(o),p++}else if(v.isPointLight){const S=n.point[d];S.position.setFromMatrixPosition(v.matrixWorld),S.position.applyMatrix4(m),d++}else if(v.isHemisphereLight){const S=n.hemi[g];S.direction.setFromMatrixPosition(v.matrixWorld),S.direction.transformDirection(m),g++}}}return{setup:a,setupView:l,state:n}}function ug(r){const e=new yR(r),t=[],n=[],i=[];function s(d){h.camera=d,t.length=0,n.length=0,i.length=0}function o(d){t.push(d)}function a(d){n.push(d)}function l(d){i.push(d)}function c(){e.setup(t)}function u(d){e.setupView(t,d)}const h={lightsArray:t,shadowsArray:n,lightProbeGridArray:i,camera:null,lights:e,transmissionRenderTarget:{},textureUnits:0};return{init:s,state:h,setupLights:c,setupLightsView:u,pushLight:o,pushShadow:a,pushLightProbeGrid:l}}function vR(r){let e=new WeakMap;function t(i,s=0){const o=e.get(i);let a;return o===void 0?(a=new ug(r),e.set(i,[a])):s>=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;V<L;V++){const B=T[V],H=B.shadow;if(H===void 0){ee("WebGLShadowMap:",B,"has no shadow.");continue}if(H.autoUpdate===!1&&H.needsUpdate===!1)continue;i.copy(H.mapSize);const ie=H.getFrameExtents();i.multiply(ie),s.copy(H.mapSize),(i.x>u||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;Ce<ve;Ce++){if(H.map.isWebGLCubeRenderTarget)r.setRenderTarget(H.map,Ce),r.clear();else{Ce===0&&(r.setRenderTarget(H.map),r.clear());const ke=H.getViewport(Ce);o.set(s.x*ke.x,s.y*ke.y,s.x*ke.z,s.y*ke.w),U.viewport(o)}if(B.isPointLight){const ke=H.camera,ut=H.matrix,Mt=B.distance||ke.far;Mt!==ke.far&&(ke.far=Mt,ke.updateProjectionMatrix()),il.setFromMatrixPosition(B.matrixWorld),ke.position.copy(il),Jh.copy(ke.position),Jh.add(TR[Ce]),ke.up.copy(MR[Ce]),ke.lookAt(Jh),ke.updateMatrixWorld(),ut.makeTranslation(-il.x,-il.y,-il.z),hg.multiplyMatrices(ke.projectionMatrix,ke.matrixWorldInverse),H._frustum.setFromProjectionMatrix(hg,ke.coordinateSystem,ke.reversedDepth)}else H.updateMatrices(B);n=H.getFrustum(),S(A,y,H.camera,B,this.type)}H.isPointLightShadow!==!0&&this.type===fs&&x(H,y),H.needsUpdate=!1}_=this.type,m.needsUpdate=!1,r.setRenderTarget(R,P,N)};function x(T,A){const y=e.update(g);d.defines.VSM_SAMPLES!==T.blurSamples&&(d.defines.VSM_SAMPLES=T.blurSamples,f.defines.VSM_SAMPLES=T.blurSamples,d.needsUpdate=!0,f.needsUpdate=!0),T.mapPass===null&&(T.mapPass=new $i(i.x,i.y,{format:Fn,type:en})),d.uniforms.shadow_pass.value=T.map.depthTexture,d.uniforms.resolution.value=T.mapSize,d.uniforms.radius.value=T.radius,r.setRenderTarget(T.mapPass),r.clear(),r.renderBufferDirect(A,null,y,d,g,null),f.uniforms.shadow_pass.value=T.mapPass.texture,f.uniforms.resolution.value=T.mapSize,f.uniforms.radius.value=T.radius,r.setRenderTarget(T.map),r.clear(),r.renderBufferDirect(A,null,y,f,g,null)}function v(T,A,y,R){let P=null;const N=y.isPointLight===!0?T.customDistanceMaterial:T.customDepthMaterial;if(N!==void 0)P=N;else if(P=y.isPointLight===!0?l:a,r.localClippingEnabled&&A.clipShadows===!0&&Array.isArray(A.clippingPlanes)&&A.clippingPlanes.length!==0||A.displacementMap&&A.displacementScale!==0||A.alphaMap&&A.alphaTest>0||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<H;B++){const ie=L[B],ce=V[ie.materialIndex];if(ce&&ce.visible){const ve=v(T,ce,R,P);T.onBeforeShadow(r,T,A,y,G,ve,ie),r.renderBufferDirect(y,null,G,ve,T,ie),T.onAfterShadow(r,T,A,y,G,ve,ie)}}}else if(V.visible){const L=v(T,V,R,P);T.onBeforeShadow(r,T,A,y,G,L,null),r.renderBufferDirect(y,null,G,L,T,null),T.onAfterShadow(r,T,A,y,G,L,null)}}const U=T.children;for(let G=0,V=U.length;G<V;G++)S(U[G],A,y,R,P)}function E(T){T.target.removeEventListener("dispose",E);for(const y in c){const R=c[y],P=T.target.uuid;P in R&&(R[P].dispose(),delete R[P])}}}function AR(r,e){function t(){let F=!1;const me=new tt;let te=null;const Pe=new tt(0,0,0,0);return{setMask:function(xe){te!==xe&&!F&&(r.colorMask(xe,xe,xe,xe),te=xe)},setLocked:function(xe){F=xe},setClear:function(xe,ue,ze,it,ln){ln===!0&&(xe*=it,ue*=it,ze*=it),me.set(xe,ue,ze,it),Pe.equals(me)===!1&&(r.clearColor(xe,ue,ze,it),Pe.copy(me))},reset:function(){F=!1,te=null,Pe.set(-1,0,0,0)}}}function n(){let F=!1,me=!1,te=null,Pe=null,xe=null;return{setReversed:function(ue){if(me!==ue){const ze=e.get("EXT_clip_control");ue?ze.clipControlEXT(ze.LOWER_LEFT_EXT,ze.ZERO_TO_ONE_EXT):ze.clipControlEXT(ze.LOWER_LEFT_EXT,ze.NEGATIVE_ONE_TO_ONE_EXT),me=ue;const it=xe;xe=null,this.setClear(it)}},getReversed:function(){return me},setTest:function(ue){ue?le(r.DEPTH_TEST):Ne(r.DEPTH_TEST)},setMask:function(ue){te!==ue&&!F&&(r.depthMask(ue),te=ue)},setFunc:function(ue){if(me&&(ue=tp[ue]),Pe!==ue){switch(ue){case Il:r.depthFunc(r.NEVER);break;case Bl:r.depthFunc(r.ALWAYS);break;case Ol:r.depthFunc(r.LESS);break;case Ar:r.depthFunc(r.LEQUAL);break;case kl:r.depthFunc(r.EQUAL);break;case Gl:r.depthFunc(r.GEQUAL);break;case Vl:r.depthFunc(r.GREATER);break;case zl:r.depthFunc(r.NOTEQUAL);break;default:r.depthFunc(r.LEQUAL)}Pe=ue}},setLocked:function(ue){F=ue},setClear:function(ue){xe!==ue&&(xe=ue,me&&(ue=1-ue),r.clearDepth(ue))},reset:function(){F=!1,te=null,Pe=null,xe=null,me=!1}}}function i(){let F=!1,me=null,te=null,Pe=null,xe=null,ue=null,ze=null,it=null,ln=null;return{setTest:function(Bt){F||(Bt?le(r.STENCIL_TEST):Ne(r.STENCIL_TEST))},setMask:function(Bt){me!==Bt&&!F&&(r.stencilMask(Bt),me=Bt)},setFunc:function(Bt,Es,qi){(te!==Bt||Pe!==Es||xe!==qi)&&(r.stencilFunc(Bt,Es,qi),te=Bt,Pe=Es,xe=qi)},setOp:function(Bt,Es,qi){(ue!==Bt||ze!==Es||it!==qi)&&(r.stencilOp(Bt,Es,qi),ue=Bt,ze=Es,it=qi)},setLocked:function(Bt){F=Bt},setClear:function(Bt){ln!==Bt&&(r.clearStencil(Bt),ln=Bt)},reset:function(){F=!1,me=null,te=null,Pe=null,xe=null,ue=null,ze=null,it=null,ln=null}}}const s=new t,o=new n,a=new i,l=new WeakMap,c=new WeakMap;let u={},h={},d={},f=new WeakMap,p=[],g=null,m=!1,_=null,x=null,v=null,S=null,E=null,T=null,A=null,y=new Ve(0,0,0),R=0,P=!1,N=null,U=null,G=null,V=null,L=null;const B=r.getParameter(r.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let H=!1,ie=0;const ce=r.getParameter(r.VERSION);ce.indexOf("WebGL")!==-1?(ie=parseFloat(/^WebGL (\d)/.exec(ce)[1]),H=ie>=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<te;ze++)F===r.TEXTURE_3D||F===r.TEXTURE_2D_ARRAY?r.texImage3D(me,0,r.RGBA,1,1,Pe,0,r.RGBA,r.UNSIGNED_BYTE,xe):r.texImage2D(me+ze,0,r.RGBA,1,1,0,r.RGBA,r.UNSIGNED_BYTE,xe);return ue}const se={};se[r.TEXTURE_2D]=W(r.TEXTURE_2D,r.TEXTURE_2D,1),se[r.TEXTURE_CUBE_MAP]=W(r.TEXTURE_CUBE_MAP,r.TEXTURE_CUBE_MAP_POSITIVE_X,6),se[r.TEXTURE_2D_ARRAY]=W(r.TEXTURE_2D_ARRAY,r.TEXTURE_2D_ARRAY,1,1),se[r.TEXTURE_3D]=W(r.TEXTURE_3D,r.TEXTURE_3D,1,1),s.setClear(0,0,0,1),o.setClear(1),a.setClear(0),le(r.DEPTH_TEST),o.setFunc(Ar),It(!1),Dt(Qd),le(r.CULL_FACE),Et(Cn);function le(F){u[F]!==!0&&(r.enable(F),u[F]=!0)}function Ne(F){u[F]!==!1&&(r.disable(F),u[F]=!1)}function Le(F,me){return d[F]!==me?(r.bindFramebuffer(F,me),d[F]=me,F===r.DRAW_FRAMEBUFFER&&(d[r.FRAMEBUFFER]=me),F===r.FRAMEBUFFER&&(d[r.DRAW_FRAMEBUFFER]=me),!0):!1}function we(F,me){let te=p,Pe=!1;if(F){te=f.get(me),te===void 0&&(te=[],f.set(me,te));const xe=F.textures;if(te.length!==xe.length||te[0]!==r.COLOR_ATTACHMENT0){for(let ue=0,ze=xe.length;ue<ze;ue++)te[ue]=r.COLOR_ATTACHMENT0+ue;te.length=xe.length,Pe=!0}}else te[0]!==r.BACK&&(te[0]=r.BACK,Pe=!0);Pe&&r.drawBuffers(te)}function xt(F){return g!==F?(r.useProgram(F),g=F,!0):!1}const Qe={[Wn]:r.FUNC_ADD,[Lf]:r.FUNC_SUBTRACT,[Uf]:r.FUNC_REVERSE_SUBTRACT};Qe[fx]=r.MIN,Qe[px]=r.MAX;const ft={[Us]:r.ZERO,[Ff]:r.ONE,[If]:r.SRC_COLOR,[Ul]:r.SRC_ALPHA,[zf]:r.SRC_ALPHA_SATURATE,[Gf]:r.DST_COLOR,[Of]:r.DST_ALPHA,[Bf]:r.ONE_MINUS_SRC_COLOR,[Fl]:r.ONE_MINUS_SRC_ALPHA,[Vf]:r.ONE_MINUS_DST_COLOR,[kf]:r.ONE_MINUS_DST_ALPHA,[Xv]:r.CONSTANT_COLOR,[qv]:r.ONE_MINUS_CONSTANT_COLOR,[jv]:r.CONSTANT_ALPHA,[Yv]:r.ONE_MINUS_CONSTANT_ALPHA};function Et(F,me,te,Pe,xe,ue,ze,it,ln,Bt){if(F===Cn){m===!0&&(Ne(r.BLEND),m=!1);return}if(m===!1&&(le(r.BLEND),m=!0),F!==Jr){if(F!==_||Bt!==P){if((x!==Wn||E!==Wn)&&(r.blendEquation(r.FUNC_ADD),x=Wn,E=Wn),Bt)switch(F){case Jn:r.blendFuncSeparate(r.ONE,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA);break;case hr:r.blendFunc(r.ONE,r.ONE);break;case dr:r.blendFuncSeparate(r.ZERO,r.ONE_MINUS_SRC_COLOR,r.ZERO,r.ONE);break;case fr:r.blendFuncSeparate(r.DST_COLOR,r.ONE_MINUS_SRC_ALPHA,r.ZERO,r.ONE);break;default:ne("WebGLState: Invalid blending: ",F);break}else switch(F){case Jn:r.blendFuncSeparate(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA);break;case hr:r.blendFuncSeparate(r.SRC_ALPHA,r.ONE,r.ONE,r.ONE);break;case dr:ne("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case fr:ne("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:ne("WebGLState: Invalid blending: ",F);break}v=null,S=null,T=null,A=null,y.set(0,0,0),R=0,_=F,P=Bt}return}xe=xe||me,ue=ue||te,ze=ze||Pe,(me!==x||xe!==E)&&(r.blendEquationSeparate(Qe[me],Qe[xe]),x=me,E=xe),(te!==v||Pe!==S||ue!==T||ze!==A)&&(r.blendFuncSeparate(ft[te],ft[Pe],ft[ue],ft[ze]),v=te,S=Pe,T=ue,A=ze),(it.equals(y)===!1||ln!==R)&&(r.blendColor(it.r,it.g,it.b,ln),y.copy(it),R=ln),_=F,P=!1}function Je(F,me){F.side===wn?Ne(r.CULL_FACE):le(r.CULL_FACE);let te=F.side===Pt;me&&(te=!te),It(te),F.blending===Jn&&F.transparent===!1?Et(Cn):Et(F.blending,F.blendEquation,F.blendSrc,F.blendDst,F.blendEquationAlpha,F.blendSrcAlpha,F.blendDstAlpha,F.blendColor,F.blendAlpha,F.premultipliedAlpha),o.setFunc(F.depthFunc),o.setTest(F.depthTest),o.setMask(F.depthWrite),s.setMask(F.colorWrite);const Pe=F.stencilWrite;a.setTest(Pe),Pe&&(a.setMask(F.stencilWriteMask),a.setFunc(F.stencilFunc,F.stencilRef,F.stencilFuncMask),a.setOp(F.stencilFail,F.stencilZFail,F.stencilZPass)),O(F.polygonOffset,F.polygonOffsetFactor,F.polygonOffsetUnits),F.alphaToCoverage===!0?le(r.SAMPLE_ALPHA_TO_COVERAGE):Ne(r.SAMPLE_ALPHA_TO_COVERAGE)}function It(F){N!==F&&(F?r.frontFace(r.CW):r.frontFace(r.CCW),N=F)}function Dt(F){F!==cx?(le(r.CULL_FACE),F!==U&&(F===Qd?r.cullFace(r.BACK):F===ux?r.cullFace(r.FRONT):r.cullFace(r.FRONT_AND_BACK))):Ne(r.CULL_FACE),U=F}function di(F){F!==G&&(H&&r.lineWidth(F),G=F)}function O(F,me,te){F?(le(r.POLYGON_OFFSET_FILL),(V!==me||L!==te)&&(V=me,L=te,o.getReversed()&&(me=-me),r.polygonOffset(me,te))):Ne(r.POLYGON_OFFSET_FILL)}function yn(F){F?le(r.SCISSOR_TEST):Ne(r.SCISSOR_TEST)}function mt(F){F===void 0&&(F=r.TEXTURE0+B-1),ve!==F&&(r.activeTexture(F),ve=F)}function Xt(F,me,te){te===void 0&&(ve===null?te=r.TEXTURE0+B-1:te=ve);let Pe=Ce[te];Pe===void 0&&(Pe={type:void 0,texture:void 0},Ce[te]=Pe),(Pe.type!==F||Pe.texture!==me)&&(ve!==te&&(r.activeTexture(te),ve=te),r.bindTexture(F,me||se[F]),Pe.type=F,Pe.texture=me)}function be(){const F=Ce[ve];F!==void 0&&F.type!==void 0&&(r.bindTexture(F.type,null),F.type=void 0,F.texture=void 0)}function rn(){try{r.compressedTexImage2D(...arguments)}catch(F){ne("WebGLState:",F)}}function w(){try{r.compressedTexImage3D(...arguments)}catch(F){ne("WebGLState:",F)}}function b(){try{r.texSubImage2D(...arguments)}catch(F){ne("WebGLState:",F)}}function z(){try{r.texSubImage3D(...arguments)}catch(F){ne("WebGLState:",F)}}function re(){try{r.compressedTexSubImage2D(...arguments)}catch(F){ne("WebGLState:",F)}}function he(){try{r.compressedTexSubImage3D(...arguments)}catch(F){ne("WebGLState:",F)}}function fe(){try{r.texStorage2D(...arguments)}catch(F){ne("WebGLState:",F)}}function ye(){try{r.texStorage3D(...arguments)}catch(F){ne("WebGLState:",F)}}function J(){try{r.texImage2D(...arguments)}catch(F){ne("WebGLState:",F)}}function ae(){try{r.texImage3D(...arguments)}catch(F){ne("WebGLState:",F)}}function Re(F){return h[F]!==void 0?h[F]:r.getParameter(F)}function Ue(F,me){h[F]!==me&&(r.pixelStorei(F,me),h[F]=me)}function _e(F){Mt.equals(F)===!1&&(r.scissor(F.x,F.y,F.z,F.w),Mt.copy(F))}function pe(F){oe.equals(F)===!1&&(r.viewport(F.x,F.y,F.z,F.w),oe.copy(F))}function et(F,me){let te=c.get(me);te===void 0&&(te=new WeakMap,c.set(me,te));let Pe=te.get(F);Pe===void 0&&(Pe=r.getUniformBlockIndex(me,F.name),te.set(F,Pe))}function at(F,me){const Pe=c.get(me).get(F);l.get(me)!==Pe&&(r.uniformBlockBinding(me,Pe,F.__bindingPointIndex),l.set(me,Pe))}function St(){r.disable(r.BLEND),r.disable(r.CULL_FACE),r.disable(r.DEPTH_TEST),r.disable(r.POLYGON_OFFSET_FILL),r.disable(r.SCISSOR_TEST),r.disable(r.STENCIL_TEST),r.disable(r.SAMPLE_ALPHA_TO_COVERAGE),r.blendEquation(r.FUNC_ADD),r.blendFunc(r.ONE,r.ZERO),r.blendFuncSeparate(r.ONE,r.ZERO,r.ONE,r.ZERO),r.blendColor(0,0,0,0),r.colorMask(!0,!0,!0,!0),r.clearColor(0,0,0,0),r.depthMask(!0),r.depthFunc(r.LESS),o.setReversed(!1),r.clearDepth(1),r.stencilMask(4294967295),r.stencilFunc(r.ALWAYS,0,4294967295),r.stencilOp(r.KEEP,r.KEEP,r.KEEP),r.clearStencil(0),r.cullFace(r.BACK),r.frontFace(r.CCW),r.polygonOffset(0,0),r.activeTexture(r.TEXTURE0),r.bindFramebuffer(r.FRAMEBUFFER,null),r.bindFramebuffer(r.DRAW_FRAMEBUFFER,null),r.bindFramebuffer(r.READ_FRAMEBUFFER,null),r.useProgram(null),r.lineWidth(1),r.scissor(0,0,r.canvas.width,r.canvas.height),r.viewport(0,0,r.canvas.width,r.canvas.height),r.pixelStorei(r.PACK_ALIGNMENT,4),r.pixelStorei(r.UNPACK_ALIGNMENT,4),r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,!1),r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),r.pixelStorei(r.UNPACK_COLORSPACE_CONVERSION_WEBGL,r.BROWSER_DEFAULT_WEBGL),r.pixelStorei(r.PACK_ROW_LENGTH,0),r.pixelStorei(r.PACK_SKIP_PIXELS,0),r.pixelStorei(r.PACK_SKIP_ROWS,0),r.pixelStorei(r.UNPACK_ROW_LENGTH,0),r.pixelStorei(r.UNPACK_IMAGE_HEIGHT,0),r.pixelStorei(r.UNPACK_SKIP_PIXELS,0),r.pixelStorei(r.UNPACK_SKIP_ROWS,0),r.pixelStorei(r.UNPACK_SKIP_IMAGES,0),u={},h={},ve=null,Ce={},d={},f=new WeakMap,p=[],g=null,m=!1,_=null,x=null,v=null,S=null,E=null,T=null,A=null,y=new Ve(0,0,0),R=0,P=!1,N=null,U=null,G=null,V=null,L=null,Mt.set(0,0,r.canvas.width,r.canvas.height),oe.set(0,0,r.canvas.width,r.canvas.height),s.reset(),o.reset(),a.reset()}return{buffers:{color:s,depth:o,stencil:a},enable:le,disable:Ne,bindFramebuffer:Le,drawBuffers:we,useProgram:xt,setBlending:Et,setMaterial:Je,setFlipSided:It,setCullFace:Dt,setLineWidth:di,setPolygonOffset:O,setScissorTest:yn,activeTexture:mt,bindTexture:Xt,unbindTexture:be,compressedTexImage2D:rn,compressedTexImage3D:w,texImage2D:J,texImage3D:ae,pixelStorei:Ue,getParameter:Re,updateUBOMapping:et,uniformBlockBinding:at,texStorage2D:fe,texStorage3D:ye,texSubImage2D:b,texSubImage3D:z,compressedTexSubImage2D:re,compressedTexSubImage3D:he,scissor:_e,viewport:pe,reset:St}}function RR(r,e,t,n,i,s,o){const a=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):null,l=typeof navigator>"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<b.__webglFramebuffer[re].length;he++)r.deleteFramebuffer(b.__webglFramebuffer[re][he]);else r.deleteFramebuffer(b.__webglFramebuffer[re]);b.__webglDepthbuffer&&r.deleteRenderbuffer(b.__webglDepthbuffer[re])}else{if(Array.isArray(b.__webglFramebuffer))for(let re=0;re<b.__webglFramebuffer.length;re++)r.deleteFramebuffer(b.__webglFramebuffer[re]);else r.deleteFramebuffer(b.__webglFramebuffer);if(b.__webglDepthbuffer&&r.deleteRenderbuffer(b.__webglDepthbuffer),b.__webglMultisampledFramebuffer&&r.deleteFramebuffer(b.__webglMultisampledFramebuffer),b.__webglColorRenderbuffer)for(let re=0;re<b.__webglColorRenderbuffer.length;re++)b.__webglColorRenderbuffer[re]&&r.deleteRenderbuffer(b.__webglColorRenderbuffer[re]);b.__webglDepthRenderbuffer&&r.deleteRenderbuffer(b.__webglDepthRenderbuffer)}const z=w.textures;for(let re=0,he=z.length;re<he;re++){const fe=n.get(z[re]);fe.__webglTexture&&(r.deleteTexture(fe.__webglTexture),o.memory.textures--),n.remove(z[re])}n.remove(w)}let U=0;function G(){U=0}function V(){return U}function L(w){U=w}function B(){const w=U;return w>=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;Ue<fe.length;Ue++){const _e=fe[ye],pe=fe[Ue],et=_e.start+_e.count,at=se(pe.start,b.width,4),St=se(_e.start,b.width,4);pe.start<=et+1&&at===St&&se(pe.start+pe.count-1,b.width,4)===at?_e.count=Math.max(_e.count,pe.start+pe.count-_e.start):(++ye,fe[ye]=pe)}fe.length=ye+1;const J=t.getParameter(r.UNPACK_ROW_LENGTH),ae=t.getParameter(r.UNPACK_SKIP_PIXELS),Re=t.getParameter(r.UNPACK_SKIP_ROWS);t.pixelStorei(r.UNPACK_ROW_LENGTH,b.width);for(let Ue=0,_e=fe.length;Ue<_e;Ue++){const pe=fe[Ue],et=Math.floor(pe.start/4),at=Math.ceil(pe.count/4),St=et%b.width,F=Math.floor(et/b.width),me=at,te=1;t.pixelStorei(r.UNPACK_SKIP_PIXELS,St),t.pixelStorei(r.UNPACK_SKIP_ROWS,F),t.texSubImage2D(r.TEXTURE_2D,0,St,F,me,te,z,re,b.data)}w.clearUpdateRanges(),t.pixelStorei(r.UNPACK_ROW_LENGTH,J),t.pixelStorei(r.UNPACK_SKIP_PIXELS,ae),t.pixelStorei(r.UNPACK_SKIP_ROWS,Re)}}function Ne(w,b,z){let re=r.TEXTURE_2D;(b.isDataArrayTexture||b.isCompressedArrayTexture)&&(re=r.TEXTURE_2D_ARRAY),b.isData3DTexture&&(re=r.TEXTURE_3D);const he=W(w,b),fe=b.source;t.bindTexture(re,w.__webglTexture,r.TEXTURE0+z);const ye=n.get(fe);if(fe.version!==ye.__version||he===!0){if(t.activeTexture(r.TEXTURE0+z),(typeof ImageBitmap<"u"&&b.image instanceof ImageBitmap)===!1){const te=Xe.getPrimaries(Xe.workingColorSpace),Pe=b.colorSpace===ri?null:Xe.getPrimaries(b.colorSpace),xe=b.colorSpace===ri||te===Pe?r.NONE:r.BROWSER_DEFAULT_WEBGL;t.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,b.flipY),t.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,b.premultiplyAlpha),t.pixelStorei(r.UNPACK_COLORSPACE_CONVERSION_WEBGL,xe)}t.pixelStorei(r.UNPACK_ALIGNMENT,b.unpackAlignment);let ae=m(b.image,!1,i.maxTextureSize);ae=be(b,ae);const Re=s.convert(b.format,b.colorSpace),Ue=s.convert(b.type);let _e=S(b.internalFormat,Re,Ue,b.normalized,b.colorSpace,b.isVideoTexture);oe(re,b);let pe;const et=b.mipmaps,at=b.isVideoTexture!==!0,St=ye.__version===void 0||he===!0,F=fe.dataReady,me=T(b,ae);if(b.isDepthTexture)_e=E(b.format===$n,b.type),St&&(at?t.texStorage2D(r.TEXTURE_2D,1,_e,ae.width,ae.height):t.texImage2D(r.TEXTURE_2D,0,_e,ae.width,ae.height,0,Re,Ue,null));else if(b.isDataTexture)if(et.length>0){at&&St&&t.texStorage2D(r.TEXTURE_2D,me,_e,et[0].width,et[0].height);for(let te=0,Pe=et.length;te<Pe;te++)pe=et[te],at?F&&t.texSubImage2D(r.TEXTURE_2D,te,0,0,pe.width,pe.height,Re,Ue,pe.data):t.texImage2D(r.TEXTURE_2D,te,_e,pe.width,pe.height,0,Re,Ue,pe.data);b.generateMipmaps=!1}else at?(St&&t.texStorage2D(r.TEXTURE_2D,me,_e,ae.width,ae.height),F&&le(b,ae,Re,Ue)):t.texImage2D(r.TEXTURE_2D,0,_e,ae.width,ae.height,0,Re,Ue,ae.data);else if(b.isCompressedTexture)if(b.isCompressedArrayTexture){at&&St&&t.texStorage3D(r.TEXTURE_2D_ARRAY,me,_e,et[0].width,et[0].height,ae.depth);for(let te=0,Pe=et.length;te<Pe;te++)if(pe=et[te],b.format!==an)if(Re!==null)if(at){if(F)if(b.layerUpdates.size>0){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;te<Pe;te++)pe=et[te],b.format!==an?Re!==null?at?F&&t.compressedTexSubImage2D(r.TEXTURE_2D,te,0,0,pe.width,pe.height,Re,pe.data):t.compressedTexImage2D(r.TEXTURE_2D,te,_e,pe.width,pe.height,0,pe.data):ee("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):at?F&&t.texSubImage2D(r.TEXTURE_2D,te,0,0,pe.width,pe.height,Re,Ue,pe.data):t.texImage2D(r.TEXTURE_2D,te,_e,pe.width,pe.height,0,Re,Ue,pe.data)}else if(b.isDataArrayTexture)if(at){if(St&&t.texStorage3D(r.TEXTURE_2D_ARRAY,me,_e,ae.width,ae.height,ae.depth),F)if(b.layerUpdates.size>0){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<me;xe++)t.texImage2D(r.TEXTURE_2D,xe,_e,te,Pe,0,Re,Ue,null),te>>=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;te<Pe;te++)pe=et[te],at?F&&t.texSubImage2D(r.TEXTURE_2D,te,0,0,Re,Ue,pe):t.texImage2D(r.TEXTURE_2D,te,_e,Re,Ue,pe);b.generateMipmaps=!1}else if(at){if(St){const te=rn(ae);t.texStorage2D(r.TEXTURE_2D,me,_e,te.width,te.height)}F&&t.texSubImage2D(r.TEXTURE_2D,0,0,0,Re,Ue,ae)}else t.texImage2D(r.TEXTURE_2D,0,_e,Re,Ue,ae);_(b)&&x(re),ye.__version=fe.version,b.onUpdate&&b.onUpdate(b)}w.__version=b.version}function Le(w,b,z){if(b.image.length!==6)return;const re=W(w,b),he=b.source;t.bindTexture(r.TEXTURE_CUBE_MAP,w.__webglTexture,r.TEXTURE0+z);const fe=n.get(he);if(he.version!==fe.__version||re===!0){t.activeTexture(r.TEXTURE0+z);const ye=Xe.getPrimaries(Xe.workingColorSpace),J=b.colorSpace===ri?null:Xe.getPrimaries(b.colorSpace),ae=b.colorSpace===ri||ye===J?r.NONE:r.BROWSER_DEFAULT_WEBGL;t.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,b.flipY),t.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,b.premultiplyAlpha),t.pixelStorei(r.UNPACK_ALIGNMENT,b.unpackAlignment),t.pixelStorei(r.UNPACK_COLORSPACE_CONVERSION_WEBGL,ae);const Re=b.isCompressedTexture||b.image[0].isCompressedTexture,Ue=b.image[0]&&b.image[0].isDataTexture,_e=[];for(let ue=0;ue<6;ue++)!Re&&!Ue?_e[ue]=m(b.image[ue],!0,i.maxCubemapSize):_e[ue]=Ue?b.image[ue].image:b.image[ue],_e[ue]=be(b,_e[ue]);const pe=_e[0],et=s.convert(b.format,b.colorSpace),at=s.convert(b.type),St=S(b.internalFormat,et,at,b.normalized,b.colorSpace),F=b.isVideoTexture!==!0,me=fe.__version===void 0||re===!0,te=he.dataReady;let Pe=T(b,pe);oe(r.TEXTURE_CUBE_MAP,b);let xe;if(Re){F&&me&&t.texStorage2D(r.TEXTURE_CUBE_MAP,Pe,St,pe.width,pe.height);for(let ue=0;ue<6;ue++){xe=_e[ue].mipmaps;for(let ze=0;ze<xe.length;ze++){const it=xe[ze];b.format!==an?et!==null?F?te&&t.compressedTexSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+ue,ze,0,0,it.width,it.height,et,it.data):t.compressedTexImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+ue,ze,St,it.width,it.height,0,it.data):ee("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):F?te&&t.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+ue,ze,0,0,it.width,it.height,et,at,it.data):t.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+ue,ze,St,it.width,it.height,0,et,at,it.data)}}}else{if(xe=b.mipmaps,F&&me){xe.length>0&&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<xe.length;ze++){const ln=xe[ze].image[ue].image;F?te&&t.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+ue,ze+1,0,0,ln.width,ln.height,et,at,ln.data):t.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+ue,ze+1,St,ln.width,ln.height,0,et,at,ln.data)}}else{F?te&&t.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+ue,0,0,0,et,at,_e[ue]):t.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+ue,0,St,et,at,_e[ue]);for(let ze=0;ze<xe.length;ze++){const it=xe[ze];F?te&&t.texSubImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+ue,ze+1,0,0,et,at,it.image[ue]):t.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+ue,ze+1,St,et,at,it.image[ue])}}}_(b)&&x(r.TEXTURE_CUBE_MAP),fe.__version=he.version,b.onUpdate&&b.onUpdate(b)}w.__version=b.version}function we(w,b,z,re,he,fe){const ye=s.convert(z.format,z.colorSpace),J=s.convert(z.type),ae=S(z.internalFormat,ye,J,z.normalized,z.colorSpace),Re=n.get(b),Ue=n.get(z);if(Ue.__renderTarget=b,!Re.__hasExternalTextures){const _e=Math.max(1,b.width>>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<re.length;he++){const fe=re[he],ye=s.convert(fe.format,fe.colorSpace),J=s.convert(fe.type),ae=S(fe.internalFormat,ye,J,fe.normalized,fe.colorSpace);mt(b)?a.renderbufferStorageMultisampleEXT(r.RENDERBUFFER,yn(b),ae,b.width,b.height):z?r.renderbufferStorageMultisample(r.RENDERBUFFER,yn(b),ae,b.width,b.height):r.renderbufferStorage(r.RENDERBUFFER,ae,b.width,b.height)}}r.bindRenderbuffer(r.RENDERBUFFER,null)}function Qe(w,b,z){const re=b.isWebGLCubeRenderTarget===!0;if(t.bindFramebuffer(r.FRAMEBUFFER,w),!(b.depthTexture&&b.depthTexture.isDepthTexture))throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");const he=n.get(b.depthTexture);if(he.__renderTarget=b,(!he.__webglTexture||b.depthTexture.image.width!==b.width||b.depthTexture.image.height!==b.height)&&(b.depthTexture.image.width=b.width,b.depthTexture.image.height=b.height,b.depthTexture.needsUpdate=!0),re){if(he.__webglInit===void 0&&(he.__webglInit=!0,b.depthTexture.addEventListener("dispose",A)),he.__webglTexture===void 0){he.__webglTexture=r.createTexture(),t.bindTexture(r.TEXTURE_CUBE_MAP,he.__webglTexture),oe(r.TEXTURE_CUBE_MAP,b.depthTexture);const Re=s.convert(b.depthTexture.format),Ue=s.convert(b.depthTexture.type);let _e;b.depthTexture.format===Nn?_e=r.DEPTH_COMPONENT24:b.depthTexture.format===$n&&(_e=r.DEPTH24_STENCIL8);for(let pe=0;pe<6;pe++)r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+pe,0,_e,b.width,b.height,0,Re,Ue,null)}}else ie(b.depthTexture,0);const fe=he.__webglTexture,ye=yn(b),J=re?r.TEXTURE_CUBE_MAP_POSITIVE_X+z:r.TEXTURE_2D,ae=b.depthTexture.format===$n?r.DEPTH_STENCIL_ATTACHMENT:r.DEPTH_ATTACHMENT;if(b.depthTexture.format===Nn)mt(b)?a.framebufferTexture2DMultisampleEXT(r.FRAMEBUFFER,ae,J,fe,0,ye):r.framebufferTexture2D(r.FRAMEBUFFER,ae,J,fe,0);else if(b.depthTexture.format===$n)mt(b)?a.framebufferTexture2DMultisampleEXT(r.FRAMEBUFFER,ae,J,fe,0,ye):r.framebufferTexture2D(r.FRAMEBUFFER,ae,J,fe,0);else throw new Error("Unknown depthTexture format")}function ft(w){const b=n.get(w),z=w.isWebGLCubeRenderTarget===!0;if(b.__boundDepthTexture!==w.depthTexture){const re=w.depthTexture;if(b.__depthDisposeCallback&&b.__depthDisposeCallback(),re){const 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;ae<b.mipmaps.length;ae++)z.__webglFramebuffer[J][ae]=r.createFramebuffer()}else z.__webglFramebuffer[J]=r.createFramebuffer()}else{if(b.mipmaps&&b.mipmaps.length>0){z.__webglFramebuffer=[];for(let J=0;J<b.mipmaps.length;J++)z.__webglFramebuffer[J]=r.createFramebuffer()}else z.__webglFramebuffer=r.createFramebuffer();if(ye)for(let J=0,ae=he.length;J<ae;J++){const Re=n.get(he[J]);Re.__webglTexture===void 0&&(Re.__webglTexture=r.createTexture(),o.memory.textures++)}if(w.samples>0&&mt(w)===!1){z.__webglMultisampledFramebuffer=r.createFramebuffer(),z.__webglColorRenderbuffer=[],t.bindFramebuffer(r.FRAMEBUFFER,z.__webglMultisampledFramebuffer);for(let J=0;J<he.length;J++){const ae=he[J];z.__webglColorRenderbuffer[J]=r.createRenderbuffer(),r.bindRenderbuffer(r.RENDERBUFFER,z.__webglColorRenderbuffer[J]);const Re=s.convert(ae.format,ae.colorSpace),Ue=s.convert(ae.type),_e=S(ae.internalFormat,Re,Ue,ae.normalized,ae.colorSpace,w.isXRRenderTarget===!0),pe=yn(w);r.renderbufferStorageMultisample(r.RENDERBUFFER,pe,_e,w.width,w.height),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0+J,r.RENDERBUFFER,z.__webglColorRenderbuffer[J])}r.bindRenderbuffer(r.RENDERBUFFER,null),w.depthBuffer&&(z.__webglDepthRenderbuffer=r.createRenderbuffer(),xt(z.__webglDepthRenderbuffer,w,!0)),t.bindFramebuffer(r.FRAMEBUFFER,null)}}if(fe){t.bindTexture(r.TEXTURE_CUBE_MAP,re.__webglTexture),oe(r.TEXTURE_CUBE_MAP,b);for(let J=0;J<6;J++)if(b.mipmaps&&b.mipmaps.length>0)for(let ae=0;ae<b.mipmaps.length;ae++)we(z.__webglFramebuffer[J][ae],w,b,r.COLOR_ATTACHMENT0,r.TEXTURE_CUBE_MAP_POSITIVE_X+J,ae);else we(z.__webglFramebuffer[J],w,b,r.COLOR_ATTACHMENT0,r.TEXTURE_CUBE_MAP_POSITIVE_X+J,0);_(b)&&x(r.TEXTURE_CUBE_MAP),t.unbindTexture()}else if(ye){for(let J=0,ae=he.length;J<ae;J++){const Re=he[J],Ue=n.get(Re);let _e=r.TEXTURE_2D;(w.isWebGL3DRenderTarget||w.isWebGLArrayRenderTarget)&&(_e=w.isWebGL3DRenderTarget?r.TEXTURE_3D:r.TEXTURE_2D_ARRAY),t.bindTexture(_e,Ue.__webglTexture),oe(_e,Re),we(z.__webglFramebuffer,w,Re,r.COLOR_ATTACHMENT0+J,_e,0),_(Re)&&x(_e)}t.unbindTexture()}else{let J=r.TEXTURE_2D;if((w.isWebGL3DRenderTarget||w.isWebGLArrayRenderTarget)&&(J=w.isWebGL3DRenderTarget?r.TEXTURE_3D:r.TEXTURE_2D_ARRAY),t.bindTexture(J,re.__webglTexture),oe(J,b),b.mipmaps&&b.mipmaps.length>0)for(let ae=0;ae<b.mipmaps.length;ae++)we(z.__webglFramebuffer[ae],w,b,r.COLOR_ATTACHMENT0,J,ae);else we(z.__webglFramebuffer,w,b,r.COLOR_ATTACHMENT0,J,0);_(b)&&x(J),t.unbindTexture()}w.depthBuffer&&ft(w)}function It(w){const b=w.textures;for(let z=0,re=b.length;z<re;z++){const he=b[z];if(_(he)){const fe=v(w),ye=n.get(he).__webglTexture;t.bindTexture(fe,ye),x(fe),t.unbindTexture()}}}const Dt=[],di=[];function O(w){if(w.samples>0){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;Re<b.length;Re++)t.bindFramebuffer(r.FRAMEBUFFER,ye.__webglMultisampledFramebuffer),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0+Re,r.RENDERBUFFER,null),t.bindFramebuffer(r.FRAMEBUFFER,ye.__webglFramebuffer),r.framebufferTexture2D(r.DRAW_FRAMEBUFFER,r.COLOR_ATTACHMENT0+Re,r.TEXTURE_2D,null,0);t.bindFramebuffer(r.READ_FRAMEBUFFER,ye.__webglMultisampledFramebuffer);const ae=w.texture.mipmaps;ae&&ae.length>0?t.bindFramebuffer(r.DRAW_FRAMEBUFFER,ye.__webglFramebuffer[0]):t.bindFramebuffer(r.DRAW_FRAMEBUFFER,ye.__webglFramebuffer);for(let Re=0;Re<b.length;Re++){if(w.resolveDepthBuffer&&(w.depthBuffer&&(he|=r.DEPTH_BUFFER_BIT),w.stencilBuffer&&w.resolveStencilBuffer&&(he|=r.STENCIL_BUFFER_BIT)),J){r.framebufferRenderbuffer(r.READ_FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.RENDERBUFFER,ye.__webglColorRenderbuffer[Re]);const Ue=n.get(b[Re]).__webglTexture;r.framebufferTexture2D(r.DRAW_FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,Ue,0)}r.blitFramebuffer(0,0,z,re,0,0,z,re,he,r.NEAREST),l===!0&&(Dt.length=0,di.length=0,Dt.push(r.COLOR_ATTACHMENT0+Re),w.depthBuffer&&w.resolveDepthBuffer===!1&&(Dt.push(fe),di.push(fe),r.invalidateFramebuffer(r.DRAW_FRAMEBUFFER,di)),r.invalidateFramebuffer(r.READ_FRAMEBUFFER,Dt))}if(t.bindFramebuffer(r.READ_FRAMEBUFFER,null),t.bindFramebuffer(r.DRAW_FRAMEBUFFER,null),J)for(let Re=0;Re<b.length;Re++){t.bindFramebuffer(r.FRAMEBUFFER,ye.__webglMultisampledFramebuffer),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0+Re,r.RENDERBUFFER,ye.__webglColorRenderbuffer[Re]);const Ue=n.get(b[Re]).__webglTexture;t.bindFramebuffer(r.FRAMEBUFFER,ye.__webglFramebuffer),r.framebufferTexture2D(r.DRAW_FRAMEBUFFER,r.COLOR_ATTACHMENT0+Re,r.TEXTURE_2D,Ue,0)}t.bindFramebuffer(r.DRAW_FRAMEBUFFER,ye.__webglMultisampledFramebuffer)}else if(w.depthBuffer&&w.resolveDepthBuffer===!1&&l){const b=w.stencilBuffer?r.DEPTH_STENCIL_ATTACHMENT:r.DEPTH_ATTACHMENT;r.invalidateFramebuffer(r.DRAW_FRAMEBUFFER,[b])}}}function yn(w){return Math.min(i.maxSamples,w.samples)}function mt(w){const b=n.get(w);return w.samples>0&&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<E.length;W++){const se=T[W];se!==null&&(T[W]=null,E[W].disconnect(se))}G=null,V=null,m.reset();for(const W in _)delete _[W];e.setRenderTarget(v),f=null,d=null,h=null,i=null,S=null,oe.stop(),n.isPresenting=!1,e.setPixelRatio(y),e.setSize(A.width,A.height,!1),n.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(W){s=W,n.isPresenting===!0&&ee("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(W){a=W,n.isPresenting===!0&&ee("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return c||o},this.setReferenceSpace=function(W){c=W},this.getBaseLayer=function(){return d!==null?d:f},this.getBinding=function(){return h===null&&g&&(h=new XRWebGLBinding(i,t)),h},this.getFrame=function(){return p},this.getSession=function(){return i},this.setSession=async function(W){if(i=W,i!==null){if(v=e.getRenderTarget(),i.addEventListener("select",L),i.addEventListener("selectstart",L),i.addEventListener("selectend",L),i.addEventListener("squeeze",L),i.addEventListener("squeezestart",L),i.addEventListener("squeezeend",L),i.addEventListener("end",B),i.addEventListener("inputsourceschange",H),x.xrCompatible!==!0&&await t.makeXRCompatible(),y=e.getPixelRatio(),e.getSize(A),g&&"createProjectionLayer"in XRWebGLBinding.prototype){let le=null,Ne=null,Le=null;x.depth&&(Le=x.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,le=x.stencil?$n:Nn,Ne=x.stencil?ui:wt);const we={colorFormat:t.RGBA8,depthFormat:Le,scaleFactor:s};h=this.getBinding(),d=h.createProjectionLayer(we),i.updateRenderState({layers:[d]}),e.setPixelRatio(1),e.setSize(d.textureWidth,d.textureHeight,!1),S=new $i(d.textureWidth,d.textureHeight,{format:an,type:$t,depthTexture:new Xn(d.textureWidth,d.textureHeight,Ne,void 0,void 0,void 0,void 0,void 0,void 0,le),stencilBuffer:x.stencil,colorSpace:e.outputColorSpace,samples:x.antialias?4:0,resolveDepthBuffer:d.ignoreDepthValues===!1,resolveStencilBuffer:d.ignoreDepthValues===!1})}else{const le={antialias:x.antialias,alpha:!0,depth:x.depth,stencil:x.stencil,framebufferScaleFactor:s};f=new XRWebGLLayer(i,t,le),i.updateRenderState({baseLayer:f}),e.setPixelRatio(1),e.setSize(f.framebufferWidth,f.framebufferHeight,!1),S=new $i(f.framebufferWidth,f.framebufferHeight,{format:an,type:$t,colorSpace:e.outputColorSpace,stencilBuffer:x.stencil,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1})}S.isXRRenderTarget=!0,this.setFoveation(l),c=null,o=await i.requestReferenceSpace(a),oe.setContext(i),oe.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(i!==null)return i.environmentBlendMode},this.getDepthTexture=function(){return m.getDepthTexture()};function H(W){for(let se=0;se<W.removed.length;se++){const le=W.removed[se],Ne=T.indexOf(le);Ne>=0&&(T[Ne]=null,E[Ne].disconnect(le))}for(let se=0;se<W.added.length;se++){const le=W.added[se];let Ne=T.indexOf(le);if(Ne===-1){for(let we=0;we<E.length;we++)if(we>=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;we<Le.length;we++)Ce(Le[we],Ne);Le.length===2?ve(U,R,P):U.projectionMatrix.copy(R.projectionMatrix),ke(W,U,Ne)};function ke(W,se,le){le===null?W.matrix.copy(se.matrixWorld):(W.matrix.copy(le.matrixWorld),W.matrix.invert(),W.matrix.multiply(se.matrixWorld)),W.matrix.decompose(W.position,W.quaternion,W.scale),W.updateMatrixWorld(!0),W.projectionMatrix.copy(se.projectionMatrix),W.projectionMatrixInverse.copy(se.projectionMatrixInverse),W.isPerspectiveCamera&&(W.fov=ao*2*Math.atan(1/W.projectionMatrix.elements[5]),W.zoom=1)}this.getCamera=function(){return U},this.getFoveation=function(){if(!(d===null&&f===null))return l},this.setFoveation=function(W){l=W,d!==null&&(d.fixedFoveation=W),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=W)},this.hasDepthSensing=function(){return m.texture!==null},this.getDepthSensingMesh=function(){return m.getMesh(U)},this.getCameraTexture=function(W){return _[W]};let ut=null;function Mt(W,se){if(u=se.getViewerPose(c||o),p=se,u!==null){const le=u.views;f!==null&&(e.setRenderTargetFramebuffer(S,f.framebuffer),e.setRenderTarget(S));let Ne=!1;le.length!==U.cameras.length&&(U.cameras.length=0,Ne=!0);for(let Qe=0;Qe<le.length;Qe++){const ft=le[Qe];let Et=null;if(f!==null)Et=f.getViewport(ft);else{const It=h.getViewSubImage(d,ft);Et=It.viewport,Qe===0&&(e.setRenderTargetTextures(S,It.colorTexture,It.depthStencilTexture),e.setRenderTarget(S))}let Je=N[Qe];Je===void 0&&(Je=new Rn,Je.layers.enable(Qe),Je.viewport=new tt,N[Qe]=Je),Je.matrix.fromArray(ft.transform.matrix),Je.matrix.decompose(Je.position,Je.quaternion,Je.scale),Je.projectionMatrix.fromArray(ft.projectionMatrix),Je.projectionMatrixInverse.copy(Je.projectionMatrix).invert(),Je.viewport.set(Et.x,Et.y,Et.width,Et.height),Qe===0&&(U.matrix.copy(Je.matrix),U.matrix.decompose(U.position,U.quaternion,U.scale)),Ne===!0&&U.cameras.push(Je)}const Le=i.enabledFeatures;if(Le&&Le.includes("depth-sensing")&&i.depthUsage=="gpu-optimized"&&g){h=n.getBinding();const Qe=h.getDepthInformation(le[0]);Qe&&Qe.isValid&&Qe.texture&&m.init(Qe,i.renderState)}if(Le&&Le.includes("camera-access")&&g){e.state.unbindTexture(),h=n.getBinding();for(let Qe=0;Qe<le.length;Qe++){const ft=le[Qe].camera;if(ft){let Et=_[ft];Et||(Et=new Cx,_[ft]=Et);const Je=h.getCameraImage(ft);Et.sourceTexture=Je}}}}for(let le=0;le<E.length;le++){const Ne=T[le],Le=E[le];Ne!==null&&Le!==void 0&&Le.update(Ne,se,c||o)}ut&&ut(W,se),se.detectedPlanes&&n.dispatchEvent({type:"planesdetected",data:se}),p=null}const oe=new Hx;oe.setAnimationLoop(Mt),this.setAnimationLoop=function(W){ut=W},this.dispose=function(){}}}const LR=new dt,Kx=new Ke;Kx.set(-1,0,0,0,1,0,0,0,1);function UR(r,e){function t(m,_){m.matrixAutoUpdate===!0&&m.updateMatrix(),_.value.copy(m.matrix)}function n(m,_){_.color.getRGB(m.fogColor.value,Dx(r)),_.isFog?(m.fogNear.value=_.near,m.fogFar.value=_.far):_.isFogExp2&&(m.fogDensity.value=_.density)}function i(m,_,x,v,S){_.isNodeMaterial?_.uniformsNeedUpdate=!1:_.isMeshBasicMaterial?s(m,_):_.isMeshLambertMaterial?(s(m,_),_.envMap&&(m.envMapIntensity.value=_.envMapIntensity)):_.isMeshToonMaterial?(s(m,_),h(m,_)):_.isMeshPhongMaterial?(s(m,_),u(m,_),_.envMap&&(m.envMapIntensity.value=_.envMapIntensity)):_.isMeshStandardMaterial?(s(m,_),d(m,_),_.isMeshPhysicalMaterial&&f(m,_,S)):_.isMeshMatcapMaterial?(s(m,_),p(m,_)):_.isMeshDepthMaterial?s(m,_):_.isMeshDistanceMaterial?(s(m,_),g(m,_)):_.isMeshNormalMaterial?s(m,_):_.isLineBasicMaterial?(o(m,_),_.isLineDashedMaterial&&a(m,_)):_.isPointsMaterial?l(m,_,x,v):_.isSpriteMaterial?c(m,_):_.isShadowMaterial?(m.color.value.copy(_.color),m.opacity.value=_.opacity):_.isShaderMaterial&&(_.uniformsNeedUpdate=!1)}function s(m,_){m.opacity.value=_.opacity,_.color&&m.diffuse.value.copy(_.color),_.emissive&&m.emissive.value.copy(_.emissive).multiplyScalar(_.emissiveIntensity),_.map&&(m.map.value=_.map,t(_.map,m.mapTransform)),_.alphaMap&&(m.alphaMap.value=_.alphaMap,t(_.alphaMap,m.alphaMapTransform)),_.bumpMap&&(m.bumpMap.value=_.bumpMap,t(_.bumpMap,m.bumpMapTransform),m.bumpScale.value=_.bumpScale,_.side===Pt&&(m.bumpScale.value*=-1)),_.normalMap&&(m.normalMap.value=_.normalMap,t(_.normalMap,m.normalMapTransform),m.normalScale.value.copy(_.normalScale),_.side===Pt&&m.normalScale.value.negate()),_.displacementMap&&(m.displacementMap.value=_.displacementMap,t(_.displacementMap,m.displacementMapTransform),m.displacementScale.value=_.displacementScale,m.displacementBias.value=_.displacementBias),_.emissiveMap&&(m.emissiveMap.value=_.emissiveMap,t(_.emissiveMap,m.emissiveMapTransform)),_.specularMap&&(m.specularMap.value=_.specularMap,t(_.specularMap,m.specularMapTransform)),_.alphaTest>0&&(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;x<a;x++)if(o.indexOf(x)===-1)return o.push(x),x;return ne("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function d(x){const v=i[x.id],S=x.uniforms,E=x.__cache;r.bindBuffer(r.UNIFORM_BUFFER,v);for(let T=0,A=S.length;T<A;T++){const y=Array.isArray(S[T])?S[T]:[S[T]];for(let R=0,P=y.length;R<P;R++){const N=y[R];if(f(N,T,R,E)===!0){const U=N.__offset,G=Array.isArray(N.value)?N.value:[N.value];let V=0;for(let L=0;L<G.length;L++){const B=G[L],H=g(B);typeof B=="number"||typeof B=="boolean"?(N.__data[0]=B,r.bufferSubData(r.UNIFORM_BUFFER,U+V,N.__data)):B.isMatrix3?(N.__data[0]=B.elements[0],N.__data[1]=B.elements[1],N.__data[2]=B.elements[2],N.__data[3]=0,N.__data[4]=B.elements[3],N.__data[5]=B.elements[4],N.__data[6]=B.elements[5],N.__data[7]=0,N.__data[8]=B.elements[6],N.__data[9]=B.elements[7],N.__data[10]=B.elements[8],N.__data[11]=0):ArrayBuffer.isView(B)?N.__data.set(new B.constructor(B.buffer,B.byteOffset,N.__data.length)):(B.toArray(N.__data,V),V+=H.storage/Float32Array.BYTES_PER_ELEMENT)}r.bufferSubData(r.UNIFORM_BUFFER,U,N.__data)}}}r.bindBuffer(r.UNIFORM_BUFFER,null)}function f(x,v,S,E){const T=x.value,A=v+"_"+S;if(E[A]===void 0)return typeof T=="number"||typeof T=="boolean"?E[A]=T:ArrayBuffer.isView(T)?E[A]=T.slice():E[A]=T.clone(),!0;{const y=E[A];if(typeof T=="number"||typeof T=="boolean"){if(y!==T)return E[A]=T,!0}else{if(ArrayBuffer.isView(T))return!0;if(y.equals(T)===!1)return y.copy(T),!0}}return!1}function p(x){const v=x.uniforms;let S=0;const E=16;for(let A=0,y=v.length;A<y;A++){const R=Array.isArray(v[A])?v[A]:[v[A]];for(let P=0,N=R.length;P<N;P++){const U=R[P],G=Array.isArray(U.value)?U.value:[U.value];for(let V=0,L=G.length;V<L;V++){const B=G[V],H=g(B),ie=S%E,ce=ie%H.boundary,ve=ie+ce;S+=ce,ve!==0&&E-ve<H.storage&&(S+=E-ve),U.__data=new Float32Array(H.storage/Float32Array.BYTES_PER_ELEMENT),U.__offset=S,S+=H.storage}}}const T=S%E;return T>0&&(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<M.length;k++)if(M[k].isOutputPass===!0){ee("THREE.WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");break}}R.setEffects(M||[])},this.getCurrentViewport=function(M){return M.copy(ie)},this.getViewport=function(M){return M.copy(le)},this.setViewport=function(M,k,q,$){M.isVector4?le.set(M.x,M.y,M.z,M.w):le.set(M,k,q,$),be.viewport(ie.copy(le).multiplyScalar(oe).round())},this.getScissor=function(M){return M.copy(Ne)},this.setScissor=function(M,k,q,$){M.isVector4?Ne.set(M.x,M.y,M.z,M.w):Ne.set(M,k,q,$),be.scissor(ce.copy(Ne).multiplyScalar(oe).round())},this.getScissorTest=function(){return Le},this.setScissorTest=function(M){be.setScissorTest(Le=M)},this.setOpaqueSort=function(M){W=M},this.setTransparentSort=function(M){se=M},this.getClearColor=function(M){return M.copy(pe.getClearColor())},this.setClearColor=function(){pe.setClearColor(...arguments)},this.getClearAlpha=function(){return pe.getClearAlpha()},this.setClearAlpha=function(){pe.setClearAlpha(...arguments)},this.clear=function(M=!0,k=!0,q=!0){let $=0;if(M){let X=!1;if(L!==null){const Ae=L.texture.format;X=m.has(Ae)}if(X){const Ae=L.texture.type,Fe=_.has(Ae),Me=pe.getClearColor(),Ge=pe.getClearAlpha(),He=Me.r,st=Me.g,ct=Me.b;Fe?(x[0]=He,x[1]=st,x[2]=ct,x[3]=Ge,O.clearBufferuiv(O.COLOR,0,x)):(v[0]=He,v[1]=st,v[2]=ct,v[3]=Ge,O.clearBufferiv(O.COLOR,0,v))}else $|=O.COLOR_BUFFER_BIT}k&&($|=O.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0)),q&&($|=O.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),$!==0&&O.clear($)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.setNodesHandler=function(M){M.setRenderer(this),U=M},this.dispose=function(){t.removeEventListener("webglcontextlost",ue,!1),t.removeEventListener("webglcontextrestored",ze,!1),t.removeEventListener("webglcontextcreationerror",it,!1),pe.dispose(),ae.dispose(),Re.dispose(),w.dispose(),z.dispose(),fe.dispose(),me.dispose(),te.dispose(),ye.dispose(),xe.dispose(),xe.removeEventListener("sessionstart",nm),xe.removeEventListener("sessionend",im),Ir.stop()};function ue(M){M.preventDefault(),Kl("WebGLRenderer: Context Lost."),N=!0}function ze(){Kl("WebGLRenderer: Context Restored."),N=!1;const M=rn.autoReset,k=_e.enabled,q=_e.autoUpdate,$=_e.needsUpdate,X=_e.type;Pe(),rn.autoReset=M,_e.enabled=k,_e.autoUpdate=q,_e.needsUpdate=$,_e.type=X}function it(M){ne("WebGLRenderer: A WebGL context could not be created. Reason: ",M.statusMessage)}function ln(M){const k=M.target;k.removeEventListener("dispose",ln),Bt(k)}function Bt(M){Es(M),w.remove(M)}function Es(M){const k=w.get(M).programs;k!==void 0&&(k.forEach(function(q){ye.releaseProgram(q)}),M.isShaderMaterial&&ye.releaseShaderCache(M))}this.renderBufferDirect=function(M,k,q,$,X,Ae){k===null&&(k=It);const Fe=X.isMesh&&X.matrixWorld.determinant()<0,Me=Tv(M,k,q,$,X);be.setMaterial($,Fe);let Ge=q.index,He=1;if($.wireframe===!0){if(Ge=he.getWireframeAttribute(q),Ge===void 0)return;He=2}const st=q.drawRange,ct=q.attributes.position;let $e=st.start*He,Ot=(st.start+st.count)*He;Ae!==null&&($e=Math.max($e,Ae.start*He),Ot=Math.min(Ot,(Ae.start+Ae.count)*He)),Ge!==null?($e=Math.max($e,0),Ot=Math.min(Ot,Ge.count)):ct!=null&&($e=Math.max($e,0),Ot=Math.min(Ot,ct.count));const cn=Ot-$e;if(cn<0||cn===1/0)return;me.setup(X,$,Me,q,Ge);let on,Vt=at;if(Ge!==null&&(on=re.get(Ge),Vt=St,Vt.setIndex(on)),X.isMesh)$.wireframe===!0?(be.setLineWidth($.wireframeLinewidth*di()),Vt.setMode(O.LINES)):Vt.setMode(O.TRIANGLES);else if(X.isLine){let kn=$.linewidth;kn===void 0&&(kn=1),be.setLineWidth(kn*di()),X.isLineSegments?Vt.setMode(O.LINES):X.isLineLoop?Vt.setMode(O.LINE_LOOP):Vt.setMode(O.LINE_STRIP)}else X.isPoints?Vt.setMode(O.POINTS):X.isSprite&&Vt.setMode(O.TRIANGLES);if(X.isBatchedMesh)if(mt.get("WEBGL_multi_draw"))Vt.renderMultiDraw(X._multiDrawStarts,X._multiDrawCounts,X._multiDrawCount);else{const kn=X._multiDrawStarts,De=X._multiDrawCounts,fi=X._multiDrawCount,vt=Ge?re.get(Ge).bytesPerElement:1,bi=w.get($).currentProgram.getUniforms();for(let ji=0;ji<fi;ji++)bi.setValue(O,"_gl_DrawID",ji),Vt.render(kn[ji]/vt,De[ji])}else if(X.isInstancedMesh)Vt.renderInstances($e,cn,X.count);else if(q.isInstancedBufferGeometry){const kn=q._maxInstanceCount!==void 0?q._maxInstanceCount:1/0,De=Math.min(q.instanceCount,kn);Vt.renderInstances($e,cn,De)}else Vt.render($e,cn)};function qi(M,k,q){M.transparent===!0&&M.side===wn&&M.forceSinglePass===!1?(M.side=Pt,M.needsUpdate=!0,yc(M,k,q),M.side=ni,M.needsUpdate=!0,yc(M,k,q),M.side=wn):yc(M,k,q)}this.compile=function(M,k,q=null){q===null&&(q=M),T=Re.get(q),T.init(k),y.push(T),q.traverseVisible(function(X){X.isLight&&X.layers.test(k.layers)&&(T.pushLight(X),X.castShadow&&T.pushShadow(X))}),M!==q&&M.traverseVisible(function(X){X.isLight&&X.layers.test(k.layers)&&(T.pushLight(X),X.castShadow&&T.pushShadow(X))}),T.setupLights();const $=new Set;return M.traverse(function(X){if(!(X.isMesh||X.isPoints||X.isLine||X.isSprite))return;const Ae=X.material;if(Ae)if(Array.isArray(Ae))for(let Fe=0;Fe<Ae.length;Fe++){const Me=Ae[Fe];qi(Me,q,X),$.add(Me)}else qi(Ae,q,X),$.add(Ae)}),T=y.pop(),$},this.compileAsync=function(M,k,q=null){const $=this.compile(M,k,q);return new Promise(X=>{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;He<st;He++){const ct=Ge[He];rm(Fe,Me,M,ct)}Dt&&pe.render(M);for(let He=0,st=Ge.length;He<st;He++){const ct=Ge[He];sm(E,M,ct,ct.viewport)}}else Me.length>0&&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;He<st;He++){const ct=Ge[He],$e=Me[ct.materialIndex];$e&&$e.visible&&E.push(M,Fe,$e,q,Je.z,ct)}}else Me.visible&&E.push(M,Fe,Me,q,Je.z,null)}}const Ae=M.children;for(let Fe=0,Me=Ae.length;Fe<Me;Fe++)yh(Ae[Fe],k,q,$)}function sm(M,k,q,$){const{opaque:X,transmissive:Ae,transparent:Fe}=M;T.setupLightsView(q),xt===!0&&Ue.setGlobalState(P.clippingPlanes,q),$&&be.viewport(ie.copy($)),X.length>0&&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;Ot<cn;Ot++){const on=k[Ot],{object:Vt,geometry:kn,material:De,group:fi}=on;if(De.side===wn&&Vt.layers.test($.layers)){const vt=De.side;De.side=Pt,De.needsUpdate=!0,om(Vt,q,$,kn,De,fi),De.side=vt,De.needsUpdate=!0,$e=!0}}$e===!0&&(b.updateMultisampleRenderTarget(Ae),b.updateRenderTargetMipmap(Ae))}P.setRenderTarget(Me,Ge,He),P.setClearColor(Ce,ke),ct!==void 0&&($.viewport=ct),P.toneMapping=st}function xc(M,k,q){const $=k.isScene===!0?k.overrideMaterial:null;for(let X=0,Ae=M.length;X<Ae;X++){const Fe=M[X],{object:Me,geometry:Ge,group:He}=Fe;let st=Fe.material;st.allowOverride===!0&&$!==null&&(st=$),Me.layers.test(q.layers)&&om(Me,k,q,Ge,st,He)}}function om(M,k,q,$,X,Ae){M.onBeforeRender(P,k,q,$,X,Ae),M.modelViewMatrix.multiplyMatrices(q.matrixWorldInverse,M.matrixWorld),M.normalMatrix.getNormalMatrix(M.modelViewMatrix),X.onBeforeRender(P,k,q,$,M,Ae),X.transparent===!0&&X.side===wn&&X.forceSinglePass===!1?(X.side=Pt,X.needsUpdate=!0,P.renderBufferDirect(q,k,$,X,M,Ae),X.side=ni,X.needsUpdate=!0,P.renderBufferDirect(q,k,$,X,M,Ae),X.side=wn):P.renderBufferDirect(q,k,$,X,M,Ae),M.onAfterRender(P,k,q,$,X,Ae)}function yc(M,k,q){k.isScene!==!0&&(k=It);const $=w.get(M),X=T.state.lights,Ae=T.state.shadowsArray,Fe=X.state.version,Me=ye.getParameters(M,X.state,Ae,k,q,T.state.lightProbeGridArray),Ge=ye.getProgramCacheKey(Me);let He=$.programs;$.environment=M.isMeshStandardMaterial||M.isMeshLambertMaterial||M.isMeshPhongMaterial?k.environment:null,$.fog=k.fog;const st=M.isMeshStandardMaterial||M.isMeshLambertMaterial&&!M.envMap||M.isMeshPhongMaterial&&!M.envMap;$.envMap=z.get(M.envMap||$.environment,st),$.envMapRotation=$.environment!==null&&M.envMap===null?k.environmentRotation:M.envMapRotation,He===void 0&&(M.addEventListener("dispose",ln),He=new Map,$.programs=He);let ct=He.get(Ge);if(ct!==void 0){if($.currentProgram===ct&&$.lightsStateVersion===Fe)return lm(M,Me),ct}else Me.uniforms=ye.getUniforms(M),U!==null&&M.isNodeMaterial&&U.build(M,q,Me),M.onBeforeCompile(Me,P),ct=ye.acquireProgram(Me,Ge),He.set(Ge,ct),$.uniforms=Me.uniforms;const $e=$.uniforms;return(!M.isShaderMaterial&&!M.isRawShaderMaterial||M.clipping===!0)&&($e.clippingPlanes=Ue.uniform),lm(M,Me),$.needsLights=Ev(M),$.lightsStateVersion=Fe,$.needsLights&&($e.ambientLightColor.value=X.state.ambient,$e.lightProbe.value=X.state.probe,$e.directionalLights.value=X.state.directional,$e.directionalLightShadows.value=X.state.directionalShadow,$e.spotLights.value=X.state.spot,$e.spotLightShadows.value=X.state.spotShadow,$e.rectAreaLights.value=X.state.rectArea,$e.ltc_1.value=X.state.rectAreaLTC1,$e.ltc_2.value=X.state.rectAreaLTC2,$e.pointLights.value=X.state.point,$e.pointLightShadows.value=X.state.pointShadow,$e.hemisphereLights.value=X.state.hemi,$e.directionalShadowMatrix.value=X.state.directionalShadowMatrix,$e.spotLightMatrix.value=X.state.spotLightMatrix,$e.spotLightMap.value=X.state.spotLightMap,$e.pointShadowMatrix.value=X.state.pointShadowMatrix),$.lightProbeGrid=T.state.lightProbeGridArray.length>0,$.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;Zs<Eo;Zs++){const cm=qt[Zs];te.update(cm,bi),te.bind(cm,bi)}}return bi}function Mv(M,k){M.ambientLightColor.needsUpdate=k,M.lightProbe.needsUpdate=k,M.directionalLights.needsUpdate=k,M.directionalLightShadows.needsUpdate=k,M.pointLights.needsUpdate=k,M.pointLightShadows.needsUpdate=k,M.spotLights.needsUpdate=k,M.spotLightShadows.needsUpdate=k,M.rectAreaLights.needsUpdate=k,M.hemisphereLights.needsUpdate=k}function Ev(M){return M.isMeshLambertMaterial||M.isMeshToonMaterial||M.isMeshPhongMaterial||M.isMeshStandardMaterial||M.isShadowMaterial||M.isShaderMaterial&&M.lights===!0}this.getActiveCubeFace=function(){return G},this.getActiveMipmapLevel=function(){return V},this.getRenderTarget=function(){return L},this.setRenderTargetTextures=function(M,k,q){const $=w.get(M);$.__autoAllocateDepthBuffer=M.resolveDepthBuffer===!1,$.__autoAllocateDepthBuffer===!1&&($.__useRenderToTexture=!1),w.get(M.texture).__webglTexture=k,w.get(M.depthTexture).__webglTexture=$.__autoAllocateDepthBuffer?void 0:q,$.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(M,k){const q=w.get(M);q.__webglFramebuffer=k,q.__useDefaultFramebuffer=k===void 0};const Av=O.createFramebuffer();this.setRenderTarget=function(M,k=0,q=0){L=M,G=k,V=q;let $=null,X=!1,Ae=!1;if(M){const Me=w.get(M);if(Me.__useDefaultFramebuffer!==void 0){be.bindFramebuffer(O.FRAMEBUFFER,Me.__webglFramebuffer),ie.copy(M.viewport),ce.copy(M.scissor),ve=M.scissorTest,be.viewport(ie),be.scissor(ce),be.setScissorTest(ve),B=-1;return}else if(Me.__webglFramebuffer===void 0)b.setupRenderTarget(M);else if(Me.__hasExternalTextures)b.rebindTextures(M,w.get(M.texture).__webglTexture,w.get(M.depthTexture).__webglTexture);else if(M.depthBuffer){const st=M.depthTexture;if(Me.__boundDepthTexture!==st){if(st!==null&&w.has(st)&&(M.width!==st.image.width||M.height!==st.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");b.setupDepthRenderbuffer(M)}}const Ge=M.texture;(Ge.isData3DTexture||Ge.isDataArrayTexture||Ge.isCompressedArrayTexture)&&(Ae=!0);const He=w.get(M).__webglFramebuffer;M.isWebGLCubeRenderTarget?(Array.isArray(He[k])?$=He[k][q]:$=He[k],X=!0):M.samples>0&&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;Ge<M.textures.length;Ge++){const He=w.get(M.textures[Ge]);O.framebufferTextureLayer(O.FRAMEBUFFER,O.COLOR_ATTACHMENT0+Ge,He.__webglTexture,q,Me)}}else if(M!==null&&q!==0){const Me=w.get(M.texture);O.framebufferTexture2D(O.FRAMEBUFFER,O.COLOR_ATTACHMENT0,O.TEXTURE_2D,Me.__webglTexture,q)}B=-1},this.readRenderTargetPixels=function(M,k,q,$,X,Ae,Fe,Me=0){if(!(M&&M.isWebGLRenderTarget)){ne("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let Ge=w.get(M).__webglFramebuffer;if(M.isWebGLCubeRenderTarget&&Fe!==void 0&&(Ge=Ge[Fe]),Ge){be.bindFramebuffer(O.FRAMEBUFFER,Ge);try{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)){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;Eo<Ge;Eo++)Mo&&(O.framebufferTextureLayer(O.READ_FRAMEBUFFER,O.COLOR_ATTACHMENT0,w.get(M).__webglTexture,X,ct+Eo),O.framebufferTextureLayer(O.DRAW_FRAMEBUFFER,O.COLOR_ATTACHMENT0,w.get(k).__webglTexture,Ae,cn+Eo)),O.blitFramebuffer(He,st,Fe,Me,$e,Ot,Fe,Me,O.DEPTH_BUFFER_BIT,O.NEAREST);be.bindFramebuffer(O.READ_FRAMEBUFFER,null),be.bindFramebuffer(O.DRAW_FRAMEBUFFER,null)}else if(X!==0||M.isRenderTargetTexture||w.has(M)){const un=w.get(M),Ks=w.get(k);be.bindFramebuffer(O.READ_FRAMEBUFFER,Rv),be.bindFramebuffer(O.DRAW_FRAMEBUFFER,wv);for(let qt=0;qt<Ge;qt++)Mo?O.framebufferTextureLayer(O.READ_FRAMEBUFFER,O.COLOR_ATTACHMENT0,un.__webglTexture,X,ct+qt):O.framebufferTexture2D(O.READ_FRAMEBUFFER,O.COLOR_ATTACHMENT0,O.TEXTURE_2D,un.__webglTexture,X),zt?O.framebufferTextureLayer(O.DRAW_FRAMEBUFFER,O.COLOR_ATTACHMENT0,Ks.__webglTexture,Ae,cn+qt):O.framebufferTexture2D(O.DRAW_FRAMEBUFFER,O.COLOR_ATTACHMENT0,O.TEXTURE_2D,Ks.__webglTexture,Ae),X!==0?O.blitFramebuffer(He,st,Fe,Me,$e,Ot,Fe,Me,O.COLOR_BUFFER_BIT,O.NEAREST):zt?O.copyTexSubImage3D(De,Ae,$e,Ot,cn+qt,He,st,Fe,Me):O.copyTexSubImage2D(De,Ae,$e,Ot,He,st,Fe,Me);be.bindFramebuffer(O.READ_FRAMEBUFFER,null),be.bindFramebuffer(O.DRAW_FRAMEBUFFER,null)}else zt?M.isDataTexture||M.isData3DTexture?O.texSubImage3D(De,Ae,$e,Ot,cn,Fe,Me,Ge,Vt,kn,on.data):k.isCompressedArrayTexture?O.compressedTexSubImage3D(De,Ae,$e,Ot,cn,Fe,Me,Ge,Vt,on.data):O.texSubImage3D(De,Ae,$e,Ot,cn,Fe,Me,Ge,Vt,kn,on):M.isDataTexture?O.texSubImage2D(O.TEXTURE_2D,Ae,$e,Ot,Fe,Me,Vt,kn,on.data):M.isCompressedTexture?O.compressedTexSubImage2D(O.TEXTURE_2D,Ae,$e,Ot,on.width,on.height,Vt,on.data):O.texSubImage2D(O.TEXTURE_2D,Ae,$e,Ot,Fe,Me,Vt,kn,on);be.pixelStorei(O.UNPACK_ROW_LENGTH,fi),be.pixelStorei(O.UNPACK_IMAGE_HEIGHT,vt),be.pixelStorei(O.UNPACK_SKIP_PIXELS,bi),be.pixelStorei(O.UNPACK_SKIP_ROWS,ji),be.pixelStorei(O.UNPACK_SKIP_IMAGES,Ys),Ae===0&&k.generateMipmaps&&O.generateMipmap(De),be.unbindTexture()},this.initRenderTarget=function(M){w.get(M).__webglFramebuffer===void 0&&b.setupRenderTarget(M)},this.initTexture=function(M){M.isCubeTexture?b.setTextureCube(M,0):M.isData3DTexture?b.setTexture3D(M,0):M.isDataArrayTexture||M.isCompressedArrayTexture?b.setTexture2DArray(M,0):b.setTexture2D(M,0),be.unbindTexture()},this.resetState=function(){G=0,V=0,L=null,be.reset(),me.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return ti}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const t=this.getContext();t.drawingBufferColorSpace=Xe._getDrawingBufferColorSpace(e),t.unpackColorSpace=Xe._getUnpackColorSpace()}}const ea=new os,Is=new de,Zx=new C,ed=new de,Tu=new de,Iu=new C,af=new C,Qx=new dt,Jx=new C,e0=new C;let Hn=null,ss=null;const Bs=[],Tr={NONE:-1,PAN:0,ROTATE:1};class kR extends Ju{constructor(e,t,n=null){super(t,n),this.objects=e,this.recursive=!0,this.transformGroup=!1,this.rotateSpeed=1,this.raycaster=new zx,this.mouseButtons={LEFT:Ln.PAN,MIDDLE:Ln.PAN,RIGHT:Ln.ROTATE},this.touches={ONE:ks.PAN},this._onPointerMove=GR.bind(this),this._onPointerDown=VR.bind(this),this._onPointerCancel=zR.bind(this),this._onContextMenu=HR.bind(this),n!==null&&this.connect(n)}connect(e){super.connect(e),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointerup",this._onPointerCancel),this.domElement.addEventListener("pointerleave",this._onPointerCancel),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointerup",this._onPointerCancel),this.domElement.removeEventListener("pointerleave",this._onPointerCancel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction="",this.domElement.style.cursor=""}dispose(){this.disconnect()}_updatePointer(e){const t=this.domElement.getBoundingClientRect();Is.x=(e.clientX-t.left)/t.width*2-1,Is.y=-(e.clientY-t.top)/t.height*2+1}_updateState(e){let t;if(e.pointerType==="touch")t=this.touches.ONE;else switch(e.button){case 0:t=this.mouseButtons.LEFT;break;case 1:t=this.mouseButtons.MIDDLE;break;case 2:t=this.mouseButtons.RIGHT;break;default:t=null}switch(t){case Ln.PAN:case ks.PAN:this.state=Tr.PAN;break;case Ln.ROTATE:case ks.ROTATE:this.state=Tr.ROTATE;break;default:this.state=Tr.NONE}}}function GR(r){const e=this.object,t=this.domElement,n=this.raycaster;if(this.enabled!==!1){if(this._updatePointer(r),n.setFromCamera(Is,e),Hn)this.state===Tr.PAN?n.ray.intersectPlane(ea,Iu)&&(Hn.position.copy(Iu.sub(Zx).applyMatrix4(Qx)),this.dispatchEvent({type:"drag",object:Hn})):this.state===Tr.ROTATE&&(ed.subVectors(Is,Tu).multiplyScalar(this.rotateSpeed),Hn.rotateOnWorldAxis(Jx,ed.x),Hn.rotateOnWorldAxis(e0.normalize(),-ed.y),this.dispatchEvent({type:"drag",object:Hn})),Tu.copy(Is);else if(r.pointerType==="mouse"||r.pointerType==="pen")if(Bs.length=0,n.setFromCamera(Is,e),n.intersectObjects(this.objects,this.recursive,Bs),Bs.length>0){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);t<e;t++)n[t]=r[t];return n}function WR(r){if(Array.isArray(r))return r}function $R(r){if(Array.isArray(r))return lf(r)}function n0(r,e,t){if(typeof r=="function"?r===e:r.has(e))return arguments.length<3?e:t;throw new TypeError("Private element is not present on this object")}function XR(r){if(r===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return r}function i0(r,e,t){return e=La(e),ew(r,yp()?Reflect.construct(e,t||[],La(r).constructor):e.apply(r,t))}function qR(r,e){if(e.has(r))throw new TypeError("Cannot initialize the same private elements twice on an object")}function s0(r,e){if(!(r instanceof e))throw new TypeError("Cannot call a class as a function")}function td(r,e){return r.get(n0(r,e))}function dg(r,e,t){qR(r,e),e.set(r,t)}function fg(r,e,t){return r.set(n0(r,e),t),t}function r0(r,e,t){if(yp())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,e);var i=new(r.bind.apply(r,n));return i}function jR(r,e){for(var t=0;t<e.length;t++){var n=e[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(r,l0(n.key),n)}}function o0(r,e,t){return e&&jR(r.prototype,e),Object.defineProperty(r,"prototype",{writable:!1}),r}function nh(r,e,t){return(e=l0(e))in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function cf(){return cf=typeof Reflect<"u"&&Reflect.get?Reflect.get.bind():function(r,e,t){var n=tw(r,e);if(n){var i=Object.getOwnPropertyDescriptor(n,e);return i.get?i.get.call(arguments.length<3?r:t):i.value}},cf.apply(null,arguments)}function La(r){return La=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},La(r)}function a0(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");r.prototype=Object.create(e&&e.prototype,{constructor:{value:r,writable:!0,configurable:!0}}),Object.defineProperty(r,"prototype",{writable:!1}),e&&uf(r,e)}function yp(){try{var r=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(yp=function(){return!!r})()}function YR(r){if(typeof Symbol<"u"&&r[Symbol.iterator]!=null||r["@@iterator"]!=null)return Array.from(r)}function KR(r,e){var t=r==null?null:typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(t!=null){var n,i,s,o,a=[],l=!0,c=!1;try{if(s=(t=t.call(r)).next,e!==0)for(;!(l=(n=s.call(t)).done)&&(a.push(n.value),a.length!==e);l=!0);}catch(u){c=!0,i=u}finally{try{if(!l&&t.return!=null&&(o=t.return(),Object(o)!==o))return}finally{if(c)throw i}}return a}}function ZR(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function QR(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
|
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function pg(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function JR(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?pg(Object(t),!0).forEach(function(n){nh(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):pg(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}function ew(r,e){if(e&&(typeof e=="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return XR(r)}function uf(r,e){return uf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,n){return t.__proto__=n,t},uf(r,e)}function El(r,e){return WR(r)||KR(r,e)||c0(r,e)||ZR()}function tw(r,e){for(;!{}.hasOwnProperty.call(r,e)&&(r=La(r))!==null;);return r}function nd(r,e,t,n){var i=cf(La(r.prototype),e,t);return typeof i=="function"?function(s){return i.apply(t,s)}:i}function zi(r){return $R(r)||YR(r)||c0(r)||QR()}function nw(r,e){if(typeof r!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var n=t.call(r,e);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function l0(r){var e=nw(r,"string");return typeof e=="symbol"?e:e+""}function hf(r){"@babel/helpers - typeof";return hf=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},hf(r)}function c0(r,e){if(r){if(typeof r=="string")return lf(r,e);var t={}.toString.call(r).slice(8,-1);return t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set"?Array.from(r):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?lf(r,e):void 0}}var u0=function(e){e instanceof Array?e.forEach(u0):(e.map&&e.map.dispose(),e.dispose())},vp=function(e){e.geometry&&e.geometry.dispose(),e.material&&u0(e.material),e.texture&&e.texture.dispose(),e.children&&e.children.forEach(vp)},mg=function(e){for(;e.children.length;){var t=e.children[0];e.remove(t),vp(t)}},id=new WeakMap,Wc=new WeakMap,sl=function(r){function e(t){var n,i=arguments.length>1&&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;_<x;_++)m()}}var Ye=window.THREE?window.THREE:{Group:Xo,Mesh:gn,MeshLambertMaterial:Fx,Color:Ve,BufferGeometry:Pn,BufferAttribute:In,Matrix4:dt,Vector3:C,SphereGeometry:hc,CylinderGeometry:cc,TubeGeometry:mp,ConeGeometry:dp,Line:JS,LineBasicMaterial:Qu,QuadraticBezierCurve3:pp,CubicBezierCurve3:Px,Box3:xo},_g={graph:Cv,forcelayout:Nv},rw=2,rd=new Ye.BufferGeometry().setAttribute?"setAttribute":"addAttribute",$c=new Ye.BufferGeometry().applyMatrix4?"applyMatrix4":"applyMatrix",ow=Df({props:{jsonUrl:{onChange:function(e,t){var n=this;e&&!t.fetchingJson&&(t.fetchingJson=!0,t.onLoading(),fetch(e).then(function(i){return i.json()}).then(function(i){t.fetchingJson=!1,t.onFinishLoading(i),n.graphData(i)}))},triggerUpdate:!1},graphData:{default:{nodes:[],links:[]},onChange:function(e,t){t.engineRunning=!1}},numDimensions:{default:3,onChange:function(e,t){var n=t.d3ForceLayout.force("charge");n&&n.strength(e>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()<e.d3AlphaMin?(e.engineRunning=!1,e.onEngineStop()):(e.layout[t?"tick":"step"](),e.onEngineTick());var o=gt(e.nodeThreeObjectExtend);e.nodeDataMapper.entries().forEach(function(d){var f=El(d,2),p=f[0],g=f[1];if(g){var m=t?p:e.layout.getNodePosition(p[e.nodeId]),_=o(p);(!e.nodePositionUpdate||!e.nodePositionUpdate(_?g.children[0]:g,{x:m.x,y:m.y,z:m.z},p)||_)&&(g.position.x=m.x,g.position.y=m.y||0,g.position.z=m.z||0)}});var a=gt(e.linkWidth),l=gt(e.linkCurvature),c=gt(e.linkCurveRotation),u=gt(e.linkThreeObjectExtend);e.linkDataMapper.entries().forEach(function(d){var f=El(d,2),p=f[0],g=f[1];if(g){var m=t?p:e.layout.getLinkPosition(e.layout.graph.getLink(p.source,p.target).id),_=m[t?"source":"from"],x=m[t?"target":"to"];if(!(!_||!x||!_.hasOwnProperty("x")||!x.hasOwnProperty("x"))){h(p);var v=u(p);if(!(e.linkPositionUpdate&&e.linkPositionUpdate(v?g.children[1]:g,{start:{x:_.x,y:_.y,z:_.z},end:{x:x.x,y:x.y,z:x.z}},p)&&!v)){var S=30,E=p.__curve,T=g.children.length?g.children[0]:g;if(T.type==="Line"){if(E){var y=E.getPoints(S);T.geometry.getAttribute("position").array.length!==y.length*3&&T.geometry[rd]("position",new Ye.BufferAttribute(new Float32Array(y.length*3),3)),T.geometry.setFromPoints(y)}else{var A=T.geometry.getAttribute("position");(!A||!A.array||A.array.length!==6)&&T.geometry[rd]("position",A=new Ye.BufferAttribute(new Float32Array(2*3),3)),A.array[0]=_.x,A.array[1]=_.y||0,A.array[2]=_.z||0,A.array[3]=x.x,A.array[4]=x.y||0,A.array[5]=x.z||0,A.needsUpdate=!0}T.geometry.computeBoundingSphere()}else if(T.type==="Mesh")if(E){T.geometry.type.match(/^Tube(Buffer)?Geometry$/)||(T.position.set(0,0,0),T.rotation.set(0,0,0),T.scale.set(1,1,1));var L=Math.ceil(a(p)*10)/10,B=L/2,H=new Ye.TubeGeometry(E,S,B,e.linkResolution,!1);T.geometry.dispose(),T.geometry=H}else{if(!T.geometry.type.match(/^Cylinder(Buffer)?Geometry$/)){var R=Math.ceil(a(p)*10)/10,P=R/2,N=new Ye.CylinderGeometry(P,P,1,e.linkResolution,1,!1);N[$c](new Ye.Matrix4().makeTranslation(0,1/2,0)),N[$c](new Ye.Matrix4().makeRotationX(Math.PI/2)),T.geometry.dispose(),T.geometry=N}var U=new Ye.Vector3(_.x,_.y||0,_.z||0),G=new Ye.Vector3(x.x,x.y||0,x.z||0),V=U.distanceTo(G);T.position.x=U.x,T.position.y=U.y,T.position.z=U.z,T.scale.z=V,T.parent.localToWorld(G),T.lookAt(G)}}}}});function h(d){var f=t?d:e.layout.getLinkPosition(e.layout.graph.getLink(d.source,d.target).id),p=f[t?"source":"from"],g=f[t?"target":"to"];if(!(!p||!g||!p.hasOwnProperty("x")||!g.hasOwnProperty("x"))){var m=l(d);if(!m)d.__curve=null;else{var _=new Ye.Vector3(p.x,p.y||0,p.z||0),x=new Ye.Vector3(g.x,g.y||0,g.z||0),v=_.distanceTo(x),S,E=c(d);if(v>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;Mt<e.warmupTicks&&!(G&&e.d3AlphaMin>0&&e.d3ForceLayout.alpha()<e.d3AlphaMin);Mt++)V[G?"tick":"step"]();e.layout=V,this.resetCountdown()}e.engineRunning=!0,e.onFinishUpdate()}});function aw(r){var e=arguments.length>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;c<a;c++)l[c]=arguments[c];return o=i0(this,s,[].concat(l)),o.__kapsuleInstance=r0(r,[].concat(zi(t?[o]:[]),l)),o}return a0(s,i),o0(s)}(e);return Object.keys(r()).forEach(function(i){return n.prototype[i]=function(){var s,o=(s=this.__kapsuleInstance)[i].apply(s,arguments);return o===this.__kapsuleInstance?this:o}}),n}var lw=window.THREE?window.THREE:{Group:Xo},h0=aw(ow,lw.Group,!0);/**
|
|
* @license
|
|
* Copyright 2010-2026 Three.js Authors
|
|
* SPDX-License-Identifier: MIT
|
|
*/const cw=["alphaMap","alphaTest","anisotropy","anisotropyMap","anisotropyRotation","aoMap","aoMapIntensity","attenuationColor","attenuationDistance","bumpMap","clearcoat","clearcoatMap","clearcoatNormalMap","clearcoatNormalScale","clearcoatRoughness","color","dispersion","displacementMap","emissive","emissiveIntensity","emissiveMap","envMap","envMapIntensity","gradientMap","ior","iridescence","iridescenceIOR","iridescenceMap","iridescenceThicknessMap","lightMap","lightMapIntensity","map","matcap","metalness","metalnessMap","normalMap","normalScale","opacity","roughness","roughnessMap","sheen","sheenColor","sheenColorMap","sheenRoughnessMap","shininess","specular","specularColor","specularColorMap","specularIntensity","specularIntensityMap","specularMap","thickness","transmission","transmissionMap"],od=new WeakMap,xg=new WeakMap,yg=new WeakMap;class uw{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=e.object.isSkinnedMesh===!0,this.refreshUniforms=cw,this.renderId=0}firstInitialization(e){return this.renderObjects.has(e)===!1?(this.getRenderObjectData(e),!0):!1}needsVelocity(e){const t=e.getMRT();return t!==null&&t.has("velocity")}getRenderObjectData(e){let t=this.renderObjects.get(e);if(t===void 0){const{geometry:n,object:i}=e;if(t={geometryId:n.id,worldMatrix:i.matrixWorld.clone()},i.center&&(t.center=i.center.clone()),i.morphTargetInfluences&&(t.morphTargetInfluences=i.morphTargetInfluences.slice()),e.bundle!==null&&(t.version=e.bundle.version),e.material.transmission>0){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<a.morphTargetInfluences.length;h++)a.morphTargetInfluences[h]!==i.morphTargetInfluences[h]&&(a.morphTargetInfluences[h]=i.morphTargetInfluences[h],u=!0);if(u)return!1}if(a.lights){for(let u=0;u<t.length;u++)if(a.lights[u].map!==t[u].map)return!1}return a.center&&a.center.equals(i.center)===!1?(a.center.copy(i.center),!0):(e.bundle!==null&&(a.version=e.bundle.version),!0)}getLightsData(e){const t=[];for(const n of e)n.isSpotLight===!0&&n.map!==null&&t.push({map:n.map.version});return t}getLights(e,t){if(od.has(e)){const i=od.get(e);if(i.renderId===t)return i.lightsData}const n=this.getLightsData(e.getLights());return od.set(e,{renderId:t,lightsData:n}),n}needsRefresh(e,t){if(this.hasNode||this.hasAnimation||this.firstInitialization(e)||this.needsVelocity(t.renderer))return!0;const{renderId:n}=t;if(this.renderId!==n)return this.renderId=n,!0;const i=e.object.static===!0,s=e.bundle!==null&&e.bundle.static===!0&&this.getRenderObjectData(e).version===e.bundle.version;if(i||s)return!1;const o=this.getLights(e.lightsNode,n);return this.equals(e,o,n)!==!0}}const hw=[/^StackTrace\.js$/,/^TSLCore\.js$/,/^.*Node\.js$/,/^three\.webgpu.*\.js$/];function dw(r){const e=/(?:at\s+(.+?)\s+\()?(?:(.+?)@)?([^@\s()]+):(\d+):(\d+)/;return r.split(`
|
|
`).map(t=>{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<r.length;i++)s=r[i],t=Math.imul(t^s,2654435761),n=Math.imul(n^s,1597334677);else for(let i=0,s;i<r.length;i++)s=r.charCodeAt(i),t=Math.imul(t^s,2654435761),n=Math.imul(n^s,1597334677);return t=Math.imul(t^t>>>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;n<t.length;n++)e+=String.fromCharCode(t[n]);return btoa(e)}function mw(r){return Uint8Array.from(atob(r),e=>e.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;s<i.length;s++){const o=i[s];o&&o.isNode===!0&&t.push({property:n,index:s,childNode:o})}else if(i&&i.isNode===!0)t.push({property:n,childNode:i});else if(i&&Object.getPrototypeOf(i)===Object.prototype)for(const s in i){if(s.startsWith("_")===!0)continue;const o=i[s];o&&o.isNode===!0&&t.push({property:n,index:s,childNode:o})}}}return t}getCacheKey(e=!1,t=null){if(e=e||this.version!==this._cacheKeyVersion,e===!0||this._cacheKey===null){t===null&&(t=new Set);const n=[];for(const{property:i,childNode:s}of this._getChildren(t))n.push(Ha(i.slice(0,-4)),s.getCacheKey(e,t));this._cacheKey=Al(dc(n),this.customCacheKey()),this._cacheKeyVersion=this.version}return this._cacheKey}customCacheKey(){return this.id}getScope(){return this}getHash(){return String(this.id)}getUpdateType(){return this.updateType}getUpdateBeforeType(){return this.updateBeforeType}getUpdateAfterType(){return this.updateAfterType}getElementType(e){const t=this.getNodeType(e);return e.getElementType(t)}getMemberType(){return"void"}getNodeType(e,t=null){const n=e.getDataFromNode(this);let i;return t!==null?(n.typeFromOutput=n.typeFromOutput||{},i=n.typeFromOutput[t],i===void 0&&(i=this.generateNodeType(e,t),n.typeFromOutput[t]=i)):(i=n.type,i===void 0&&(i=this.generateNodeType(e),n.type=i)),i}generateNodeType(e,t=null){const n=e.getNodeProperties(this);return n.outputNode?n.outputNode.getNodeType(e,t):this.nodeType}getShared(e){const t=this.getHash(e);return e.getNodeFromHash(t)||this}getArrayCount(){return null}setup(e){const t=e.getNodeProperties(this);let n=0;for(const i of this.getChildren())t["node"+n++]=i;return t.outputNode||null}analyze(e,t=null){const n=e.increaseUsage(this);if(this.parents===!0){const i=e.getDataFromNode(this,"any");i.stages=i.stages||{},i.stages[e.shaderStage]=i.stages[e.shaderStage]||[],i.stages[e.shaderStage].push(t)}if(n===1){const i=e.getNodeProperties(this);for(const s of Object.values(i))s&&s.isNode===!0&&s.build(e,this)}}generate(e,t){const{outputNode:n}=e.getNodeProperties(this);if(n&&n.isNode===!0)return n.build(e,t)}updateBefore(){ee("Abstract function.")}updateAfter(){ee("Abstract function.")}update(){ee("Abstract function.")}before(e){return this._beforeNodes===null&&(this._beforeNodes=[]),this._beforeNodes.push(e),this}build(e,t=null){const n=this.getShared(e);if(this!==n)return n.build(e,t);if(this._beforeNodes!==null){const l=this._beforeNodes;this._beforeNodes=null;for(const c of l)c.build(e,t);this._beforeNodes=l}const i=e.getDataFromNode(this);i.buildStages=i.buildStages||{},i.buildStages[e.buildStage]=!0;const s=_w[e.buildStage];if(s&&i.buildStages[s]!==!0){const l=e.getBuildStage();e.setBuildStage(s),this.build(e),e.setBuildStage(l)}e.addChain(this);let o=null;const a=e.getBuildStage();if(a==="setup"){e.addNode(this),this.updateReference(e);const l=e.getNodeProperties(this);if(l.initialized!==!0){l.initialized=!0,l.outputNode=this.setup(e)||l.outputNode||null;for(const c of Object.values(l))if(c&&c.isNode===!0){if(c.parents===!0){const u=e.getNodeProperties(c);u.parents=u.parents||[],u.parents.push(this)}c.build(e)}e.addSequentialNode(this)}o=l.outputNode}else if(a==="analyze")this.analyze(e,t);else if(a==="generate"){if(this.generate.length<2){const c=this.getNodeType(e),u=e.getDataFromNode(this);o=u.snippet,o===void 0?u.generated===void 0?(u.generated=!0,o=this.generate(e)||"",u.snippet=o):(ee("Node: Recursion detected.",this),o="/* Recursion detected. */"):u.flowCodes!==void 0&&e.context.nodeBlock!==void 0&&e.addFlowCodeHierarchy(this,e.context.nodeBlock),o=e.format(o,c,t)}else o=this.generate(e,t)||"";o===""&&t!==null&&t!=="void"&&t!=="OutputType"&&(ne(`TSL: Invalid generated code, expected a "${t}".`),o=e.generateConst(t))}return e.removeChain(this),o}getSerializeChildren(){return this._getChildren()}serialize(e){const t=this.getSerializeChildren(),n={};for(const{property:i,index:s,childNode:o}of t)s!==void 0?(n[i]===void 0&&(n[i]=Number.isInteger(s)?[]:{}),n[i][s]=o.toJSON(e.meta).uuid):n[i]=o.toJSON(e.meta).uuid;Object.keys(n).length>0&&(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;d<u;d++){const f=Wa[d];f===n[0]?(h.push(l),d+=n.length-1):h.push(c+"."+f)}return`${e.getType(s)}( ${h.join(", ")} )`}}class Tw extends _n{static get type(){return"FlipNode"}constructor(e,t){super(),this.sourceNode=e,this.components=t}generateNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{components:t,sourceNode:n}=this,i=this.getNodeType(e),s=n.build(e),o=e.getVarFromNode(this),a=e.getPropertyName(o);e.addLineFlowCode(a+" = "+s,this);const l=e.getTypeLength(i),c=[];let u=0;for(let h=0;h<l;h++){const d=Wa[h];d===t[u]?(c.push("1.0 - "+(a+"."+d)),u++):c.push(a+"."+d)}return`${e.getType(i)}( ${c.join(", ")} )`}}class Tp extends Oe{static get type(){return"InputNode"}constructor(e,t=null){super(t),this.isInputNode=!0,this.value=e,this.precision=null}generateNodeType(){return this.nodeType===null?Bu(this.value):this.nodeType}getInputType(e){return this.getNodeType(e)}setPrecision(e){return this.precision=e,this}serialize(e){super.serialize(e),e.value=this.value,this.value&&this.value.toArray&&(e.value=this.value.toArray()),e.valueType=Bu(this.value),e.nodeType=this.nodeType,e.valueType==="ArrayBuffer"&&(e.value=pw(e.value)),e.precision=this.precision}deserialize(e){super.deserialize(e),this.nodeType=e.nodeType,this.value=Array.isArray(e.value)?bp(e.valueType,...e.value):e.value,this.precision=e.precision||null,this.value&&this.value.fromArray&&(this.value=this.value.fromArray(e.value))}generate(){ee("Abstract function.")}}const Sg=/float|u?int/;class Ts extends Tp{static get type(){return"ConstNode"}constructor(e,t=null){super(e,t),this.isConstNode=!0}generateConst(e){return e.generateConst(this.getNodeType(e),this.value)}generate(e,t){const n=this.getNodeType(e);return Sg.test(n)&&Sg.test(t)?e.generateConst(t,this.value):e.format(this.generateConst(e),n,t)}}class Mw extends Oe{static get type(){return"MemberNode"}constructor(e,t){super(),this.structNode=e,this.property=t,this.isMemberNode=!0}hasMember(e){return this.structNode.isMemberNode&&this.structNode.hasMember(e)===!1?!1:this.structNode.getMemberType(e,this.property)!=="void"}generateNodeType(e){return this.hasMember(e)===!1?"float":this.structNode.getMemberType(e,this.property)}getMemberType(e,t){if(this.hasMember(e)===!1)return"float";const n=this.getNodeType(e);return e.getStructTypeNode(n).getMemberType(e,t)}generate(e){if(this.hasMember(e)===!1){ee(`TSL: Member "${this.property}" does not exist in struct.`,this.stackTrace);const n=this.getNodeType(e);return e.generateConst(n)}return this.structNode.build(e)+"."+this.property}}let lo=null;const df=new Map;function Y(r,e){if(df.has(r)){ee(`TSL: Redefinition of method chaining '${r}'.`);return}if(typeof e!="function")throw new Error(`THREE.TSL: Node element ${r} is not a function`);df.set(r,e),r!=="assign"&&(Oe.prototype[r]=function(...t){return this.isStackNode?this.addToStack(e(...t)):e(this,...t)},Oe.prototype[r+"Assign"]=function(...t){return this.isStackNode?this.assign(t[0],e(...t)):this.assign(e(this,...t))})}const Ew=r=>r.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;n<t;n++)r[n]=Be(r[n],e);return r},m0=function(r,e=null,t=null,n=null){function i(u){return n!==null?(u=Be(Object.assign(u,n)),n.intent===!0&&(u=u.toVarIntent())):u=Be(u),u}let s,o=e,a,l;function c(u){let h;return o?h=/[a-z]/i.test(o)?o+"()":o:h=r.type,a!==void 0&&u.length<a?(ne(`TSL: "${h}" parameter length is less than minimum required.`,new jn),u.concat(new Array(a-u.length).fill(0))):l!==void 0&&u.length>l?(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;_<p.components.length;_++){const x=p.components[_];e.addLineFlowCode(`${m}.${x} = ${f}[ ${_} ]`,this)}t!=="void"&&(h=o)}else h=`${o} = ${l}`,(t==="void"||c==="void")&&(e.addLineFlowCode(h,this),t!=="void"&&(h=o));return u.initialized=!0,e.format(h,a,t)}}const Kw=Ft(Yw).setParameterLength(2);Y("assign",Kw);class Zw extends _n{static get type(){return"FunctionCallNode"}constructor(e=null,t={}){super(),this.functionNode=e,this.parameters=t}setParameters(e){return this.parameters=e,this}getParameters(){return this.parameters}generateNodeType(e){return this.functionNode.getNodeType(e)}getMemberType(e,t){return this.functionNode.getMemberType(e,t)}generate(e){const t=[],n=this.functionNode,i=n.getInputs(e),s=this.parameters,o=(l,c)=>{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<i.length)for(ne("TSL: The number of provided parameters is less than the expected number of inputs in 'Fn()'.");s.length<i.length;)s.push(j(0));for(let l=0;l<s.length;l++)t.push(o(s[l],i[l]))}else for(const l of i){const c=s[l.name];c!==void 0?t.push(o(c,l)):(ne(`TSL: Input '${l.name}' not found in 'Fn()'.`),t.push(o(j(0),l)))}return`${n.build(e,"property")}( ${t.join(", ")} )`}}const Qw=(r,...e)=>(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<i.length-1;o++)s=new nn(e,s,i[o]);t=s,n=i[i.length-1]}this.op=e,this.aNode=t,this.bNode=n,this.isOperatorNode=!0}getOperatorMethod(e,t){return e.getMethod(Jw[this.op],t)}generateNodeType(e,t=null){const n=this.op,i=this.aNode,s=this.bNode,o=i.getNodeType(e),a=s?s.getNodeType(e):null;if(o==="void"||a==="void")return t||"void";if(n==="%")return o;if(n==="~"||n==="&"||n==="|"||n==="^"||n===">>"||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;o<arguments.length-1;o++)s=new I(e,s,arguments[o]);t=s,n=arguments[arguments.length-1],i=null}this.method=e,this.aNode=t,this.bNode=n,this.cNode=i,this.isMathNode=!0}getInputType(e){const t=this.aNode.getNodeType(e),n=this.bNode?this.bNode.getNodeType(e):null,i=this.cNode?this.cNode.getNodeType(e):null,s=e.isMatrix(t)?0:e.getTypeLength(t),o=e.isMatrix(n)?0:e.getTypeLength(n),a=e.isMatrix(i)?0:e.getTypeLength(i);return s>o&&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;i<t.length;i++)n=n[t[i]];return n}updateReference(e){return this.reference=this.object!==null?this.object:e.object,this.reference}setup(){return this.updateValue(),this.node}update(){this.updateValue()}updateValue(){this.node===null&&this.setNodeType(this.uniformType);const e=this.getValueFromReference();Array.isArray(e)?this.node.array=e:this.node.value=e}}const gN=(r,e,t)=>new 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<e.length;t++){const n=e[t];(typeof n!="number"||n<=0||!Number.isInteger(n))&&ne(`TSL: compute() workgroupSize element at index [ ${t} ] must be a positive integer`,new jn)}for(;e.length<3;)e.push(1);return new MN(Be(r),e)},EN=(r,e,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;i<e.length;i++){const s=i*4;t[s]=e[i]}else if(n==="color")for(let i=0;i<e.length;i++){const s=i*4,o=e[i];t[s]=o.r,t[s+1]=o.g,t[s+2]=o.b||0}else if(n==="mat2")for(let i=0;i<e.length;i++){const s=i*4,o=e[i];t[s]=o.elements[0],t[s+1]=o.elements[1],t[s+2]=o.elements[2],t[s+3]=o.elements[3]}else if(n==="mat3")for(let i=0;i<e.length;i++){const s=i*16,o=e[i];t[s]=o.elements[0],t[s+1]=o.elements[1],t[s+2]=o.elements[2],t[s+4]=o.elements[3],t[s+5]=o.elements[4],t[s+6]=o.elements[5],t[s+8]=o.elements[6],t[s+9]=o.elements[7],t[s+10]=o.elements[8],t[s+15]=1}else if(n==="mat4")for(let i=0;i<e.length;i++){const s=i*16,o=e[i];for(let a=0;a<o.elements.length;a++)t[s+a]=o.elements[a]}else for(let i=0;i<e.length;i++){const s=i*4,o=e[i];t[s]=o.x,t[s+1]=o.y,t[s+2]=o.z||0,t[s+3]=o.w||0}}setup(e){const t=this.array.length,n=this.elementType;let i=Float32Array;const s=this.paddedType,o=e.getTypeLength(s);return n.charAt(0)==="i"&&(i=Int32Array),n.charAt(0)==="u"&&(i=Uint32Array),this.value=new i(t*o),this.bufferCount=t,this.bufferType=s,this.update(),super.setup(e)}element(e){return new zN(this,Be(e))}}const Ri=(r,e)=>new 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<i;n++)t.push(new C);Qc===null?Qc=Ri(t).setGroup(qe).setName("cameraPositions").onRenderUpdate(({camera:n},i)=>{const s=n.cameras,o=i.array;for(let a=0,l=s.length;a<l;a++)o[a].setFromMatrixPosition(s[a].matrixWorld)}):Qc.array=t,e=Qc.element(r.isMultiViewCamera?qa("gl_ViewID_OVR"):ah).toConst("cameraPosition")}else fd===null&&(fd=We(new C).setName("cameraPosition").setGroup(qe).onRenderUpdate(({camera:t},n)=>n.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;i<t.length;i++)n=n[t[i]];return n}updateReference(e){return this.reference=this.object!==null?this.object:e.object,this.reference}setup(){return this.updateValue(),this.node}update(){this.updateValue()}updateValue(){this.node===null&&this.setNodeType(this.uniformType);const e=this.getValueFromReference();Array.isArray(e)?this.node.array=e:this.node.value=e}}const Qt=(r,e,t)=>new 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;a<l;a++){const c=this.params[a],u=c.isNode!==!0&&c.name||this.getVarName(a),h=c.isNode!==!0&&c.type||"int";n[u]=hs(u,h)}const i=e.addStack(),s=this.params[this.params.length-1](n);t.returnsNode=s.context({nodeLoop:s}),t.stackNode=i;const o=this.params[0];if(o.isNode!==!0&&typeof o.update=="function"){const a=Q(this.params[0].update)(n);t.updateNode=a.context({nodeLoop:a})}return e.removeStack(),t}setup(e){if(this.getProperties(e),e.fnCall){const t=e.getDataFromNode(e.fnCall.shaderNode);t.hasLoop=!0}}generate(e){const t=this.getProperties(e),n=this.params,i=t.stackNode;for(let o=0,a=n.length-1;o<a;o++){const l=n[o];let c=!1,u=null,h=null,d=null,f=null,p=null,g=null;l.isNode?l.getNodeType(e)==="bool"?(c=!0,f="bool",h=l.build(e,f)):(f="int",d=this.getVarName(o),u="0",h=l.build(e,f),p="<"):(f=l.type||"int",d=l.name||this.getVarName(o),u=l.start,h=l.end,p=l.condition,g=l.update,typeof u=="number"?u=e.generateConst(f,u):u&&u.isNode&&(u=u.build(e,f)),typeof h=="number"?h=e.generateConst(f,h):h&&h.isNode&&(h=h.build(e,f)),u!==void 0&&h===void 0?(u=u+" - 1",h="0",p=">="):h!==void 0&&u===void 0&&(u="0",p="<"),p===void 0&&(Number(u)>Number(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;o<a;o++)e.addFlowCode((o===0?"":e.tab)+`}
|
|
|
|
`).removeFlowTab();e.addFlowTab()}}const wi=(...r)=>new 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<s;x++){const v=a[x],S=l[x],E=c[x],T=h*d*4*x;for(let A=0;A<v.count;A++){const y=A*m;e===!0&&(_i.fromBufferAttribute(v,A),p[T+y+0]=_i.x,p[T+y+1]=_i.y,p[T+y+2]=_i.z,p[T+y+3]=0),t===!0&&(_i.fromBufferAttribute(S,A),p[T+y+4]=_i.x,p[T+y+5]=_i.y,p[T+y+6]=_i.z,p[T+y+7]=0),n===!0&&(_i.fromBufferAttribute(E,A),p[T+y+8]=_i.x,p[T+y+9]=_i.y,p[T+y+10]=_i.z,p[T+y+11]=E.itemSize===4?_i.w:1)}}o={count:s,texture:g,stride:u,size:new de(h,d)},_d.set(r,o),r.addEventListener("dispose",_)}return o}class _P extends Oe{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=We(1),this.updateType=je.OBJECT}setup(e){const{geometry:t}=e,n=t.morphAttributes.position!==void 0,i=t.hasAttribute("normal")&&t.morphAttributes.normal!==void 0,s=t.morphAttributes.position||t.morphAttributes.normal||t.morphAttributes.color,o=s!==void 0?s.length:0,{texture:a,stride:l,size:c}=gP(t);n===!0&&bn.mulAssign(this.morphBaseInfluence),i===!0&&bs.mulAssign(this.morphBaseInfluence);const u=Kt(c.width);wi(o,({i:h})=>{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;e<this._lodMeshes.length;e++)this._lodMeshes[e].geometry.dispose()}_cleanup(e){this._renderer.setRenderTarget(Md,Ed,Ad),e.scissorTest=!1,this._setViewport(e,0,0,e.width,e.height)}_fromTexture(e,t){this._setSizeFromTexture(e),Md=this._renderer.getRenderTarget(),Ed=this._renderer.getActiveCubeFace(),Ad=this._renderer.getActiveMipmapLevel();const n=t||this._allocateTarget();return this._init(n),this._textureToCubeUV(e,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTarget(){const e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize;return u_(e,t)}_init(e){if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e.width||this._pingPongRenderTarget.height!==e.height){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=u_(e.width,e.height);const{_lodMax:t}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=OD(t)),this._blurMaterial=kD(t,e.width,e.height),this._ggxMaterial=GD(t,e.width,e.height)}}async _compileMaterial(e){const t=new gn(new Pn,e);await this._renderer.compile(t,hl)}_sceneToCubeUV(e,t,n,i,s){const o=UD;o.near=t,o.far=n;const a=[1,1,1,1,-1,1],l=[1,-1,1,-1,1,-1],c=this._renderer,u=c.autoClear;c.getClearColor(c_),c.autoClear=!1,this._backgroundBox===null&&(this._backgroundBox=new gn(new yo,new us({name:"PMREM.Background",side:Pt,depthWrite:!1,depthTest:!1})));const h=this._backgroundBox,d=h.material;let f=!1;const p=e.background;p?p.isColor&&(d.color.copy(p),e.background=null,f=!0):(d.color.copy(c_),f=!0),c.setRenderTarget(i),c.clear(),f&&c.render(h,o);for(let g=0;g<6;g++){const m=g%3;m===0?(o.up.set(0,a[g],0),o.position.set(s.x,s.y,s.z),o.lookAt(s.x+l[g],s.y,s.z)):m===1?(o.up.set(0,0,a[g]),o.position.set(s.x,s.y,s.z),o.lookAt(s.x,s.y+l[g],s.z)):(o.up.set(0,a[g],0),o.position.set(s.x,s.y,s.z),o.lookAt(s.x,s.y,s.z+l[g]));const _=this._cubeSize;this._setViewport(i,m*_,g>2?_: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;s<i;s++)this._applyGGXFilter(e,s-1,s);t.autoClear=n}_applyGGXFilter(e,t,n){const i=this._renderer,s=this._pingPongRenderTarget,o=this._ggxMaterial,a=this._lodMeshes[n];a.material=o;const l=Hu.get(o),c=n/(this._lodMeshes.length-1),u=t/(this._lodMeshes.length-1),h=Math.sqrt(c*c-u*u),d=0+c*1.25,f=h*d,{_lodMax:p}=this,g=this._sizeLods[n],m=3*g*(n>p-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;A<Qr;++A){const y=A/g,R=Math.exp(-y*y/2);_.push(R),A===0?x+=R:A<m&&(x+=2*R)}for(let A=0;A<_.length;A++)_[A]=_[A]/x;e.texture.frame=(e.texture.frame||0)+1,d.envMap.value=e.texture,d.samples.value=m,d.weights.array=_,d.latitudinal.value=o==="latitudinal"?1:0,a&&(d.poleAxis.value=a);const{_lodMax:v}=this;d.dTheta.value=p,d.mipInt.value=v-n;const S=this._sizeLods[i],E=3*S*(i>v-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;o<s;o++){const a=Math.pow(2,i);e.push(a);let l=1/a;o>r-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;T<f;T++){const A=T%3*2/3-1,y=T>2?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;n<t;n++)r[n]!==void 0&&e++;return e===t}function XD(r){return r==null?!1:r.height>0}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<e.length-1;n++)if(t=t.get(e[n]),t===void 0)return;return t.get(e[e.length-1])}set(e,t){let n=this._getWeakMap(e);for(let i=0;i<e.length-1;i++){const s=e[i];n.has(s)===!1&&n.set(s,new WeakMap),n=n.get(s)}return n.set(e[e.length-1],t),this}delete(e){let t=this._getWeakMap(e);for(let n=0;n<e.length-1;n++)if(t=t.get(e[n]),t===void 0)return!1;return t.delete(e[e.length-1])}}let mL=0;function gL(r){const e=Object.keys(r);let t=Object.getPrototypeOf(r);for(;t;){const n=Object.getOwnPropertyDescriptors(t);for(const i in n)if(n[i]!==void 0){const s=n[i];s&&typeof s.get=="function"&&e.push(i)}t=Object.getPrototypeOf(t)}return e}class _L{constructor(e,t,n,i,s,o,a,l,c,u){this.id=mL++,this._nodes=e,this._geometries=t,this.renderer=n,this.object=i,this.material=s,this.scene=o,this.camera=a,this.lightsNode=l,this.context=c,this.geometry=i.geometry,this.version=s.version,this.drawRange=null,this.attributes=null,this.attributesId=null,this.pipeline=null,this.group=null,this.vertexBuffers=null,this.drawParams=null,this.bundle=null,this.clippingContext=u,this.clippingContextCacheKey=u!==null?u.cacheKey:"",this.initialNodesCacheKey=this.getDynamicCacheKey(),this.initialCacheKey=this.getCacheKey(),this._nodeBuilderState=null,this._bindings=null,this._monitor=null,this.onDispose=null,this.isRenderObject=!0,this.onMaterialDispose=()=>{this.dispose()},this.onGeometryDispose=()=>{this.attributes=null,this.attributesId=null},this.material.addEventListener("dispose",this.onMaterialDispose),this.geometry.addEventListener("dispose",this.onGeometryDispose)}updateClipping(e){this.clippingContext=e}get clippingNeedsUpdate(){return 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;s<o;s++){const a=i[s];t+=a.id+","}}return e.index&&(t+="index,"),t}getMaterialCacheKey(){const{object:e,material:t,renderer:n}=this;let i=t.customProgramCacheKey();for(const s of gL(t)){if(/^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test(s))continue;const o=t[s];let a;if(o!==null){const l=typeof o;l==="number"?a=o!==0?"1":"0":l==="object"?(a="{",o.isTexture&&(a+=o.mapping,n.backend.isWebGPUBackend===!0&&(a+=o.magFilter,a+=o.minFilter,a+=o.wrapS,a+=o.wrapT,a+=o.wrapR)),a+="}"):a=String(o)}else a=String(o);i+=a+","}return i+=this.clippingContextCacheKey+",",e.geometry&&(i+=this.getGeometryCacheKey()),e.skeleton&&(i+=e.skeleton.bones.length+","),e.isBatchedMesh&&(i+=e._matricesTexture.uuid+",",e._colorsTexture!==null&&(i+=e._colorsTexture.uuid+",")),(e.isInstancedMesh||e.count>1||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<i.version||i.usage===Nu)&&(this.backend.updateAttribute(e),n.version=i.version)}}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}function ky(r){return r.index!==null?r.index.version:r.attributes.position.version}function Gy(r){return r.index!==null?r.index.id:r.attributes.position.id}function g_(r){const e=[],t=r.index,n=r.attributes.position;if(t!==null){const s=t.array;for(let o=0,a=s.length;o<a;o+=3){const l=s[o+0],c=s[o+1],u=s[o+2];e.push(l,c,c,u,u,l)}}else{const s=n.array;for(let o=0,a=s.length/3-1;o<a;o+=3){const l=o+0,c=o+1,u=o+2;e.push(l,c,c,u,u,l)}}const i=new(n.count>=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<c.length;h++){const d=c[h];if(d.data)u+=d.data.byteLength;else{const f=d.width||Math.max(1,s>>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;e++){const n=this.renderItems[e];if(n.id===null)break;n.id=null,n.object=null,n.geometry=null,n.material=null,n.groupOrder=null,n.renderOrder=null,n.z=null,n.group=null,n.clippingContext=null}}}const Go=[];class PL{constructor(e){this.lighting=e,this.lists=new Pr}get(e,t){const n=this.lists;Go[0]=e,Go[1]=t;let i=n.get(Go);return i===void 0&&(i=new NL(this.lighting,e,t),n.set(Go,i)),Go[0]=null,Go[1]=null,i}dispose(){this.lists=new Pr}}let DL=0;class LL{constructor(){this.id=DL++,this.mrt=null,this.color=!0,this.clearColor=!0,this.clearColorValue={r:0,g:0,b:0,a:1},this.depth=!0,this.clearDepth=!0,this.clearDepthValue=1,this.stencil=!1,this.clearStencil=!0,this.clearStencilValue=1,this.viewport=!1,this.viewportValue=new tt,this.scissor=!1,this.scissorValue=new tt,this.renderTarget=null,this.textures=null,this.depthTexture=null,this.activeCubeFace=0,this.activeMipmapLevel=0,this.sampleCount=1,this.width=0,this.height=0,this.occlusionQueryCount=0,this.clippingContext=null,this.camera=null,this.isRenderContext=!0}getCacheKey(){return zy(this)}}function zy(r){const{textures:e,activeCubeFace:t,activeMipmapLevel:n}=r,i=[t,n];for(const s of e)i.push(s.id);return dc(i)}class UL{constructor(e){this.renderer=e,this._renderContexts={}}get(e=null,t=null,n=0){let i;if(e===null)i="default";else{const l=e.texture.format,c=e.texture.type;i=`${e.textures.length}:${l}:${c}:${e.samples}:${e.depthBuffer}:${e.stencilBuffer}`}const s=t!==null?t.id:"default",o=i+"-"+s+"-"+n;let a=this._renderContexts[o];return a===void 0&&(a=new LL,a.mrt=t,this._renderContexts[o]=a),e!==null&&(a.sampleCount=e.samples===0?1:e.samples),a.clearDepthValue=this.renderer.getClearDepth(),a.clearStencilValue=this.renderer.getClearStencil(),a}dispose(){this._renderContexts={}}}const FL=new C;class IL extends Ur{constructor(e,t,n){super(),this.renderer=e,this.backend=t,this.info=n,this._htmlTextures=new Set}updateRenderTarget(e,t=0){const n=this.get(e),i=e.samples===0?1:e.samples,s=n.depthTextureMips||(n.depthTextureMips={}),o=e.textures,a=this.getSize(o[0]),l=a.width>>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<o.length;p++){const g=o[p];d&&(g.needsUpdate=!0),this.updateTexture(g,f)}u&&this.updateTexture(u,f)}n.initialized!==!0&&(n.initialized=!0,this.info.memory.renderTargets++,n.onDispose=()=>{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<n.length;s++)this._destroyTexture(n[s]);i&&this._destroyTexture(i),this.delete(e),this.backend.delete(e),this.info.memory.renderTargets--}}_destroyTexture(e){if(this.has(e)===!0){const t=this.get(e);e.removeEventListener("dispose",t.onDispose);const n=t.isDefaultTexture;if(this.backend.destroyTexture(e,n),t.bindGroups)for(const i of t.bindGroups){const s=this.backend.get(i);s.groups=void 0,s.versions=void 0}this._htmlTextures.delete(e),this.delete(e),this.info.destroyTexture(e)}}}class zp extends Ve{constructor(e,t,n,i=1){super(e,t,n),this.a=i}set(e,t,n,i=1){return this.a=i,super.set(e,t,n)}copy(e){return e.a!==void 0&&(this.a=e.a),super.copy(e)}clone(){return new this.constructor(this.r,this.g,this.b,this.a)}}class BL extends Tt{static get type(){return"ParameterNode"}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getMemberType(e,t){const n=this.getNodeType(e),i=e.getStructTypeNode(n);let s;return i!==null?s=i.getMemberType(e,t):(ne(`TSL: Member "${t}" not found in struct "${n}".`,new jn),s="float"),s}getHash(){return String(this.id)}generate(){return this.name}}class OL extends Oe{static get type(){return"StackNode"}constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this._expressionNode=null,this._currentNode=null,this.isStackNode=!0}getElementType(e){return this.hasOutput(e)?this.outputNode.getElementType(e):"void"}generateNodeType(e){return this.hasOutput(e)?this.outputNode.getNodeType(e):"void"}getMemberType(e,t){return this.hasOutput(e)?this.outputNode.getMemberType(e,t):"void"}addToStack(e,t=this.nodes.length){return e.isNode!==!0?(ne("TSL: Invalid node added to stack.",new jn),this):(this.nodes.splice(t,0,e),this)}addToStackBefore(e){const t=this._currentNode?this.nodes.indexOf(this._currentNode):0;return this.addToStack(e,t)}If(e,t){const n=new xl(t);return this._currentCond=Si(e,n),this.addToStack(this._currentCond)}ElseIf(e,t){const n=new xl(t),i=Si(e,n);return this._currentCond.elseNode=i,this._currentCond=i,this}Else(e){return this._currentCond.elseNode=new xl(e),this}Switch(e){return this._expressionNode=Be(e),this}Case(...e){const t=[];if(e.length>=2)for(let a=0;a<e.length-1;a++)t.push(this._expressionNode.equal(Be(e[a])));else ne("TSL: Invalid parameter length. Case() requires at least two parameters.",new jn);const n=e[e.length-1],i=new xl(n);let s=t[0];for(let a=1;a<t.length;a++)s=s.or(t[a]);const o=Si(s,i);return this._currentCond===null?(this._currentCond=o,this.addToStack(this._currentCond)):(this._currentCond.elseNode=o,this._currentCond=o,this)}Default(e){return this.Else(e),this}setup(e){const t=e.getNodeProperties(this);let n=0;for(const i of this.getChildren())i.isVarNode&&i.isIntent(e)&&i.isAssign(e)!==!0||(t["node"+n++]=i);return t.outputNode||null}hasOutput(e){return this.outputNode&&this.outputNode.isNode&&this.outputNode.getNodeType(e)!=="void"}build(e,...t){const n=_0(),i=e.buildStage;Ou(this),e.setActiveStack(this);const s=c=>{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;u<n;u++){const h=c[u];l[h].assign(i(a[h]))}return l}}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}setup(e){const{method:t,aNode:n}=this,{renderer:i}=e;if(i.backend.isWebGPUBackend)return super.setup(e);const s=this.getInputType(e),o=e.getElementType(s),a=e.getTypeLength(s),l=`${t}_base_${o}`,c=`${t}_${s}`;let u=su[l];if(u===void 0){switch(t){case io.COUNT_LEADING_ZEROS:{u=this._createLeadingZerosBaseLayout(l,o);break}case io.COUNT_TRAILING_ZEROS:{u=this._createTrailingZerosBaseLayout(l,o);break}case io.COUNT_ONE_BITS:{u=this._createOneBitsBaseLayout(l,o);break}}su[l]=u}let h=su[c];return h===void 0&&(h=this._createMainLayout(c,s,a,u),su[c]=h),Q(()=>h(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;n<e.length;n++){const i=e[n];if(dl.push(i.id),dl.push(i.castShadow?1:0),i.isSpotLight===!0){const s=i.map!==null?i.map.id:-1,o=i.colorNode?i.colorNode.getCacheKey():-1;dl.push(s,o)}}const t=dc(dl);return dl.length=0,t}getHash(e){if(this._lightNodesHash===null){this._lightNodes===null&&this.setupLightsNode(e);const t=[];for(const n of this._lightNodes)t.push(n.getHash());this._lightNodesHash="lights-"+t.join(",")}return this._lightNodesHash}analyze(e){const t=e.getNodeProperties(this);for(const n of t.nodes)n.build(e);t.outputNode.build(e)}setupLightsNode(e){const t=[],n=this._lightNodes,i=cU(this._lights),s=e.renderer.library;for(const o of i)if(o.isNode)t.push(Be(o));else{let a=null;if(n!==null&&(a=uU(o.id,n)),a===null){const l=s.getLightNodeClass(o.constructor);if(l===null){ee(`LightsNode.setupNodeLights: Light node not found for ${o.constructor.name}`);continue}Dd.has(o)===!1&&Dd.set(o,new l(o)),a=Dd.get(o)}t.push(a)}this._lightNodes=t}setupDirectLight(e,t,n){const{lightingModel:i,reflectedLight:s}=e.context;i.direct({...n,lightNode:t,reflectedLight:s},e)}setupDirectRectAreaLight(e,t,n){const{lightingModel:i,reflectedLight:s}=e.context;i.directRectArea({...n,lightNode:t,reflectedLight:s},e)}setupLights(e,t){for(const n of t)n.build(e)}getLightNodes(e){return this._lightNodes===null&&this.setupLightsNode(e),this._lightNodes}setup(e){const t=e.lightsNode;e.lightsNode=this;let n=this.outgoingLightNode;const i=e.context,s=i.lightingModel,o=e.getNodeProperties(this);if(s){const{totalDiffuseNode:a,totalSpecularNode:l}=this;i.outgoingLight=n;const c=e.addStack();o.nodes=c.nodes,s.start(e);const{backdrop:u,backdropAlpha:h}=i,{directDiffuse:d,directSpecular:f,indirectDiffuse:p,indirectSpecular:g}=i.reflectedLight;let m=d.add(p);u!==null&&(h!==null?m=K(h.mix(m,u)):m=K(u)),a.assign(m),l.assign(f.add(g)),n.assign(a.add(l)),s.finish(e),n=n.bypass(e.removeStack())}else o.nodes=[];return e.lightsNode=t,n}setLights(e){return this._lights=e,this._lightNodes=null,this._lightNodesHash=null,this}getLights(){return this._lights}get hasLights(){return this._lights.length>0}}class 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;o<t.length;o++)n!==t[o].groupNode&&(i=!1);let s;if(i){let o="";for(const u of t)if(u.isNodeUniformsGroup){u.uniforms.sort((h,d)=>h.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<e.length;t++){const n=e[t];this.bindingsIndexes[n.name].group=t}}setHashNode(e,t){this.hashNodes[t]=e}addNode(e){this.nodes.includes(e)===!1&&(this.nodes.push(e),this.setHashNode(e,e.getHash(this)))}addSequentialNode(e){const t=e.getUpdateBeforeType(),n=e.getUpdateAfterType();(t!==je.NONE||n!==je.NONE)&&this.sequentialNodes.includes(e)===!1&&this.sequentialNodes.push(e)}buildUpdateNodes(){for(const e of this.nodes)e.getUpdateType()!==je.NONE&&this.updateNodes.push(e);for(const e of this.sequentialNodes){const t=e.getUpdateBeforeType(),n=e.getUpdateAfterType();t!==je.NONE&&this.updateBeforeNodes.push(e),n!==je.NONE&&this.updateAfterNodes.push(e)}}get currentNode(){return this.chaining[this.chaining.length-1]}isFilteredTexture(e){return e.magFilter===Ut||e.magFilter===Qo||e.magFilter===Gs||e.magFilter===li||e.minFilter===Ut||e.minFilter===Qo||e.minFilter===Gs||e.minFilter===li}getUniformBufferLimit(){return this.renderer.backend.capabilities.getUniformBufferLimit()}addChain(e){this.chaining.push(e)}removeChain(e){if(this.chaining.pop()!==e)throw new Error("NodeBuilder: Invalid node chaining!")}getMethod(e){return e}getTernary(){return null}getNodeFromHash(e){return this.hashNodes[e]}addFlow(e,t){return this.flowNodes[e].push(t),t}setContext(e){this.context=e}getContext(){return this.context}addContext(e){const t=this.getContext();return this.setContext({...this.context,...e}),t}getSharedContext(){const e={...this.context};return delete e.material,delete e.getUV,delete e.getOutput,delete e.getTextureLevel,delete e.getAO,delete e.getShadow,e}setCache(e){this.cache=e}getCache(){return this.cache}getCacheFromNode(e,t=!0){const n=this.getDataFromNode(e);return n.cache===void 0&&(n.cache=new Fd(t?this.getCache():null)),n.cache}isAvailable(){return!1}getVertexIndex(){ee("Abstract function.")}getInstanceIndex(){ee("Abstract function.")}getDrawIndex(){ee("Abstract function.")}getFrontFacing(){ee("Abstract function.")}getFragCoord(){ee("Abstract function.")}isFlipY(){return!1}increaseUsage(e){const t=this.getDataFromNode(e);return t.usageCount=t.usageCount===void 0?1:t.usageCount+1,t.usageCount}generateTexture(){ee("Abstract function.")}generateTextureLod(){ee("Abstract function.")}generateArrayDeclaration(e,t){return this.getType(e)+"[ "+t+" ]"}generateArray(e,t,n=null){let i=this.generateArrayDeclaration(e,t)+"( ";for(let s=0;s<t;s++){const o=n?n[s]:null;o!==null?i+=o.build(this,e):i+=this.generateConst(e),s<t-1&&(i+=", ")}return i+=" )",i}generateStruct(e,t,n=null){const i=[];for(const s of t){const{name:o,type:a}=s;n&&n[o]&&n[o].isNode?i.push(n[o].build(this,a)):i.push(this.generateConst(a))}return e+"( "+i.join(", ")+" )"}generateConst(e,t=null){if(t===null&&(e==="float"||e==="int"||e==="uint"?t=0:e==="bool"?t=!1:e==="color"?t=new Ve:e==="vec2"||e==="uvec2"||e==="ivec2"?t=new de:e==="vec3"||e==="uvec3"||e==="ivec3"?t=new C:(e==="vec4"||e==="uvec4"||e==="ivec4")&&(t=new tt)),e==="float")return lu(t);if(e==="int")return`${Math.round(t)}`;if(e==="uint")return 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<s.length;){const p=s[l][0]==="const";p===!0&&l++;let g=s[l][0];g==="in"||g==="out"||g==="inout"?l++:g="";const m=s[l++][0];let _=Number.parseInt(s[l][0]);Number.isNaN(_)===!1?l++:_=null;const x=s[l++][0];a.push(new $p(m,x,_,g,p))}const c=t.substring(n[0].length),u=n[3]!==void 0?n[3]:"",h=n[2],d=n[1]!==void 0?n[1]:"",f=e!==-1?r.slice(0,e):"";return{type:h,inputs:a,name:u,precision:d,inputsCode:i,blockCode:c,headerCode:f}}else throw new Error("FunctionNode: Function is not a GLSL code.")};class wF extends qp{constructor(e){const{type:t,inputs:n,name:i,precision:s,inputsCode:o,blockCode:a,headerCode:l}=RF(e);super(t,n,i,s),this.inputsCode=o,this.blockCode=a,this.headerCode=l}getCode(e=this.name){let t;const n=this.blockCode;if(n!==""){const{type:i,inputsCode:s,headerCode:o,precision:a}=this;let l=`${i} ${e} ( ${s.trim()} )`;a!==""&&(l=`${a} ${l}`),t=o+l+n}else t="";return t}}class CF extends tv{parseFunction(e){return new wF(e)}}const Mi=[],rr=[];class NF extends Ur{constructor(e,t){super(),this.renderer=e,this.backend=t,this.nodeFrame=new A_,this.nodeBuilderCache=new Map,this.callHashCache=new Pr,this.groupsData=new Pr,this._buildQueue=[],this._buildInProgress=!1,this.cacheLib={}}updateGroup(e){const t=e.groupNode;Mi[0]=t,Mi[1]=e;let n=this.groupsData.get(Mi);return n===void 0&&this.groupsData.set(Mi,n={}),Mi[0]=null,Mi[1]=null,n.version!==t.version?(n.version=t.version,!0):!1}getForRenderCacheKey(e){return e.initialCacheKey}_createNodeBuilder(e,t){const n=this.backend.createNodeBuilder(e.object,this.renderer);return n.scene=e.scene,n.material=t,n.camera=e.camera,n.context.material=t,n.lightsNode=e.lightsNode,n.environmentNode=this.getEnvironmentNode(e.scene),n.fogNode=this.getFogNode(e.scene),n.clippingContext=e.clippingContext,this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview&&n.enableMultiview(),n}getForRender(e,t=!1){const n=this.get(e);let i=n.nodeBuilderState;if(i===void 0){const{nodeBuilderCache:s}=this,o=this.getForRenderCacheKey(e);if(i=s.get(o),i===void 0){const a=async()=>{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;s<i;s++){Bd.copy(e[s]).applyMatrix4(this.viewMatrix,this.viewNormalMatrix);const o=t[n+s],a=Bd.normal;o.x=-a.x,o.y=-a.y,o.z=-a.z,o.w=Bd.constant}}updateGlobal(e,t){this.shadowPass=e.overrideMaterial!==null&&e.overrideMaterial.isShadowPassMaterial,this.viewMatrix=t.matrixWorldInverse,this.viewNormalMatrix.getNormalMatrix(this.viewMatrix)}update(e,t){let n=!1;e.version!==this.parentVersion&&(this.intersectionPlanes=Array.from(e.intersectionPlanes),this.unionPlanes=Array.from(e.unionPlanes),this.parentVersion=e.version),this.clipIntersection!==t.clipIntersection&&(this.clipIntersection=t.clipIntersection,this.clipIntersection?this.unionPlanes.length=e.unionPlanes.length:this.intersectionPlanes.length=e.intersectionPlanes.length);const i=t.clippingPlanes,s=i.length;let o,a;if(this.clipIntersection?(o=this.intersectionPlanes,a=e.intersectionPlanes.length):(o=this.unionPlanes,a=e.unionPlanes.length),o.length!==a+s){o.length=a+s;for(let l=0;l<s;l++)o[a+l]=new tt;n=!0}this.projectPlanes(i,o,a),n&&(this.version++,this.cacheKey=`${this.intersectionPlanes.length}:${this.unionPlanes.length}`)}getGroupContext(e){if(this.shadowPass&&!e.clipShadows)return this;let t=this.clippingGroupContexts.get(e);return t===void 0&&(t=new $u(this),this.clippingGroupContexts.set(e,t)),t.update(this,e),t}get unionClippingCount(){return this.unionPlanes.length}}class PF{constructor(e,t,n){this.bundleGroup=e,this.camera=t,this.renderContext=n}}const or=[];class DF{constructor(){this.bundles=new Pr}get(e,t,n){const i=this.bundles;or[0]=e,or[1]=t,or[2]=n;let s=i.get(or);return s===void 0&&(s=new PF(e,t,n),i.set(or,s)),or[0]=null,or[1]=null,or[2]=null,s}dispose(){this.bundles=new Pr}}class nv{constructor(){this.lightNodes=new WeakMap,this.materialNodes=new Map,this.toneMappingNodes=new Map}fromMaterial(e){if(e.isNodeMaterial)return e;let t=null;const n=this.getMaterialNodeClass(e.type);if(n!==null){t=new n;for(const i in e)t[i]=e[i]}return t}addToneMapping(e,t){this.addType(e,t,this.toneMappingNodes)}getToneMappingFunction(e){return this.toneMappingNodes.get(e)||null}getMaterialNodeClass(e){return this.materialNodes.get(e)||null}addMaterial(e,t){this.addType(e,t,this.materialNodes)}getLightNodeClass(e){return this.lightNodes.get(e)||null}addLight(e,t){this.addClass(e,t,this.lightNodes)}addType(e,t,n){if(n.has(t)){ee(`Redefinition of node ${t}`);return}if(typeof e!="function")throw new Error(`Node class ${e.name} is not a class.`);if(typeof t=="function"||typeof t=="object")throw new Error(`Base class ${t} is not a class.`);n.set(t,e)}addClass(e,t,n){if(n.has(t)){ee(`Redefinition of node ${t.name}`);return}if(typeof e!="function")throw new Error(`Node class ${e.name} is not a class.`);if(typeof t!="function")throw new Error(`Base class ${t.name} is not a class.`);n.set(t,e)}}const LF=new Yy,w_=new WeakMap;class UF{createNode(e=[]){return new Yy().setLights(e)}getNode(e){if(e.isQuadMesh)return LF;let t=w_.get(e);return t===void 0&&(t=this.createNode(),w_.set(e,t)),t}}class vl extends Lr{constructor(e=1,t=1,n={}){super(e,t,n),this.isXRRenderTarget=!0,this._hasExternalTextures=!1,this._autoAllocateDepthBuffer=!0,this._isOpaqueFramebuffer=!1}copy(e){return super.copy(e),this._hasExternalTextures=e._hasExternalTextures,this._autoAllocateDepthBuffer=e._autoAllocateDepthBuffer,this._isOpaqueFramebuffer=e._isOpaqueFramebuffer,this}}const C_=new C,N_=new C,P_=new WeakMap;class FF extends Ii{constructor(e,t=!1){super(),this.enabled=!1,this.isPresenting=!1,this.cameraAutoUpdate=!0,this._renderer=e,this._cameraL=new Rn,this._cameraL.viewport=new tt,this._cameraR=new Rn,this._cameraR.viewport=new tt,this._cameras=[this._cameraL,this._cameraR],this._cameraXR=new Gx,this._currentDepthNear=null,this._currentDepthFar=null,this._controllers=[],this._controllerInputSources=[],this._xrRenderTarget=null,this._layers=[],this._sessionUsesLayers=!1,this._supportsGlBinding=typeof XRWebGLBinding<"u",this._createXRLayer=VF.bind(this),this._gl=null,this._currentAnimationContext=null,this._currentAnimationLoop=null,this._currentPixelRatio=null,this._currentSize=new de,this._onSessionEvent=OF.bind(this),this._onSessionEnd=kF.bind(this),this._onInputSourcesChange=GF.bind(this),this._onAnimationFrame=zF.bind(this),this._referenceSpace=null,this._referenceSpaceType="local-floor",this._customReferenceSpace=null,this._framebufferScaleFactor=1,this._foveation=1,this._session=null,this._glBaseLayer=null,this._glBinding=null,this._glProjLayer=null,this._xrFrame=null,this._supportsLayers=this._supportsGlBinding&&"createProjectionLayer"in XRWebGLBinding.prototype,this._useMultiviewIfPossible=t,this._useMultiview=!1}getController(e){return this._getController(e).getTargetRaySpace()}getControllerGrip(e){return this._getController(e).getGripSpace()}getHand(e){return this._getController(e).getHandSpace()}getFoveation(){if(!(this._glProjLayer===null&&this._glBaseLayer===null))return this._foveation}setFoveation(e){this._foveation=e,this._glProjLayer!==null&&(this._glProjLayer.fixedFoveation=e),this._glBaseLayer!==null&&this._glBaseLayer.fixedFoveation!==void 0&&(this._glBaseLayer.fixedFoveation=e)}getFramebufferScaleFactor(){return this._framebufferScaleFactor}setFramebufferScaleFactor(e){this._framebufferScaleFactor=e,this.isPresenting===!0&&ee("XRManager: Cannot change framebuffer scale while presenting.")}getReferenceSpaceType(){return this._referenceSpaceType}setReferenceSpaceType(e){this._referenceSpaceType=e,this.isPresenting===!0&&ee("XRManager: Cannot change reference space type while presenting.")}getReferenceSpace(){return this._customReferenceSpace||this._referenceSpace}setReferenceSpace(e){this._customReferenceSpace=e}getCamera(){return this._cameraXR}getEnvironmentBlendMode(){if(this._session!==null)return this._session.environmentBlendMode}getBinding(){return this._glBinding===null&&this._supportsGlBinding&&(this._glBinding=new XRWebGLBinding(this._session,this._gl)),this._glBinding}getFrame(){return this._xrFrame}useMultiview(){return this._useMultiview}createQuadLayer(e,t,n,i,s,o,a,l={}){const c=new uc(e,t),u=new vl(s,o,{format:an,type:$t,depthTexture:new Xn(s,o,l.stencil?ui:wt,void 0,void 0,void 0,void 0,void 0,void 0,l.stencil?$n:Nn),stencilBuffer:l.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});u._autoAllocateDepthBuffer=!0;const h=new us({color:16777215,side:ni});h.map=u.texture,h.map.offset.y=1,h.map.repeat.y=-1;const d=new gn(c,h);d.position.copy(n),d.quaternion.copy(i);const f={type:"quad",width:e,height:t,translation:n,quaternion:i,pixelwidth:s,pixelheight:o,plane:d,material:h,rendercall:a,renderTarget:u};if(this._layers.push(f),this._session!==null){f.plane.material=new us({color:16777215,side:ni}),f.plane.material.blending=Jr,f.plane.material.blendEquation=Wn,f.plane.material.blendSrc=Us,f.plane.material.blendDst=Us,f.xrlayer=this._createXRLayer(f);const p=this._session.renderState.layers;p.unshift(f.xrlayer),this._session.updateRenderState({layers:p})}else u.isXRRenderTarget=!1;return d}createCylinderLayer(e,t,n,i,s,o,a,l,c={}){const u=new cc(e,e,e*t/n,64,64,!0,Math.PI-t/2,t),h=new vl(o,a,{format:an,type:$t,depthTexture:new Xn(o,a,c.stencil?ui:wt,void 0,void 0,void 0,void 0,void 0,void 0,c.stencil?$n:Nn),stencilBuffer:c.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});h._autoAllocateDepthBuffer=!0;const d=new us({color:16777215,side:Pt});d.map=h.texture,d.map.offset.y=1,d.map.repeat.y=-1;const f=new gn(u,d);f.position.copy(i),f.quaternion.copy(s);const p={type:"cylinder",radius:e,centralAngle:t,aspectratio:n,translation:i,quaternion:s,pixelwidth:o,pixelheight:a,plane:f,material:d,rendercall:l,renderTarget:h};if(this._layers.push(p),this._session!==null){p.plane.material=new us({color:16777215,side:Pt}),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);const g=this._session.renderState.layers;g.unshift(p.xrlayer),this._session.updateRenderState({layers:g})}else h.isXRRenderTarget=!1;return f}renderLayers(){const e=new C,t=new Li,n=this._renderer,i=this.isPresenting;this.isPresenting=!1;const s=new de;n.getSize(s);const o=n.getRenderTarget();for(const a of this._layers){a.renderTarget.isXRRenderTarget=this._session!==null,a.renderTarget._hasExternalTextures=a.renderTarget.isXRRenderTarget;const l=n.contextNode;let c;if(a.renderTarget.isXRRenderTarget&&this._sessionUsesLayers){a.xrlayer.transform=new XRRigidTransform(a.plane.getWorldPosition(e),a.plane.getWorldQuaternion(t));const u=this._glBinding.getSubImage(a.xrlayer,this._xrFrame);n.backend.setXRRenderTargetTextures(a.renderTarget,u.colorTexture,void 0),n._setXRLayerSize(a.renderTarget.width,a.renderTarget.height),c=P_.get(l),c===void 0&&(c=l.context({getOutput:h=>j0(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<c.length;u++)D_(c[u],l);c.length===2?IF(s,o,a):s.projectionMatrix.copy(o.projectionMatrix),BF(e,s,l)}_getController(e){let t=this._controllers[e];return t===void 0&&(t=new Su,this._controllers[e]=t),t}}function IF(r,e,t){C_.setFromMatrixPosition(e.matrixWorld),N_.setFromMatrixPosition(t.matrixWorld);const n=C_.distanceTo(N_),i=e.projectionMatrix.elements,s=t.projectionMatrix.elements,o=i[14]/(i[10]-1),a=i[14]/(i[10]+1),l=(i[9]+1)/i[5],c=(i[9]-1)/i[5],u=(i[8]-1)/i[0],h=(s[8]+1)/s[0],d=o*u,f=o*h,p=n/(-u+h),g=p*-u;if(e.matrixWorld.decompose(r.position,r.quaternion,r.scale),r.translateX(g),r.translateZ(p),r.matrixWorld.compose(r.position,r.quaternion,r.scale),r.matrixWorldInverse.copy(r.matrixWorld).invert(),i[10]===-1)r.projectionMatrix.copy(e.projectionMatrix),r.projectionMatrixInverse.copy(e.projectionMatrixInverse);else{const m=o+p,_=a+p,x=d-g,v=f+(n-g),S=l*a/_*m,E=c*a/_*m;r.projectionMatrix.makePerspective(x,v,S,E,m,_),r.projectionMatrixInverse.copy(r.projectionMatrix).invert()}}function D_(r,e){e===null?r.matrixWorld.copy(r.matrix):r.matrixWorld.multiplyMatrices(e.matrixWorld,r.matrix),r.matrixWorldInverse.copy(r.matrixWorld).invert()}function BF(r,e,t){t===null?r.matrix.copy(e.matrixWorld):(r.matrix.copy(t.matrixWorld),r.matrix.invert(),r.matrix.multiply(e.matrixWorld)),r.matrix.decompose(r.position,r.quaternion,r.scale),r.updateMatrixWorld(!0),r.projectionMatrix.copy(e.projectionMatrix),r.projectionMatrixInverse.copy(e.projectionMatrixInverse),r.isPerspectiveCamera&&(r.fov=ao*2*Math.atan(1/r.projectionMatrix.elements[5]),r.zoom=1)}function OF(r){const e=this._controllerInputSources.indexOf(r.inputSource);if(e===-1)return;const t=this._controllers[e];if(t!==void 0){const n=this.getReferenceSpace();t.update(r.inputSource,r.frame,n),t.dispatchEvent({type:r.type,data:r.inputSource})}}function kF(){const r=this._session,e=this._renderer;r.removeEventListener("select",this._onSessionEvent),r.removeEventListener("selectstart",this._onSessionEvent),r.removeEventListener("selectend",this._onSessionEvent),r.removeEventListener("squeeze",this._onSessionEvent),r.removeEventListener("squeezestart",this._onSessionEvent),r.removeEventListener("squeezeend",this._onSessionEvent),r.removeEventListener("end",this._onSessionEnd),r.removeEventListener("inputsourceschange",this._onInputSourcesChange);for(let t=0;t<this._controllers.length;t++){const n=this._controllerInputSources[t];n!==null&&(this._controllerInputSources[t]=null,this._controllers[t].disconnect(n))}if(this._currentDepthNear=null,this._currentDepthFar=null,e._resetXRState(),this._session=null,this._xrRenderTarget=null,this._glBinding=null,this._glBaseLayer=null,this._glProjLayer=null,this._sessionUsesLayers===!0)for(const t of this._layers)t.renderTarget=new vl(t.pixelwidth,t.pixelheight,{format:an,type:$t,depthTexture:new Xn(t.pixelwidth,t.pixelheight,t.stencilBuffer?ui:wt,void 0,void 0,void 0,void 0,void 0,void 0,t.stencilBuffer?$n:Nn),stencilBuffer:t.stencilBuffer,resolveDepthBuffer:!1,resolveStencilBuffer:!1}),t.renderTarget.isXRRenderTarget=!1,t.plane.material=t.material,t.material.map=t.renderTarget.texture,t.material.map.offset.y=1,t.material.map.repeat.y=-1,delete t.xrlayer;this.isPresenting=!1,this._useMultiview=!1,e._animation.stop(),e._animation.setAnimationLoop(this._currentAnimationLoop),e._animation.setContext(this._currentAnimationContext),e._animation.start(),e.setPixelRatio(this._currentPixelRatio),e.setSize(this._currentSize.width,this._currentSize.height,!1),this.dispatchEvent({type:"sessionend"})}function GF(r){const e=this._controllers,t=this._controllerInputSources;for(let n=0;n<r.removed.length;n++){const i=r.removed[n],s=t.indexOf(i);s>=0&&(t[s]=null,e[s].disconnect(i))}for(let n=0;n<r.added.length;n++){const i=r.added[n];let s=t.indexOf(i);if(s===-1){for(let a=0;a<e.length;a++)if(a>=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<l.length;u++){const h=l[u];let d;if(this._supportsLayers===!0){const p=this._glBinding.getViewSubImage(this._glProjLayer,h);d=p.viewport,u===0&&i.setXRRenderTargetTextures(this._xrRenderTarget,p.colorTexture,this._glProjLayer.ignoreDepthValues&&!this._useMultiview?void 0:p.depthStencilTexture)}else d=s.getViewport(h);let f=this._cameras[u];f===void 0&&(f=new Rn,f.layers.enable(u),f.viewport=new tt,this._cameras[u]=f),f.matrix.fromArray(h.transform.matrix),f.matrix.decompose(f.position,f.quaternion,f.scale),f.projectionMatrix.fromArray(h.projectionMatrix),f.projectionMatrixInverse.copy(f.projectionMatrix).invert(),f.viewport.set(d.x,d.y,d.width,d.height),u===0&&(t.matrix.copy(f.matrix),t.matrix.decompose(t.position,t.quaternion,t.scale)),c===!0&&t.cameras.push(f)}n.setOutputRenderTarget(this._xrRenderTarget)}for(let l=0;l<this._controllers.length;l++){const c=this._controllerInputSources[l],u=this._controllers[l];c!==null&&u!==void 0&&u.update(c,e,o)}this._currentAnimationLoop&&this._currentAnimationLoop(r,e),e.detectedPlanes&&this.dispatchEvent({type:"planesdetected",data:e}),this._xrFrame=null}class HF extends Ii{constructor(e){super(),this.domElement=e,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new tt(0,0,this._width,this._height),this._scissor=new tt(0,0,this._width,this._height),this._scissorTest=!1,this.colorTexture=new Rx,this.depthTexture=new Xn}getPixelRatio(){return this._pixelRatio}getDrawingBufferSize(e){return e.set(this._width*this._pixelRatio,this._height*this._pixelRatio).floor()}getSize(e){return e.set(this._width,this._height)}setPixelRatio(e=1){this._pixelRatio!==e&&(this._pixelRatio=e,this.setSize(this._width,this._height,!1))}setDrawingBufferSize(e,t,n){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this._pixelRatio=n,this.domElement.width=Math.floor(e*n),this.domElement.height=Math.floor(t*n),this.setViewport(0,0,e,t),this._dispatchResize())}setSize(e,t,n=!0){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this.domElement.width=Math.floor(e*this._pixelRatio),this.domElement.height=Math.floor(t*this._pixelRatio),n===!0&&(this.domElement.style.width=e+"px",this.domElement.style.height=t+"px"),this.setViewport(0,0,e,t),this._dispatchResize())}getScissor(e){const t=this._scissor;return e.x=t.x,e.y=t.y,e.width=t.width,e.height=t.height,e}setScissor(e,t,n,i){const s=this._scissor;e.isVector4?s.copy(e):s.set(e,t,n,i)}getScissorTest(){return this._scissorTest}setScissorTest(e){this._scissorTest=e}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,n,i,s=0,o=1){const a=this._viewport;e.isVector4?a.copy(e):a.set(e,t,n,i),a.minDepth=s,a.maxDepth=o}_dispatchResize(){this.dispatchEvent({type:"resize"})}dispose(){this.dispatchEvent({type:"dispose"})}}const L_=new op,zo=new de,Od=new tt,kd=new lc,Gd=new hp,uu=new dt,Ps=new tt,WF={[ni]:Pt,[Pt]:ni,[wn]:wn};class $F{constructor(e,t={}){this.isRenderer=!0;const{logarithmicDepthBuffer:n=!1,reversedDepthBuffer:i=!1,alpha:s=!0,depth:o=!0,stencil:a=!1,antialias:l=!1,samples:c=0,getFallback:u=null,outputBufferType:h=en,multiview:d=!1}=t;this.backend=e,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.alpha=s,this.logarithmicDepthBuffer=n,this.reversedDepthBuffer=i,this.outputColorSpace=Qn,this.toneMapping=Un,this.toneMappingExposure=1,this.sortObjects=!0,this.depth=o,this.stencil=a,this.info=new TL,this.contextNode=So(),this.library=new nv,this.lighting=new UF,this._samples=c||l===!0?4:0,this._onCanvasTargetResize=this._onCanvasTargetResize.bind(this),this._canvasTarget=new HF(e.getDomElement()),this._canvasTarget.addEventListener("resize",this._onCanvasTargetResize),this._canvasTarget.isDefaultCanvasTarget=!0,this._inspector=new Y0,this._inspector.setRenderer(this),this._getFallback=u,this._attributes=null,this._geometries=null,this._nodes=null,this._animation=null,this._bindings=null,this._objects=null,this._pipelines=null,this._bundles=null,this._renderLists=null,this._renderContexts=null,this._textures=null,this._background=null,this._quadCache=new Map,this._currentRenderContext=null,this._opaqueSort=null,this._transparentSort=null,this._frameBufferTargets=new Map;const f=this.alpha===!0?0:1;this._clearColor=new zp(0,0,0,f),this._clearDepth=1,this._clearStencil=0,this._renderTarget=null,this._activeCubeFace=0,this._activeMipmapLevel=0,this._outputRenderTarget=null,this._mrt=null,this._renderObjectFunction=null,this._currentRenderObjectFunction=null,this._currentRenderBundle=null,this._handleObjectFunction=this._renderObjectDirect,this._isDeviceLost=!1,this.onDeviceLost=this._onDeviceLost,this._outputBufferType=h,this._cacheShadowNodes=new WeakMap,this._initialized=!1,this._callDepth=-1,this._initPromise=null,this._compilationPromises=null,this.transparent=!0,this.opaque=!0,this.shadowMap={enabled:!1,transmitted:!1,type:Yo},this.xr=new FF(this,d),this.debug={checkShaderErrors:!0,onShaderError:null,getShaderAsync:async(p,g,m)=>{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<p;f++){const g=d[f];this._nodes.needsRefresh(g)&&(this._nodes.updateBefore(g),this._nodes.updateForRender(g),this._bindings.updateForRender(g),this._nodes.updateAfter(g))}}this.backend.addBundle(a,l)}render(e,t){if(this._initialized===!1)throw new Error('Renderer: .render() called before the backend is initialized. Use "await renderer.init();" before rendering.');this._renderScene(e,t)}get initialized(){return this._initialized}_getFrameBufferTarget(){const{currentToneMapping:e,currentColorSpace:t}=this,n=e!==Un,i=t!==Xe.workingColorSpace;if(n===!1&&i===!1)return null;const{width:s,height:o}=this.getDrawingBufferSize(zo),{depth:a,stencil:l}=this,c=this._outputRenderTarget||this._canvasTarget;let u=this._frameBufferTargets.get(c);if(u===void 0){u=new Lr(s,o,{depthBuffer:a,stencilBuffer:l,type:this._outputBufferType,format:an,colorSpace:Xe.workingColorSpace,generateMipmaps:!1,minFilter:Ut,magFilter:Ut,samples:this.samples}),u.isPostProcessingRenderTarget=!0;const m=()=>{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;d<f;d++){const p=h[d],g=u[p.materialIndex];g&&g.visible&&i.push(e,c,g,n,Ps.z,p,s)}}else u.visible&&i.push(e,c,u,n,Ps.z,null,s)}}}if(e.isBundleGroup===!0&&this.backend.beginBundle!==void 0){const l=i;i=this._renderLists.get(e,t),i.begin(),l.pushBundle({bundleGroup:e,camera:t,renderList:i}),i.finish()}const a=e.children;for(let l=0,c=a.length;l<c;l++)this._projectObject(a[l],t,n,i,s)}_renderBundles(e,t,n){for(const i of e)this._renderBundle(i,t,n)}_renderTransparents(e,t,n,i,s){if(t.length>0){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<a;o++){const{object:l,geometry:c,material:u,group:h,clippingContext:d}=e[o];this._currentRenderObjectFunction(l,n,t,c,u,h,i,d,s)}}_getShadowNodes(e){const t=e.version;let n=this._cacheShadowNodes.get(e);if(n===void 0||n.version!==t){const i=e.map!==null,s=e.colorNode&&e.colorNode.isNode,o=e.castShadowNode&&e.castShadowNode.isNode,a=e.maskShadowNode&&e.maskShadowNode.isNode||e.maskNode&&e.maskNode.isNode;let l=null,c=null,u=null;if(i||s||o||a){let h,d;if(o?(h=e.castShadowNode.rgb,d=e.castShadowNode.a,this.shadowMap.transmitted!==!0&&Yt("Renderer: `shadowMap.transmitted` needs to be set to `true` when using `material.castShadowNode`.")):(h=K(0),d=j(1)),i&&(d=d.mul(Qt("map","texture",e).a)),s&&(d=d.mul(e.colorNode.a)),c=Ze(h,d),a){const f=e.maskShadowNode||e.maskNode;c=Q(([p])=>(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<i;n++){const s=this.uniforms[n],o=s.boundary,a=s.itemSize*e,l=t%ur,c=l%o,u=l+c;t+=c,u!==0&&ur-u<a&&(t+=ur-u),s.offset=t/e,s.index=n,t+=a}return Math.ceil(t/ur)*ur}update(){let e=!1;for(const t of this.uniforms)this.updateByType(t)===!0&&(e=!0);return e}updateByType(e){if(e.isNumberUniform)return this.updateNumber(e);if(e.isVector2Uniform)return this.updateVector2(e);if(e.isVector3Uniform)return this.updateVector3(e);if(e.isVector4Uniform)return this.updateVector4(e);if(e.isColorUniform)return this.updateColor(e);if(e.isMatrix3Uniform)return this.updateMatrix3(e);if(e.isMatrix4Uniform)return this.updateMatrix4(e);ne("WebGPUUniformsGroup: Unsupported uniform type.",e)}updateNumber(e){let t=!1;const n=this.values,i=e.getValue(),s=e.offset,o=e.getType();if(n[s]!==i){const a=this._getBufferForType(o);a[s]=n[s]=i,t=!0,this.addUniformUpdateRange(e)}return t}updateVector2(e){let t=!1;const n=this.values,i=e.getValue(),s=e.offset,o=e.getType();if(n[s+0]!==i.x||n[s+1]!==i.y){const a=this._getBufferForType(o);a[s+0]=n[s+0]=i.x,a[s+1]=n[s+1]=i.y,t=!0,this.addUniformUpdateRange(e)}return t}updateVector3(e){let t=!1;const n=this.values,i=e.getValue(),s=e.offset,o=e.getType();if(n[s+0]!==i.x||n[s+1]!==i.y||n[s+2]!==i.z){const a=this._getBufferForType(o);a[s+0]=n[s+0]=i.x,a[s+1]=n[s+1]=i.y,a[s+2]=n[s+2]=i.z,t=!0,this.addUniformUpdateRange(e)}return t}updateVector4(e){let t=!1;const n=this.values,i=e.getValue(),s=e.offset,o=e.getType();if(n[s+0]!==i.x||n[s+1]!==i.y||n[s+2]!==i.z||n[s+3]!==i.w){const a=this._getBufferForType(o);a[s+0]=n[s+0]=i.x,a[s+1]=n[s+1]=i.y,a[s+2]=n[s+2]=i.z,a[s+3]=n[s+3]=i.w,t=!0,this.addUniformUpdateRange(e)}return t}updateColor(e){let t=!1;const n=this.values,i=e.getValue(),s=e.offset;if(n[s+0]!==i.r||n[s+1]!==i.g||n[s+2]!==i.b){const o=this.buffer;o[s+0]=n[s+0]=i.r,o[s+1]=n[s+1]=i.g,o[s+2]=n[s+2]=i.b,t=!0,this.addUniformUpdateRange(e)}return t}updateMatrix3(e){let t=!1;const n=this.values,i=e.getValue().elements,s=e.offset;if(n[s+0]!==i[0]||n[s+1]!==i[1]||n[s+2]!==i[2]||n[s+4]!==i[3]||n[s+5]!==i[4]||n[s+6]!==i[5]||n[s+8]!==i[6]||n[s+9]!==i[7]||n[s+10]!==i[8]){const o=this.buffer;o[s+0]=n[s+0]=i[0],o[s+1]=n[s+1]=i[1],o[s+2]=n[s+2]=i[2],o[s+4]=n[s+4]=i[3],o[s+5]=n[s+5]=i[4],o[s+6]=n[s+6]=i[5],o[s+8]=n[s+8]=i[6],o[s+9]=n[s+9]=i[7],o[s+10]=n[s+10]=i[8],t=!0,this.addUniformUpdateRange(e)}return t}updateMatrix4(e){let t=!1;const n=this.values,i=e.getValue().elements,s=e.offset;return KF(n,i,s)===!1&&(this.buffer.set(i,s),YF(n,i,s),t=!0,this.addUniformUpdateRange(e)),t}_getBufferForType(e){return e==="int"||e==="ivec2"||e==="ivec3"||e==="ivec4"?new Int32Array(this.buffer.buffer):e==="uint"||e==="uvec2"||e==="uvec3"||e==="uvec4"?new Uint32Array(this.buffer.buffer):this.buffer}}function YF(r,e,t){for(let n=0,i=e.length;n<i;n++)r[t+n]=e[n]}function KF(r,e,t){for(let n=0,i=e.length;n<i;n++)if(r[t+n]!==e[n])return!1;return!0}let ZF=0;class av extends jF{constructor(e,t){super(e),this.id=ZF++,this.groupNode=t,this.isNodeUniformsGroup=!0}}class lv extends iv{constructor(e,t){super(e),this._texture=null,this._onTextureDispose=()=>{this.generation=null,this.version=-1},this.texture=t,this.version=t?t.version:-1,this.generation=null,this.samplerKey="",this.isSampler=!0}set texture(e){this._texture!==e&&(this._texture&&this._texture.removeEventListener("dispose",this._onTextureDispose),this._texture=e,this.generation=null,this.version=-1,this._texture&&this._texture.addEventListener("dispose",this._onTextureDispose))}get texture(){return this._texture}update(){const{texture:e,version:t}=this;return t!==e.version?(this.version=e.version,!0):!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*s<i&&u++;const h=c*u*s,d=new n.constructor(h);d.set(n,0),t.array=d;const f=new up(t.array,c,u,a,l[t.array.constructor.name]||Zt);f.needsUpdate=!0,f.isPBOTexture=!0;const p=new pc(f,null,null);p.setPrecision("high"),t.pboNode=p,t.pbo=p.value,this.getUniformFromNode(t.pboNode,"texture",this.shaderStage,this.context.nodeName)}}getPropertyName(e,t=this.shaderStage){return e.isNodeUniform&&e.node.isTextureNode!==!0&&e.node.isBufferNode!==!0?e.name:super.getPropertyName(e,t)}generatePBO(e){const{node:t,indexNode:n}=e,i=t.value;if(this.renderer.backend.has(i)){const u=this.renderer.backend.get(i);u.pbo=i.pbo}const s=this.getUniformFromNode(i.pboNode,"texture",this.shaderStage,this.context.nodeName),o=this.getPropertyName(s);this.increaseUsage(n);const a=n.build(this,"uint"),l=this.getDataFromNode(e);let c=l.propertyName;if(c===void 0){const u=this.getVarFromNode(e);c=this.getPropertyName(u);const h=this.getDataFromNode(t);let d=h.propertySizeName;d===void 0&&(d=c+"Size",this.getVarFromNode(t,d,"uint"),this.addLineFlowCode(`${d} = uint( textureSize( ${o}, 0 ).x )`,e),h.propertySizeName=d);const{itemSize:f}=i,p="."+Wa.join("").slice(0,f),g=`ivec2(${a} % ${d}, ${a} / ${d})`,m=this.generateTextureLoad(null,o,g,"0",null,null);let _="vec4";i.pbo.type===wt?_="uvec4":i.pbo.type===Sn&&(_="ivec4"),this.addLineFlowCode(`${c} = ${_}(${m})${p}`,e),l.propertyName=c}return c}generateTextureLoad(e,t,n,i,s,o){i===null&&(i="0");let a;return s?o?a=`texelFetchOffset( ${t}, ivec3( ${n}, ${s} ), int( ${i} ), ${o} )`:a=`texelFetch( ${t}, ivec3( ${n}, ${s} ), int( ${i} ) )`:o?a=`texelFetchOffset( ${t}, ${n}, int( ${i} ), ${o} )`:a=`texelFetch( ${t}, ${n}, int( ${i} ) )`,e!==null&&e.isDepthTexture&&(a+=".x"),a}generateTexture(e,t,n,i,s){return i&&(n=`vec3( ${n}, ${i} )`),e.isDepthTexture?s?`textureOffset( ${t}, ${n}, ${s} ).x`:`texture( ${t}, ${n} ).x`:s?`textureOffset( ${t}, ${n}, ${s} )`:`texture( ${t}, ${n} )`}generateTextureLevel(e,t,n,i,s,o){return s&&(n=`vec3( ${n}, ${s} )`),o?`textureLodOffset( ${t}, ${n}, ${i}, ${o} )`:`textureLod( ${t}, ${n}, ${i} )`}generateTextureBias(e,t,n,i,s,o){return s&&(n=`vec3( ${n}, ${s} )`),o?`textureOffset( ${t}, ${n}, ${o}, ${i} )`:`texture( ${t}, ${n}, ${i} )`}generateTextureGrad(e,t,n,i,s,o){return s&&(n=`vec3( ${n}, ${s} )`),o?`textureGradOffset( ${t}, ${n}, ${i[0]}, ${i[1]}, ${o} )`:`textureGrad( ${t}, ${n}, ${i[0]}, ${i[1]} )`}generateTextureCompare(e,t,n,i,s,o,a=this.shaderStage){if(a==="fragment")return e.isCubeTexture?`texture( ${t}, vec4( ${n}, ${i} ) )`:s?o?`textureOffset( ${t}, vec4( ${n}, ${s}, ${i} ), ${o} )`:`texture( ${t}, vec4( ${n}, ${s}, ${i} ) )`:o?`textureOffset( ${t}, vec3( ${n}, ${i} ), ${o} )`:`texture( ${t}, vec3( ${n}, ${i} ) )`;ne(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${a} shader.`)}getUniforms(e){const t=this.uniforms[e],n=[],i={};for(const o of t){let a=null,l=!1;if(o.type==="texture"||o.type==="texture3D"){const c=o.node.value;let u="";(c.isDataTexture===!0||c.isData3DTexture===!0)&&(c.type===wt?u="u":c.type===Sn&&(u="i")),o.type==="texture3D"&&c.isArrayTexture===!1?a=`${u}sampler3D ${o.name};`:c.compareFunction?c.isArrayTexture===!0?a=`sampler2DArrayShadow ${o.name};`:a=`sampler2DShadow ${o.name};`:c.isArrayTexture===!0||c.isDataArrayTexture===!0||c.isCompressedArrayTexture===!0?a=`${u}sampler2DArray ${o.name};`:a=`${u}sampler2D ${o.name};`}else if(o.type==="cubeTexture")a=`samplerCube ${o.name};`;else if(o.type==="cubeDepthTexture")o.node.value.compareFunction?a=`samplerCubeShadow ${o.name};`:a=`samplerCube ${o.name};`;else if(o.type==="buffer"){const c=o.node,u=this.getType(c.bufferType),h=c.bufferCount,d=h>0?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;n<e.length;n++){const i=e[n],s=this.getPropertyName(i.attributeNode);s&&(t+=`${i.varyingName} = ${s};
|
|
`)}return t}_getGLSLUniformStruct(e,t){return`
|
|
layout( std140 ) uniform ${e} {
|
|
${t}
|
|
};`}_getGLSLVertexCode(e){return`#version 300 es
|
|
|
|
${this.getSignature()}
|
|
|
|
// extensions
|
|
${e.extensions}
|
|
|
|
// precision
|
|
${k_}
|
|
|
|
// uniforms
|
|
${e.uniforms}
|
|
|
|
// varyings
|
|
${e.varyings}
|
|
|
|
// attributes
|
|
${e.attributes}
|
|
|
|
// vars
|
|
${e.vars}
|
|
|
|
// codes
|
|
${e.codes}
|
|
|
|
void main() {
|
|
|
|
// transforms
|
|
${e.transforms}
|
|
|
|
// flow
|
|
${e.flow}
|
|
|
|
gl_PointSize = 1.0;
|
|
|
|
}
|
|
`}_getGLSLFragmentCode(e){return`#version 300 es
|
|
|
|
${this.getSignature()}
|
|
|
|
// extensions
|
|
${e.extensions}
|
|
|
|
// precision
|
|
${k_}
|
|
|
|
// structs
|
|
${e.structs}
|
|
|
|
// uniforms
|
|
${e.uniforms}
|
|
|
|
// varyings
|
|
${e.varyings}
|
|
|
|
// vars
|
|
${e.vars}
|
|
|
|
// codes
|
|
${e.codes}
|
|
|
|
void main() {
|
|
|
|
// flow
|
|
${e.flow}
|
|
|
|
}
|
|
`}buildCode(){const e=this.material!==null?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){let n=`// code
|
|
|
|
`;n+=this.flowCode[t];const i=this.flowNodes[t],s=i[i.length-1];for(const a of i){const l=this.getFlowData(a),c=a.name;c&&(n.length>0&&(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<u;c++){const h=l[c];n.bufferSubData(a,h.start*i.BYTES_PER_ELEMENT,i,h.start,h.count)}s.clearUpdateRanges()}n.bindBuffer(a,null),o.version=s.version}destroyAttribute(e){const t=this.backend,{gl:n}=t;e.isInterleavedBufferAttribute&&t.delete(e.data);const i=t.get(e);n.deleteBuffer(i.bufferGPU),t.delete(e)}async getArrayBufferAsync(e,t=null,n=0,i=-1){const s=this.backend,{gl:o}=s,a=e.isInterleavedBufferAttribute?e.data:e,l=s.get(a),{bufferGPU:c}=l,u=i===-1?l.byteLength-n:i;let h;if(t===null)h=new Uint8Array(new ArrayBuffer(u));else if(t.isReadbackBuffer){if(t._mapped===!0)throw new Error("WebGPURenderer: ReadbackBuffer must be released before being used again.");const d=()=>{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;o<e.length;o++){const a=e[o];let l=null;if(t!==null){const c=t.getBlendMode(a.name);c.blending===dx?l=n:c.blending!==Cn&&(l=c)}else l=n;l!==null?this._setMRTBlendingIndex(o,l):s.blendFuncSeparateiOES(o,i.ONE,i.ZERO,i.ONE,i.ZERO)}}_setMRTBlendingIndex(e,t){const{gl:n}=this,i=this.backend.drawBuffersIndexedExt,s=t.blending,o=t.blendSrc,a=t.blendDst,l=t.blendEquation,c=t.premultipliedAlpha;if(s===Jr){const u=t.blendSrcAlpha!==null?t.blendSrcAlpha:o,h=t.blendDstAlpha!==null?t.blendDstAlpha:a,d=t.blendEquationAlpha!==null?t.blendEquationAlpha:l;i.blendEquationSeparateiOES(e,ml[l],ml[d]),i.blendFuncSeparateiOES(e,Ds[o],Ds[a],Ds[u],Ds[h])}else if(i.blendEquationSeparateiOES(e,n.FUNC_ADD,n.FUNC_ADD),c)switch(s){case Jn:i.blendFuncSeparateiOES(e,n.ONE,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA);break;case hr:i.blendFuncSeparateiOES(e,n.ONE,n.ONE,n.ONE,n.ONE);break;case dr:i.blendFuncSeparateiOES(e,n.ZERO,n.ONE_MINUS_SRC_COLOR,n.ZERO,n.ONE);break;case fr:i.blendFuncSeparateiOES(e,n.DST_COLOR,n.ONE_MINUS_SRC_ALPHA,n.ZERO,n.ONE);break;default:i.blendFuncSeparateiOES(e,n.ONE,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA);break}else switch(s){case Jn:i.blendFuncSeparateiOES(e,n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA);break;case hr:i.blendFuncSeparateiOES(e,n.SRC_ALPHA,n.ONE,n.ONE,n.ONE);break;case dr:i.blendFuncSeparateiOES(e,n.ZERO,n.ONE_MINUS_SRC_COLOR,n.ZERO,n.ONE);break;case fr:i.blendFuncSeparateiOES(e,n.DST_COLOR,n.ONE_MINUS_SRC_ALPHA,n.ZERO,n.ONE);break;default:i.blendFuncSeparateiOES(e,n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA);break}}setBlending(e,t,n,i,s,o,a,l){const{gl:c}=this;if(e===Cn){this.currentBlendingEnabled===!0&&(this.disable(c.BLEND),this.currentBlendingEnabled=!1);return}if(this.currentBlendingEnabled===!1&&(this.enable(c.BLEND),this.currentBlendingEnabled=!0),e!==Jr){if(e!==this.currentBlending||l!==this.currentPremultipledAlpha){if((this.currentBlendEquation!==Wn||this.currentBlendEquationAlpha!==Wn)&&(c.blendEquation(c.FUNC_ADD),this.currentBlendEquation=Wn,this.currentBlendEquationAlpha=Wn),l)switch(e){case Jn:c.blendFuncSeparate(c.ONE,c.ONE_MINUS_SRC_ALPHA,c.ONE,c.ONE_MINUS_SRC_ALPHA);break;case hr:c.blendFunc(c.ONE,c.ONE);break;case dr:c.blendFuncSeparate(c.ZERO,c.ONE_MINUS_SRC_COLOR,c.ZERO,c.ONE);break;case fr:c.blendFuncSeparate(c.DST_COLOR,c.ONE_MINUS_SRC_ALPHA,c.ZERO,c.ONE);break;default:ne("WebGLState: Invalid blending: ",e);break}else switch(e){case Jn:c.blendFuncSeparate(c.SRC_ALPHA,c.ONE_MINUS_SRC_ALPHA,c.ONE,c.ONE_MINUS_SRC_ALPHA);break;case hr:c.blendFuncSeparate(c.SRC_ALPHA,c.ONE,c.ONE,c.ONE);break;case dr:ne("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case fr:ne("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:ne("WebGLState: Invalid blending: ",e);break}this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentBlending=e,this.currentPremultipledAlpha=l}return}s=s||t,o=o||n,a=a||i,(t!==this.currentBlendEquation||s!==this.currentBlendEquationAlpha)&&(c.blendEquationSeparate(ml[t],ml[s]),this.currentBlendEquation=t,this.currentBlendEquationAlpha=s),(n!==this.currentBlendSrc||i!==this.currentBlendDst||o!==this.currentBlendSrcAlpha||a!==this.currentBlendDstAlpha)&&(c.blendFuncSeparate(Ds[n],Ds[i],Ds[o],Ds[a]),this.currentBlendSrc=n,this.currentBlendDst=i,this.currentBlendSrcAlpha=o,this.currentBlendDstAlpha=a),this.currentBlending=e,this.currentPremultipledAlpha=!1}setColorMask(e){this.currentColorMask!==e&&(this.gl.colorMask(e,e,e,e),this.currentColorMask=e)}setDepthTest(e){const{gl:t}=this;e?this.enable(t.DEPTH_TEST):this.disable(t.DEPTH_TEST)}setReversedDepth(e){if(this.currentDepthReversed!==e){const t=this.backend.extensions.get("EXT_clip_control");e?t.clipControlEXT(t.LOWER_LEFT_EXT,t.ZERO_TO_ONE_EXT):t.clipControlEXT(t.LOWER_LEFT_EXT,t.NEGATIVE_ONE_TO_ONE_EXT),this.currentDepthReversed=e}}setDepthMask(e){this.currentDepthMask!==e&&(this.gl.depthMask(e),this.currentDepthMask=e)}setDepthFunc(e){if(this.currentDepthReversed&&(e=tp[e]),this.currentDepthFunc!==e){const{gl:t}=this;switch(e){case Il:t.depthFunc(t.NEVER);break;case Bl:t.depthFunc(t.ALWAYS);break;case Ol:t.depthFunc(t.LESS);break;case Ar:t.depthFunc(t.LEQUAL);break;case kl:t.depthFunc(t.EQUAL);break;case Gl:t.depthFunc(t.GEQUAL);break;case Vl:t.depthFunc(t.GREATER);break;case zl:t.depthFunc(t.NOTEQUAL);break;default:t.depthFunc(t.LEQUAL)}this.currentDepthFunc=e}}scissor(e,t,n,i){const s=this._tempVec4.set(e,t,n,i);if(this.currentScissor.equals(s)===!1){const{gl:o}=this;o.scissor(s.x,s.y,s.z,s.w),this.currentScissor.copy(s)}}viewport(e,t,n,i){const s=this._tempVec4.set(e,t,n,i);if(this.currentViewport.equals(s)===!1){const{gl:o}=this;o.viewport(s.x,s.y,s.z,s.w),this.currentViewport.copy(s)}}setScissorTest(e){const t=this.gl;e?this.enable(t.SCISSOR_TEST):this.disable(t.SCISSOR_TEST)}setStencilTest(e){const{gl:t}=this;e?this.enable(t.STENCIL_TEST):this.disable(t.STENCIL_TEST)}setStencilMask(e){this.currentStencilMask!==e&&(this.gl.stencilMask(e),this.currentStencilMask=e)}setStencilFunc(e,t,n){(this.currentStencilFunc!==e||this.currentStencilRef!==t||this.currentStencilFuncMask!==n)&&(this.gl.stencilFunc(e,t,n),this.currentStencilFunc=e,this.currentStencilRef=t,this.currentStencilFuncMask=n)}setStencilOp(e,t,n){(this.currentStencilFail!==e||this.currentStencilZFail!==t||this.currentStencilZPass!==n)&&(this.gl.stencilOp(e,t,n),this.currentStencilFail=e,this.currentStencilZFail=t,this.currentStencilZPass=n)}setMaterial(e,t,n){const{gl:i}=this;e.side===wn?this.disable(i.CULL_FACE):this.enable(i.CULL_FACE);let s=e.side===Pt;t&&(s=!s),this.setFlipSided(s),e.blending===Jn&&e.transparent===!1?this.setBlending(Cn):this.setBlending(e.blending,e.blendEquation,e.blendSrc,e.blendDst,e.blendEquationAlpha,e.blendSrcAlpha,e.blendDstAlpha,e.premultipliedAlpha),this.setDepthFunc(e.depthFunc),this.setDepthTest(e.depthTest),this.setDepthMask(e.depthWrite),this.setColorMask(e.colorWrite);const o=e.stencilWrite;if(this.setStencilTest(o),o&&(this.setStencilMask(e.stencilWriteMask),this.setStencilFunc(e.stencilFunc,e.stencilRef,e.stencilFuncMask),this.setStencilOp(e.stencilFail,e.stencilZFail,e.stencilZPass)),this.setPolygonOffset(e.polygonOffset,e.polygonOffsetFactor,e.polygonOffsetUnits),e.alphaToCoverage===!0&&this.backend.renderer.currentSamples>0?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<n?this.enable(12288+l):this.disable(12288+l)}setPolygonOffset(e,t,n){const{gl:i}=this;e?(this.enable(i.POLYGON_OFFSET_FILL),(this.currentPolygonOffsetFactor!==t||this.currentPolygonOffsetUnits!==n)&&(i.polygonOffset(t,n),this.currentPolygonOffsetFactor=t,this.currentPolygonOffsetUnits=n)):this.disable(i.POLYGON_OFFSET_FILL)}useProgram(e){return this.currentProgram!==e?(this.gl.useProgram(e),this.currentProgram=e,!0):!1}setVertexState(e,t=null){const n=this.gl;return this.currentVAO!==e||this.currentIndex!==t?(n.bindVertexArray(e),t!==null&&n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,t),this.currentVAO=e,this.currentIndex=t,!0):!1}resetVertexState(){const e=this.gl;e.bindVertexArray(null),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null),this.currentVAO=null,this.currentIndex=null}bindFramebuffer(e,t){const{gl:n,currentBoundFramebuffers:i}=this;return i[e]!==t?(n.bindFramebuffer(e,t),i[e]=t,e===n.DRAW_FRAMEBUFFER&&(i[n.FRAMEBUFFER]=t),e===n.FRAMEBUFFER&&(i[n.DRAW_FRAMEBUFFER]=t),!0):!1}drawBuffers(e,t){const{gl:n}=this;let i=[],s=!1;if(e.textures!==null){i=this.currentDrawbuffers.get(t),i===void 0&&(i=[],this.currentDrawbuffers.set(t,i));const o=e.textures;if(i.length!==o.length||i[0]!==n.COLOR_ATTACHMENT0){for(let a=0,l=o.length;a<l;a++)i[a]=n.COLOR_ATTACHMENT0+a;i.length=o.length,s=!0}}else i[0]!==n.BACK&&(i[0]=n.BACK,s=!0);s&&n.drawBuffers(i)}activeTexture(e){const{gl:t,currentTextureSlot:n,maxTextures:i}=this;e===void 0&&(e=t.TEXTURE0+i-1),n!==e&&(t.activeTexture(e),this.currentTextureSlot=e)}bindTexture(e,t,n){const{gl:i,currentTextureSlot:s,currentBoundTextures:o,maxTextures:a}=this;n===void 0&&(s===null?n=i.TEXTURE0+a-1:n=s);let l=o[n];l===void 0&&(l={type:void 0,texture:void 0},o[n]=l),(l.type!==e||l.texture!==t)&&(s!==n&&(i.activeTexture(n),this.currentTextureSlot=n),i.bindTexture(e,t),l.type=e,l.texture=t)}bindBufferBase(e,t,n){const{gl:i}=this,s=`${e}-${t}`;return this.currentBoundBufferBases[s]!==n?(i.bindBufferBase(e,t,n),this.currentBoundBufferBases[s]=n,!0):!1}unbindTexture(){const{gl:e,currentTextureSlot:t,currentBoundTextures:n}=this,i=n[t];i!==void 0&&i.type!==void 0&&(e.bindTexture(i.type,null),i.type=void 0,i.texture=void 0)}getParameter(e){const{gl:t,parameters:n}=this;return n[e]!==void 0?n[e]:t.getParameter(e)}pixelStorei(e,t){const{gl:n,parameters:i}=this;i[e]!==t&&(n.pixelStorei(e,t),i[e]=t)}}class oI{constructor(e){this.backend=e,this.gl=this.backend.gl,this.extensions=e.extensions}convert(e,t=ri){const{gl:n,extensions:i}=this;let s;const o=Xe.getTransfer(t);if(e===$t)return n.UNSIGNED_BYTE;if(e===ic)return n.UNSIGNED_SHORT_4_4_4_4;if(e===sc)return n.UNSIGNED_SHORT_5_5_5_1;if(e===rc)return n.UNSIGNED_INT_5_9_9_9_REV;if(e===oc)return n.UNSIGNED_INT_10F_11F_11F_REV;if(e===_r)return n.BYTE;if(e===xr)return n.SHORT;if(e===Ci)return n.UNSIGNED_SHORT;if(e===Sn)return n.INT;if(e===wt)return n.UNSIGNED_INT;if(e===Zt)return n.FLOAT;if(e===en)return n.HALF_FLOAT;if(e===Yu)return n.ALPHA;if(e===Ba)return n.RGB;if(e===an)return n.RGBA;if(e===Nn)return n.DEPTH_COMPONENT;if(e===$n)return n.DEPTH_STENCIL;if(e===Oa)return n.RED;if(e===mo)return n.RED_INTEGER;if(e===Fn)return n.RG;if(e===go)return n.RG_INTEGER;if(e===ka)return n.RGBA_INTEGER;if(e===yr||e===vr||e===Sr||e===br)if(o===Ee)if(s=i.get("WEBGL_compressed_texture_s3tc_srgb"),s!==null){if(e===yr)return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(e===vr)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(e===Sr)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(e===br)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(s=i.get("WEBGL_compressed_texture_s3tc"),s!==null){if(e===yr)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(e===vr)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(e===Sr)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(e===br)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(e===Hl||e===Wl||e===$l||e===Xl)if(s=i.get("WEBGL_compressed_texture_pvrtc"),s!==null){if(e===Hl)return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(e===Wl)return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(e===$l)return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(e===Xl)return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(e===oa||e===aa||e===la||e===ca||e===ua||e===Rr||e===ha)if(s=i.get("WEBGL_compressed_texture_etc"),s!==null){if(e===oa||e===aa)return o===Ee?s.COMPRESSED_SRGB8_ETC2:s.COMPRESSED_RGB8_ETC2;if(e===la)return o===Ee?s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:s.COMPRESSED_RGBA8_ETC2_EAC;if(e===ca)return s.COMPRESSED_R11_EAC;if(e===ua)return s.COMPRESSED_SIGNED_R11_EAC;if(e===Rr)return s.COMPRESSED_RG11_EAC;if(e===ha)return s.COMPRESSED_SIGNED_RG11_EAC}else return null;if(e===da||e===fa||e===pa||e===ma||e===ga||e===_a||e===xa||e===ya||e===va||e===Sa||e===ba||e===Ta||e===Ma||e===Ea)if(s=i.get("WEBGL_compressed_texture_astc"),s!==null){if(e===da)return o===Ee?s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:s.COMPRESSED_RGBA_ASTC_4x4_KHR;if(e===fa)return o===Ee?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:s.COMPRESSED_RGBA_ASTC_5x4_KHR;if(e===pa)return o===Ee?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:s.COMPRESSED_RGBA_ASTC_5x5_KHR;if(e===ma)return o===Ee?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:s.COMPRESSED_RGBA_ASTC_6x5_KHR;if(e===ga)return o===Ee?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:s.COMPRESSED_RGBA_ASTC_6x6_KHR;if(e===_a)return o===Ee?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:s.COMPRESSED_RGBA_ASTC_8x5_KHR;if(e===xa)return o===Ee?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:s.COMPRESSED_RGBA_ASTC_8x6_KHR;if(e===ya)return o===Ee?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:s.COMPRESSED_RGBA_ASTC_8x8_KHR;if(e===va)return o===Ee?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:s.COMPRESSED_RGBA_ASTC_10x5_KHR;if(e===Sa)return o===Ee?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:s.COMPRESSED_RGBA_ASTC_10x6_KHR;if(e===ba)return o===Ee?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:s.COMPRESSED_RGBA_ASTC_10x8_KHR;if(e===Ta)return o===Ee?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:s.COMPRESSED_RGBA_ASTC_10x10_KHR;if(e===Ma)return o===Ee?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:s.COMPRESSED_RGBA_ASTC_12x10_KHR;if(e===Ea)return o===Ee?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:s.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(e===Aa)if(s=i.get("EXT_texture_compression_bptc"),s!==null){if(e===Aa)return o===Ee?s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:s.COMPRESSED_RGBA_BPTC_UNORM_EXT}else return null;if(e===Ra||e===wa||e===wr||e===Ca)if(s=i.get("EXT_texture_compression_rgtc"),s!==null){if(e===Ra)return s.COMPRESSED_RED_RGTC1_EXT;if(e===wa)return s.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(e===wr)return s.COMPRESSED_RED_GREEN_RGTC2_EXT;if(e===Ca)return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return e===ui?n.UNSIGNED_INT_24_8:n[e]!==void 0?n[e]:null}_clientWaitAsync(){const{gl:e}=this,t=e.fenceSync(e.SYNC_GPU_COMMANDS_COMPLETE,0);return e.flush(),new Promise((n,i)=>{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;f<h.length;f++){const p=h[f];e.isCompressedArrayTexture?e.format!==n.RGBA?l!==null?n.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,f,0,0,0,p.width,p.height,d.depth,l,p.data):ee("WebGLBackend: Attempt to load unsupported compressed texture format in .uploadTexture()"):n.texSubImage3D(n.TEXTURE_2D_ARRAY,f,0,0,0,p.width,p.height,d.depth,l,c,p.data):l!==null?n.compressedTexSubImage2D(n.TEXTURE_2D,f,0,0,p.width,p.height,l,p.data):ee("WebGLBackend: Unsupported compressed texture format")}}else if(e.isCubeTexture){const h=t.images,d=e.mipmaps;for(let f=0;f<6;f++){const p=du(h[f]);n.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+f,0,0,0,i,s,l,c,p);for(let g=0;g<d.length;g++){const m=d[g],_=du(m.images[f]);n.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+f,g+1,0,0,_.width,_.height,l,c,_)}}}else if(e.isDataArrayTexture||e.isArrayTexture){const h=t.image;if(e.layerUpdates.size>0){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;d<f;d++){const p=h[d],g=du(p);n.texSubImage2D(a,d,0,0,p.width,p.height,l,c,g)}else{const d=du(t.image);n.texSubImage2D(a,0,0,0,i,s,l,c,d)}}}generateMipmaps(e){const{gl:t,backend:n}=this,{textureGPU:i,glTextureType:s}=n.get(e);n.state.bindTexture(s,i),t.generateMipmap(s)}deallocateRenderBuffers(e){const{gl:t,backend:n}=this;if(e){const i=n.get(e);if(i.renderBufferStorageSetup=void 0,i.framebuffers){for(const s in i.framebuffers)t.deleteFramebuffer(i.framebuffers[s]);delete i.framebuffers}if(i.depthRenderbuffer&&(t.deleteRenderbuffer(i.depthRenderbuffer),delete i.depthRenderbuffer),i.stencilRenderbuffer&&(t.deleteRenderbuffer(i.stencilRenderbuffer),delete i.stencilRenderbuffer),i.msaaFrameBuffer&&(t.deleteFramebuffer(i.msaaFrameBuffer),delete i.msaaFrameBuffer),i.msaaRenderbuffers){for(let s=0;s<i.msaaRenderbuffers.length;s++)t.deleteRenderbuffer(i.msaaRenderbuffers[s]);delete i.msaaRenderbuffers}}}destroyTexture(e,t=!1){const{gl:n,backend:i}=this,{textureGPU:s,renderTarget:o}=i.get(e);this.deallocateRenderBuffers(o),t===!1&&n.deleteTexture(s),i.delete(e)}copyTextureToTexture(e,t,n=null,i=null,s=0,o=0){const{gl:a,backend:l}=this,{state:c}=this.backend,{textureGPU:u,glTextureType:h,glType:d,glFormat:f}=l.get(t);c.bindTexture(h,u);let p,g,m,_,x,v,S,E,T;const A=e.isCompressedTexture?e.mipmaps[o]:e.image;if(n!==null)p=n.max.x-n.min.x,g=n.max.y-n.min.y,m=n.isBox3?n.max.z-n.min.z:1,_=n.min.x,x=n.min.y,v=n.isBox3?n.min.z:0;else{const L=Math.pow(2,-s);p=Math.floor(A.width*L),g=Math.floor(A.height*L),e.isDataArrayTexture||e.isArrayTexture?m=A.depth:e.isData3DTexture?m=Math.floor(A.depth*L):m=1,_=0,x=0,v=0}i!==null?(S=i.x,E=i.y,T=i.z):(S=0,E=0,T=0),c.pixelStorei(a.UNPACK_FLIP_Y_WEBGL,t.flipY),c.pixelStorei(a.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),c.pixelStorei(a.UNPACK_ALIGNMENT,t.unpackAlignment);const y=c.getParameter(a.UNPACK_ROW_LENGTH),R=c.getParameter(a.UNPACK_IMAGE_HEIGHT),P=c.getParameter(a.UNPACK_SKIP_PIXELS),N=c.getParameter(a.UNPACK_SKIP_ROWS),U=c.getParameter(a.UNPACK_SKIP_IMAGES);c.pixelStorei(a.UNPACK_ROW_LENGTH,A.width),c.pixelStorei(a.UNPACK_IMAGE_HEIGHT,A.height),c.pixelStorei(a.UNPACK_SKIP_PIXELS,_),c.pixelStorei(a.UNPACK_SKIP_ROWS,x),c.pixelStorei(a.UNPACK_SKIP_IMAGES,v);const G=e.isDataArrayTexture||e.isData3DTexture||t.isArrayTexture,V=t.isDataArrayTexture||t.isData3DTexture||t.isArrayTexture;if(e.isDepthTexture){const L=l.get(e),B=l.get(t),H=l.get(L.renderTarget),ie=l.get(B.renderTarget),ce=H.framebuffers[L.cacheKey],ve=ie.framebuffers[B.cacheKey];c.bindFramebuffer(a.READ_FRAMEBUFFER,ce),c.bindFramebuffer(a.DRAW_FRAMEBUFFER,ve);for(let Ce=0;Ce<m;Ce++)G&&(a.framebufferTextureLayer(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,L.textureGPU,s,v+Ce),a.framebufferTextureLayer(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,u,o,T+Ce)),a.blitFramebuffer(_,x,p,g,S,E,p,g,a.DEPTH_BUFFER_BIT,a.NEAREST);c.bindFramebuffer(a.READ_FRAMEBUFFER,null),c.bindFramebuffer(a.DRAW_FRAMEBUFFER,null)}else if(s!==0||e.isRenderTargetTexture||l.has(e)){const L=l.get(e);this._srcFramebuffer===null&&(this._srcFramebuffer=a.createFramebuffer()),this._dstFramebuffer===null&&(this._dstFramebuffer=a.createFramebuffer()),c.bindFramebuffer(a.READ_FRAMEBUFFER,this._srcFramebuffer),c.bindFramebuffer(a.DRAW_FRAMEBUFFER,this._dstFramebuffer);for(let B=0;B<m;B++)G?a.framebufferTextureLayer(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,L.textureGPU,s,v+B):a.framebufferTexture2D(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,L.textureGPU,s),V?a.framebufferTextureLayer(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,u,o,T+B):a.framebufferTexture2D(a.DRAW_FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,u,o),s!==0?a.blitFramebuffer(_,x,p,g,S,E,p,g,a.COLOR_BUFFER_BIT,a.NEAREST):V?a.copyTexSubImage3D(h,o,S,E,T+B,_,x,p,g):a.copyTexSubImage2D(h,o,S,E,_,x,p,g);c.bindFramebuffer(a.READ_FRAMEBUFFER,null),c.bindFramebuffer(a.DRAW_FRAMEBUFFER,null)}else V?e.isDataTexture||e.isData3DTexture?a.texSubImage3D(h,o,S,E,T,p,g,m,f,d,A.data):t.isCompressedArrayTexture?a.compressedTexSubImage3D(h,o,S,E,T,p,g,m,f,A.data):a.texSubImage3D(h,o,S,E,T,p,g,m,f,d,A):e.isDataTexture?a.texSubImage2D(a.TEXTURE_2D,o,S,E,p,g,f,d,A.data):e.isCompressedTexture?a.compressedTexSubImage2D(a.TEXTURE_2D,o,S,E,A.width,A.height,f,A.data):a.texSubImage2D(a.TEXTURE_2D,o,S,E,p,g,f,d,A);c.pixelStorei(a.UNPACK_ROW_LENGTH,y),c.pixelStorei(a.UNPACK_IMAGE_HEIGHT,R),c.pixelStorei(a.UNPACK_SKIP_PIXELS,P),c.pixelStorei(a.UNPACK_SKIP_ROWS,N),c.pixelStorei(a.UNPACK_SKIP_IMAGES,U),o===0&&t.generateMipmaps&&a.generateMipmap(h),c.unbindTexture()}copyFramebufferToTexture(e,t,n){const{gl:i}=this,{state:s}=this.backend,{textureGPU:o}=this.backend.get(e),{x:a,y:l,z:c,w:u}=n,h=e.isDepthTexture===!0||t.renderTarget&&t.renderTarget.samples>0,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;c<n;c++)this.render(e[c],t[c]);else{this.index!==0?l.multiDrawElementsWEBGL(s,t,0,this.type,e,0,n):l.multiDrawArraysWEBGL(s,e,0,t,0,n);let c=0;for(let u=0;u<n;u++)c+=t[u];a.update(o,c,1)}}}class hv{constructor(e=256){this.trackTimestamp=!0,this.maxQueries=e,this.currentQueryIndex=0,this.queryOffsets=new Map,this.isDisposed=!1,this.lastValue=0,this.frames=[],this.pendingResolve=!1,this.timestamps=new Map}getTimestampFrames(){return this.frames}getTimestamp(e){let t=this.timestamps.get(e);return t===void 0&&(ee(`TimestampQueryPool: No timestamp available for uid ${e}.`),t=0),t}hasTimestamp(e){return this.timestamps.has(e)}allocateQueriesForContext(){}async resolveQueriesAsync(){}dispose(){}}class hI extends hv{constructor(e,t,n=2048){if(super(n),this.gl=e,this.type=t,this.ext=e.getExtension("EXT_disjoint_timer_query_webgl2")||e.getExtension("EXT_disjoint_timer_query"),!this.ext){ee("EXT_disjoint_timer_query not supported; timestamps will be disabled."),this.trackTimestamp=!1;return}this.queries=[];for(let i=0;i<this.maxQueries;i++)this.queries.push(e.createQuery());this.activeQuery=null,this.queryStates=new Map}allocateQueriesForContext(e){if(!this.trackTimestamp)return null;if(this.currentQueryIndex+2>this.maxQueries)return 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<a.length;l++){const c=a[l];c.generateMipmaps&&this.generateMipmaps(c)}if(this._currentContext=s,this._resolveRenderTarget(e),s!==null){if(this._setFramebuffer(s),s.viewport)this.updateViewport(s);else{const{width:l,height:c}=this.getDrawingBufferSize();n.viewport(0,0,l,c)}if(s.scissor)this.updateScissor(s);else{const{width:l,height:c}=this.getDrawingBufferSize();n.scissor(0,0,l,c)}}this.prepareTimestampBuffer(ps.RENDER,this.getTimestampUID(e))}resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueries:n,currentOcclusionQueryObjects:i}=t;if(n&&i){const s=new WeakSet,{gl:o}=this;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueries=null;const a=()=>{let l=0;for(let c=0;c<n.length;c++){const u=n[c];u!==null&&o.getQueryParameter(u,o.QUERY_RESULT_AVAILABLE)&&(o.getQueryParameter(u,o.QUERY_RESULT)===0&&s.add(i[c]),n[c]=null,o.deleteQuery(u),l++)}l<n.length?requestAnimationFrame(a):t.occluded=s};a()}}isOccluded(e,t){const n=this.get(e);return n.occluded&&n.occluded.has(t)}updateViewport(e){const{state:t}=this,{x:n,y:i,width:s,height:o}=e.viewportValue;t.viewport(n,e.height-o-i,s,o)}updateScissor(e){const{state:t}=this,{x:n,y:i,width:s,height:o}=e.scissorValue;t.scissor(n,e.height-o-i,s,o)}setScissorTest(e){this.state.setScissorTest(e)}getClearColor(){const e=super.getClearColor();return e.r*=e.a,e.g*=e.a,e.b*=e.a,e}clear(e,t,n,i=null,s=!0,o=!0){const{gl:a,renderer:l}=this;i===null&&(i={textures:null,clearColorValue:this.getClearColor()});let c=0;if(e&&(c|=a.COLOR_BUFFER_BIT),t&&(c|=a.DEPTH_BUFFER_BIT),n&&(c|=a.STENCIL_BUFFER_BIT),c!==0){let u;i.clearColorValue?u=i.clearColorValue:u=this.getClearColor();const h=l.getClearDepth(),d=l.getClearStencil();if(t&&this.state.setDepthMask(!0),i.textures===null)a.clearColor(u.r,u.g,u.b,u.a),a.clear(c);else{if(s&&this._setFramebuffer(i),e)for(let f=0;f<i.textures.length;f++)f===0?a.clearBufferfv(a.COLOR,f,[u.r,u.g,u.b,u.a]):a.clearBufferfv(a.COLOR,f,[0,0,0,1]);t&&n?a.clearBufferfi(a.DEPTH_STENCIL,0,h,d):t?a.clearBufferfv(a.DEPTH,0,[h]):n&&a.clearBufferiv(a.STENCIL,0,[d]),s&&o&&this._resolveRenderTarget(i)}}}beginCompute(e){const{state:t,gl:n}=this;t.bindFramebuffer(n.FRAMEBUFFER,null),this.initTimestampQuery(ps.COMPUTE,this.getTimestampUID(e))}compute(e,t,n,i,s=null){const{state:o,gl:a}=this;this.discard===!1&&(o.enable(a.RASTERIZER_DISCARD),this.discard=!0);const{programGPU:l,transformBuffers:c,attributes:u}=this.get(i),h=this._getVaoKey(u),d=this.vaoCache[h];d===void 0?this.vaoCache[h]=this._createVao(u):o.setVertexState(d),o.useProgram(l),this._bindUniforms(n);const f=this._getTransformFeedback(c);a.bindTransformFeedback(a.TRANSFORM_FEEDBACK,f),a.beginTransformFeedback(a.POINTS),s=s!==null?s:t.count,Array.isArray(s)?(Yt("WebGLBackend.compute(): The count parameter must be a single number, not an array."),s=s[0]):s&&typeof s=="object"&&s.isIndirectStorageBufferAttribute&&(Yt("WebGLBackend.compute(): The count parameter must be a single number, not IndirectStorageBufferAttribute"),s=t.count),u[0].isStorageInstancedBufferAttribute?a.drawArraysInstanced(a.POINTS,0,1,s):a.drawArrays(a.POINTS,0,s),a.endTransformFeedback(),a.bindTransformFeedback(a.TRANSFORM_FEEDBACK,null);for(let p=0;p<c.length;p++){const g=c[p];g.pbo&&this.has(g.pbo)&&this.textureUtils.copyBufferToTexture(g.transformBuffer,g.pbo),g.switchBuffers()}}finishCompute(e){const{state:t,gl:n}=this;this.discard=!1,t.disable(n.RASTERIZER_DISCARD),this.prepareTimestampBuffer(ps.COMPUTE,this.getTimestampUID(e)),this._currentContext&&this._setFramebuffer(this._currentContext)}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.isArrayTexture&&e.camera.isArrayCamera}_draw(e,t,n,i,s,o){if(e.isBatchedMesh)if(this.hasFeature("WEBGL_multi_draw")===!1){const{gl:a}=this,l=a.getUniformLocation(o,"nodeUniformDrawId"),c=e._multiDrawStarts,u=e._multiDrawCounts,h=e._multiDrawCount;for(let d=0;d<h;d++)a.uniform1ui(l,d),t.render(c[d],u[d])}else t.renderMultiDraw(e._multiDrawStarts,e._multiDrawCounts,e._multiDrawCount);else s>1?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<ie;H++){const ce=l.createBuffer();L[0]=H,l.bindBuffer(l.UNIFORM_BUFFER,ce),l.bufferData(l.UNIFORM_BUFFER,L,l.STATIC_DRAW),B.push(ce)}A.indexesGPU=B}let P=0;e:for(const L of e.getBindings())for(const B of L.bindings){if(B===R)break e;(B.isUniformsGroup||B.isUniformBuffer)&&P++}const N=this.renderer.getPixelRatio(),U=this._currentContext.renderTarget,G=this._isRenderCameraDepthArray(this._currentContext),V=this._currentContext.activeCubeFace;if(G){const L=this.get(U.depthTexture);if(L.clearedRenderId!==this.renderer._nodes.nodeFrame.renderId){L.clearedRenderId=this.renderer._nodes.nodeFrame.renderId;const{stencilBuffer:B}=U;for(let H=0,ie=y.length;H<ie;H++)this.renderer._activeCubeFace=H,this._currentContext.activeCubeFace=H,this._setFramebuffer(this._currentContext),this.clear(!1,!0,B,this._currentContext,!1,!1);this.renderer._activeCubeFace=V,this._currentContext.activeCubeFace=V}}for(let L=0,B=y.length;L<B;L++){const H=y[L];if(t.layers.test(H.layers)){G&&(this.renderer._activeCubeFace=L,this._currentContext.activeCubeFace=L,this._setFramebuffer(this._currentContext));const ie=H.viewport;if(ie!==void 0){const ce=ie.x*N,ve=ie.y*N,Ce=ie.width*N,ke=ie.height*N;c.viewport(Math.floor(ce),Math.floor(e.context.height-ke-ve),Math.floor(Ce),Math.floor(ke))}c.bindBufferBase(l.UNIFORM_BUFFER,P,A.indexesGPU[L]),this._draw(t,v,T,S,E,a)}this._currentContext.activeCubeFace=V,this.renderer._activeCubeFace=V}}else this._draw(t,v,T,S,E,a)}needsRenderUpdate(){return!1}getRenderCacheKey(){return""}createDefaultTexture(e){this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e,t=!1){this.textureUtils.destroyTexture(e,t)}async copyTextureToBuffer(e,t,n,i,s,o){return this.textureUtils.copyTextureToBuffer(e,t,n,i,s,o)}updateSampler(){return""}createNodeBuilder(e,t){return new tI(e,t)}createProgram(e){const t=this.gl,{stage:n,code:i}=e,s=n==="fragment"?t.createShader(t.FRAGMENT_SHADER):t.createShader(t.VERTEX_SHADER);t.shaderSource(s,i),t.compileShader(s),this.set(e,{shaderGPU:s})}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){const n=this.gl,i=e.pipeline,{fragmentProgram:s,vertexProgram:o}=i,a=n.createProgram(),l=this.get(s).shaderGPU,c=this.get(o).shaderGPU;if(n.attachShader(a,l),n.attachShader(a,c),n.linkProgram(a),this.set(i,{programGPU:a,fragmentShader:l,vertexShader:c}),t!==null&&this.parallel){const u=new Promise(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<o;a++){const l=a+1;i.push(`${l===t?">":" "} ${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;m<u.length;m++){const _=u[m];h.push(_.varyingName),d.push(_.attributeNode)}i.attachShader(a,l),i.attachShader(a,c),i.transformFeedbackVaryings(a,h,i.SEPARATE_ATTRIBS),i.linkProgram(a),i.getProgramParameter(a,i.LINK_STATUS)===!1&&this._logProgramError(a,l,c),n.useProgram(a),this._setupBindings(t,a);const f=o.attributes,p=[],g=[];for(let m=0;m<f.length;m++){const _=f[m].node.attribute;p.push(_),this.has(_)||this.attributeUtils.createAttribute(_,i.ARRAY_BUFFER)}for(let m=0;m<d.length;m++){const _=d[m].attribute;this.has(_)||this.attributeUtils.createAttribute(_,i.ARRAY_BUFFER);const x=this.get(_);g.push(x)}this.set(e,{programGPU:a,transformBuffers:g,attributes:p})}createBindings(e,t){if(this._knownBindings.has(t)===!1){this._knownBindings.add(t);let n=0,i=0;for(const s of t){this.set(s,{textures:i,uniformBuffers:n});for(const o of s.bindings)o.isUniformBuffer&&n++,o.isSampledTexture&&i++}}this.updateBindings(e,t)}updateBindings(e){const{gl:t}=this;for(const n of e.bindings){const i=this.get(n);if(n.isUniformsGroup||n.isUniformBuffer){const s=n.buffer;let{bufferGPU:o}=this.get(s);o===void 0?(o=t.createBuffer(),t.bindBuffer(t.UNIFORM_BUFFER,o),t.bufferData(t.UNIFORM_BUFFER,s.byteLength,t.DYNAMIC_DRAW),this.set(s,{bufferGPU:o})):t.bindBuffer(t.UNIFORM_BUFFER,o);const a=n.updateRanges;if(t.bindBuffer(t.UNIFORM_BUFFER,o),a.length===0)t.bufferData(t.UNIFORM_BUFFER,s,t.DYNAMIC_DRAW);else{const l=Pu(s),c=l?1:s.BYTES_PER_ELEMENT;for(let u=0,h=a.length;u<h;u++){const d=a[u],f=d.start*c,p=d.count*c,g=f*(l?s.BYTES_PER_ELEMENT:1);t.bufferSubData(t.UNIFORM_BUFFER,g,s,f,p)}}i.bufferGPU=o,this.set(n,i)}else if(n.isSampledTexture){const{textureGPU:s,glTextureType:o}=this.get(n.texture);i.textureGPU=s,i.glTextureType=o,this.set(n,i)}}}updateBinding(e){const t=this.gl;if(e.isUniformsGroup||e.isUniformBuffer){const i=this.get(e).bufferGPU,s=e.buffer,o=e.updateRanges;if(t.bindBuffer(t.UNIFORM_BUFFER,i),o.length===0)t.bufferData(t.UNIFORM_BUFFER,s,t.DYNAMIC_DRAW);else{const a=Pu(s),l=a?1:s.BYTES_PER_ELEMENT;for(let c=0,u=o.length;c<u;c++){const h=o[c],d=h.start*l,f=h.count*l,p=d*(a?s.BYTES_PER_ELEMENT:1);t.bufferSubData(t.UNIFORM_BUFFER,p,s,d,f)}}}}createIndexAttribute(e){const t=this.gl;this.attributeUtils.createAttribute(e,t.ELEMENT_ARRAY_BUFFER)}createAttribute(e){if(this.has(e))return;const t=this.gl;this.attributeUtils.createAttribute(e,t.ARRAY_BUFFER)}createStorageAttribute(e){if(this.has(e))return;const t=this.gl;this.attributeUtils.createAttribute(e,t.ARRAY_BUFFER)}updateAttribute(e){this.attributeUtils.updateAttribute(e)}destroyAttribute(e){this.attributeUtils.destroyAttribute(e)}hasFeature(e){const t=Object.keys(z_).filter(i=>z_[i]===e),n=this.extensions;for(let i=0;i<t.length;i++)if(n.has(t[i]))return!0;return!1}copyTextureToTexture(e,t,n=null,i=null,s=0,o=0){this.textureUtils.copyTextureToTexture(e,t,n,i,s,o)}copyFramebufferToTexture(e,t,n){this.textureUtils.copyFramebufferToTexture(e,t,n)}hasCompatibility(e){return e===_o.TEXTURE_COMPARE?!0:super.hasCompatibility(e)}initRenderTarget(e){const{gl:t,state:n}=this;this._setFramebuffer(e),n.bindFramebuffer(t.FRAMEBUFFER,null)}_setFramebuffer(e){const{gl:t,state:n}=this;let i=null;if(e.textures!==null){const s=e.renderTarget,o=this.get(s),{samples:a,depthBuffer:l,stencilBuffer:c}=s,u=s.isCubeRenderTarget===!0,h=s.isRenderTarget3D===!0,d=s.depth>1,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;R<T.length;R++){const P=T[R],N=this.get(P);N.renderTarget=e.renderTarget,N.cacheKey=S;const U=t.COLOR_ATTACHMENT0+R;if(s.multiview)x.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,U,N.textureGPU,0,a,0,2);else if(h||d){const G=this.renderer._activeCubeFace,V=this.renderer._activeMipmapLevel;t.framebufferTextureLayer(t.FRAMEBUFFER,U,N.textureGPU,V,G)}else if(v)_.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,U,t.TEXTURE_2D,N.textureGPU,0,a);else{const G=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,U,t.TEXTURE_2D,N.textureGPU,G)}}}const y=c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(s._autoAllocateDepthBuffer===!0){const R=t.createRenderbuffer();this.textureUtils.setupRenderBufferStorage(R,e,0,v),o.xrDepthRenderbuffer=R,A.push(c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT),t.bindRenderbuffer(t.RENDERBUFFER,R),t.framebufferRenderbuffer(t.FRAMEBUFFER,y,t.RENDERBUFFER,R)}else if(e.depthTexture!==null){A.push(c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT);const R=this.get(e.depthTexture);if(R.renderTarget=e.renderTarget,R.cacheKey=S,s.multiview)x.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,y,R.textureGPU,0,a,0,2);else if(p&&v)_.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,y,t.TEXTURE_2D,R.textureGPU,0,a);else if(e.depthTexture.isArrayTexture){const P=this.renderer._activeCubeFace;t.framebufferTextureLayer(t.FRAMEBUFFER,y,R.textureGPU,0,P)}else if(e.depthTexture.isCubeTexture){const P=this.renderer._activeCubeFace;t.framebufferTexture2D(t.FRAMEBUFFER,y,t.TEXTURE_CUBE_MAP_POSITIVE_X+P,R.textureGPU,0)}else t.framebufferTexture2D(t.FRAMEBUFFER,y,t.TEXTURE_2D,R.textureGPU,0)}o.depthInvalidationArray=A}else{if(this._isRenderCameraDepthArray(e)){n.bindFramebuffer(t.FRAMEBUFFER,E);const A=this.renderer._activeCubeFace,y=this.get(e.depthTexture),R=c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;t.framebufferTextureLayer(t.FRAMEBUFFER,R,y.textureGPU,0,A)}if((f||v||s.multiview)&&s._isOpaqueFramebuffer!==!0){n.bindFramebuffer(t.FRAMEBUFFER,E);const A=this.get(e.textures[0]);s.multiview?x.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,A.textureGPU,0,a,0,2):v?_.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,A.textureGPU,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,A.textureGPU,0);const y=c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(s._autoAllocateDepthBuffer===!0){const R=o.xrDepthRenderbuffer;t.bindRenderbuffer(t.RENDERBUFFER,R),t.framebufferRenderbuffer(t.FRAMEBUFFER,y,t.RENDERBUFFER,R)}else{const R=this.get(e.depthTexture);s.multiview?x.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,y,R.textureGPU,0,a,0,2):v?_.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,y,t.TEXTURE_2D,R.textureGPU,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,y,t.TEXTURE_2D,R.textureGPU,0)}}}if(a>0&&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;R<y.length;R++){A[R]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,A[R]),T.push(t.COLOR_ATTACHMENT0+R);const P=e.textures[R],N=this.get(P);t.renderbufferStorageMultisample(t.RENDERBUFFER,a,N.glInternalFormat,e.width,e.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+R,t.RENDERBUFFER,A[R])}if(t.bindRenderbuffer(t.RENDERBUFFER,null),o.msaaFrameBuffer=g,o.msaaRenderbuffers=A,l&&m===void 0){m=t.createRenderbuffer(),this.textureUtils.setupRenderBufferStorage(m,e,a),o.depthRenderbuffer=m;const R=c?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;T.push(R)}o.invalidationArray=T}i=o.msaaFrameBuffer}else i=E;n.drawBuffers(e,E)}n.bindFramebuffer(t.FRAMEBUFFER,i)}_getVaoKey(e){let t="";for(let n=0;n<e.length;n++){const i=this.get(e[n]);t+=":"+i.id}return t}_createVao(e){const{gl:t}=this,n=t.createVertexArray();t.bindVertexArray(n);for(let i=0;i<e.length;i++){const s=e[i],o=this.get(s);t.bindBuffer(t.ARRAY_BUFFER,o.bufferGPU),t.enableVertexAttribArray(i);let a,l;s.isInterleavedBufferAttribute===!0?(a=s.data.stride*o.bytesPerElement,l=s.offset*o.bytesPerElement):(a=0,l=0),o.isInteger?t.vertexAttribIPointer(i,s.itemSize,o.type,a,l):t.vertexAttribPointer(i,s.itemSize,o.type,s.normalized,a,l),s.isInstancedBufferAttribute&&!s.isInterleavedBufferAttribute?t.vertexAttribDivisor(i,s.meshPerAttribute):s.isInterleavedBufferAttribute&&s.data.isInstancedInterleavedBuffer&&t.vertexAttribDivisor(i,s.data.meshPerAttribute)}return t.bindBuffer(t.ARRAY_BUFFER,null),n}_getTransformFeedback(e){let t="";for(let s=0;s<e.length;s++)t+=":"+e[s].id;let n=this.transformFeedbackCache[t];if(n!==void 0)return n;const{gl:i}=this;n=i.createTransformFeedback(),i.bindTransformFeedback(i.TRANSFORM_FEEDBACK,n);for(let s=0;s<e.length;s++){const o=e[s];i.bindBufferBase(i.TRANSFORM_FEEDBACK_BUFFER,s,o.transformBuffer)}return i.bindTransformFeedback(i.TRANSFORM_FEEDBACK,null),this.transformFeedbackCache[t]=n,n}_setupBindings(e,t){const n=this.gl;let i=0,s=0;for(const o of e)for(const a of o.bindings)if(a.isUniformsGroup||a.isUniformBuffer){const l=i++,c=n.getUniformBlockIndex(t,a.name);n.uniformBlockBinding(t,c,l)}else if(a.isSampledTexture){const l=s++,c=n.getUniformLocation(t,a.name);n.uniform1i(c,l)}}_bindUniforms(e){const{gl:t,state:n}=this;let i=0,s=0;for(const o of e)for(const a of o.bindings){const l=this.get(a);if(a.isUniformsGroup||a.isUniformBuffer){const c=i++;n.bindBufferBase(t.UNIFORM_BUFFER,c,l.bufferGPU)}else if(a.isSampledTexture){const c=s++;n.bindTexture(l.glTextureType,l.textureGPU,t.TEXTURE0+c)}}}_resolveRenderTarget(e){const{gl:t,state:n}=this,i=e.renderTarget;if(e.textures!==null&&i){const s=this.get(i);if(i.samples>0&&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;d<u.length;d++)t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0+d,t.RENDERBUFFER,null),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+d,t.TEXTURE_2D,null,0);for(let d=0;d<u.length;d++){if(h){const{textureGPU:f}=this.get(u[d]);t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,c[d]),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,f,0)}if(e.scissor){const{x:f,y:p,width:g,height:m}=e.scissorValue,_=e.height-m-p;t.blitFramebuffer(f,_,f+g,_+m,f,_,f+g,_+m,a,t.NEAREST)}else t.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,a,t.NEAREST)}if(h)for(let d=0;d<u.length;d++){const{textureGPU:f}=this.get(u[d]);t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0+d,t.RENDERBUFFER,c[d]),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+d,t.TEXTURE_2D,f,0)}this._supportsInvalidateFramebuffer===!0&&t.invalidateFramebuffer(t.READ_FRAMEBUFFER,s.invalidationArray)}else if(i.resolveDepthBuffer===!1&&s.framebuffers){const o=s.framebuffers[e.getCacheKey()];n.bindFramebuffer(t.DRAW_FRAMEBUFFER,o),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,s.depthInvalidationArray)}}}_useMultisampledExtension(e){return e.multiview===!0?!0:e.samples>0&&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<uniform> 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<f32>;
|
|
|
|
@fragment
|
|
fn main_2d( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {
|
|
|
|
return textureSample( img2d, imgSampler, Varys.vTex );
|
|
|
|
}
|
|
|
|
@group( 0 ) @binding( 1 )
|
|
var img2dArray : texture_2d_array<f32>;
|
|
|
|
@fragment
|
|
fn main_2d_array( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {
|
|
|
|
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<f32>;
|
|
|
|
@fragment
|
|
fn main_cube( Varys: VarysStruct ) -> @location( 0 ) vec4<f32> {
|
|
|
|
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;o<e.mipLevelCount;o++)for(let a=0;a<e.depthOrArrayLayers;a++){const l=this.device.createBindGroup({layout:i,entries:[{binding:0,resource:this.mipmapSampler},{binding:1,resource:e.createView({dimension:t,baseMipLevel:o-1,mipLevelCount:1})},{binding:2,resource:{buffer:this.noFlipUniformBuffer}}]}),c={colorAttachments:[{view:e.createView({dimension:"2d",baseMipLevel:o,mipLevelCount:1,baseArrayLayer:a,arrayLayerCount:1}),loadOp:At.Clear,storeOp:Zn.Store}]},u=this.device.createRenderBundleEncoder({colorFormats:[e.format]});u.setPipeline(n),u.setBindGroup(0,l),u.draw(3,1,0,a),s.push({renderBundles:[u.finish()],passDescriptor:c})}return s}_mipmapRunBundles(e,t){const n=t.length;for(let i=0;i<n;i++){const s=t[i],o=e.beginRenderPass(s.passDescriptor);o.executeBundles(s.renderBundles),o.end()}}}const xI={[Zf]:"never",[Ku]:"less",[Qf]:"equal",[Dr]:"less-equal",[jl]:"greater",[$s]:"greater-equal",[ep]:"always",[Jf]:"not-equal"},yI=[0,1,3,2,4,5];class vI{constructor(e){this.backend=e,this._passUtils=null,this.defaultTexture={},this.defaultCubeTexture={},this.defaultVideoFrame=null,this._samplerCache=new Map}updateSampler(e){const t=this.backend,n=e.minFilter+"-"+e.magFilter+"-"+e.wrapS+"-"+e.wrapT+"-"+(e.wrapR||"0")+"-"+e.anisotropy+"-"+(e.compareFunction||0);let i=this._samplerCache.get(n);if(i===void 0){const o={addressModeU:this._convertAddressMode(e.wrapS),addressModeV:this._convertAddressMode(e.wrapT),addressModeW:this._convertAddressMode(e.wrapR),magFilter:this._convertFilterMode(e.magFilter),minFilter:this._convertFilterMode(e.minFilter),mipmapFilter:this._convertFilterMode(e.minFilter),maxAnisotropy:1};e.isDepthTexture&&e.compareFunction===null&&(o.magFilter=rs.Nearest,o.minFilter=rs.Nearest,o.mipmapFilter=rs.Nearest),o.magFilter===rs.Linear&&o.minFilter===rs.Linear&&o.mipmapFilter===rs.Linear&&(o.maxAnisotropy=e.anisotropy),e.isDepthTexture&&e.compareFunction!==null&&t.hasCompatibility(_o.TEXTURE_COMPARE)&&(o.compare=xI[e.compareFunction]),i={sampler:t.device.createSampler(o),usedTimes:0},this._samplerCache.set(n,i)}const s=t.get(e);if(s.sampler!==i.sampler){if(s.sampler!==void 0){const o=this._samplerCache.get(s.samplerKey);o.usedTimes--,o.usedTimes===0&&this._samplerCache.delete(s.samplerKey)}s.samplerKey=n,s.sampler=i.sampler,i.usedTimes++}return n}createDefaultTexture(e){let t;const n=Cf(e,this.backend.device);e.isCubeTexture?t=this._getDefaultCubeTextureGPU(n):t=this._getDefaultTextureGPU(n),this.backend.get(e).texture=t}createTexture(e,t={}){const n=this.backend,i=n.get(e);if(i.initialized)throw new Error("WebGPUTextureUtils: Texture already initialized.");if(e.isExternalTexture){i.texture=e.sourceTexture,i.initialized=!0;return}t.needsMipmaps===void 0&&(t.needsMipmaps=!1),t.levels===void 0&&(t.levels=1),t.depth===void 0&&(t.depth=1);const{width:s,height:o,depth:a,levels:l}=t;e.isFramebufferTexture&&(t.renderTarget?t.format=this.backend.utils.getCurrentColorFormat(t.renderTarget):t.format=this.backend.utils.getPreferredCanvasFormat());const c=this._getDimension(e),u=e.internalFormat||t.format||Cf(e,n.device);i.format=u;const{samples:h,primarySamples:d,isMSAA:f}=n.utils.getTextureSampleData(e);let p=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC;e.isStorageTexture===!0&&(p|=GPUTextureUsage.STORAGE_BINDING),e.isCompressedTexture!==!0&&e.isCompressedArrayTexture!==!0&&u!==D.RGB9E5UFloat&&(p|=GPUTextureUsage.RENDER_ATTACHMENT);const g={label:e.name,size:{width:s,height:o,depthOrArrayLayers:a},mipLevelCount:l,sampleCount:d,dimension:c,format:u,usage:p};if(u===void 0){ee("WebGPURenderer: Texture format not supported."),this.createDefaultTexture(e);return}e.isCubeTexture&&(g.textureBindingViewDimension=zn.Cube);try{i.texture=n.device.createTexture(g)}catch{ee("WebGPURenderer: Failed to create texture with descriptor:",g),this.createDefaultTexture(e);return}if(f){const m=Object.assign({},g);m.label=m.label+"-msaa",m.sampleCount=h,m.mipLevelCount=1,i.msaaTexture=n.device.createTexture(m)}i.initialized=!0,i.textureDescriptorGPU=g}destroyTexture(e,t=!1){const n=this.backend,i=n.get(e);i.texture!==void 0&&t===!1&&i.texture.destroy(),i.msaaTexture!==void 0&&i.msaaTexture.destroy(),n.delete(e)}generateMipmaps(e,t=null){const n=this.backend.get(e);this._generateMipmaps(n.texture,t)}getColorBuffer(){const e=this.backend,t=e.renderer.getCanvasTarget(),{width:n,height:i}=e.getDrawingBufferSize(),s=e.renderer.currentSamples,o=t.colorTexture,a=e.get(o);if(o.width===n&&o.height===i&&o.samples===s)return a.texture;let l=a.texture;return l&&l.destroy(),l=e.device.createTexture({label:"colorBuffer",size:{width:n,height:i,depthOrArrayLayers:1},sampleCount:e.utils.getSampleCount(e.renderer.currentSamples),format:e.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC}),o.source.width=n,o.source.height=i,o.samples=s,a.texture=l,l}getDepthBuffer(e=!0,t=!1){const n=this.backend,i=n.renderer.getCanvasTarget(),{width:s,height:o}=n.getDrawingBufferSize(),a=n.renderer.currentSamples,l=i.depthTexture;if(l.width===s&&l.height===o&&l.samples===a&&l.depth===e&&l.stencil===t)return n.get(l).texture;const c=n.get(l).texture;let u,h;if(t?(u=$n,h=n.renderer.reversedDepthBuffer===!0?Zt:ui):e&&(u=Nn,h=n.renderer.reversedDepthBuffer===!0?Zt:wt),c!==void 0){if(l.image.width===s&&l.image.height===o&&l.format===u&&l.type===h&&l.samples===a)return c;this.destroyTexture(l)}return l.name="depthBuffer",l.format=u,l.type=h,l.image.width=s,l.image.height=o,l.samples=a,this.createTexture(l,{width:s,height:o}),n.get(l).texture}updateTexture(e,t){const n=this.backend.get(e),i=e.mipmaps,{textureDescriptorGPU:s}=n;if(!(e.isRenderTargetTexture||s===void 0)){if(e.isDataTexture)if(i.length>0)for(let o=0,a=i.length;o<a;o++){const l=i[o];this._copyBufferToTexture(l,n.texture,s,0,e.flipY,0,o)}else this._copyBufferToTexture(t.image,n.texture,s,0,e.flipY);else if(e.isArrayTexture||e.isDataArrayTexture||e.isData3DTexture)if(e.layerUpdates&&e.layerUpdates.size>0){for(const o of e.layerUpdates)this._copyBufferToTexture(t.image,n.texture,s,o,e.flipY,o);e.clearLayerUpdates()}else for(let o=0;o<t.image.depth;o++)this._copyBufferToTexture(t.image,n.texture,s,o,e.flipY,o);else if(e.isCompressedTexture||e.isCompressedArrayTexture)this._copyCompressedBufferToTexture(e.mipmaps,n.texture,s);else if(e.isCubeTexture)this._copyCubeMapToTexture(e,n.texture,s);else if(e.isHTMLTexture){const o=this.backend.device,a=this.backend.renderer.domElement,l=e.image;if(typeof o.queue.copyElementImageToTexture!="function")return;if(!n.hasPaintCallback){n.hasPaintCallback=!0,a.requestPaint();return}const c=s.size.width,u=s.size.height;o.queue.copyElementImageToTexture(l,c,u,{texture:n.texture}),e.flipY&&this._flipY(n.texture,s)}else if(i.length>0)for(let o=0,a=i.length;o<a;o++){const l=i[o];this._copyImageToTexture(l,n.texture,s,0,e.flipY,e.premultiplyAlpha,o)}else this._copyImageToTexture(t.image,n.texture,s,0,e.flipY,e.premultiplyAlpha);n.version=e.version}}async copyTextureToBuffer(e,t,n,i,s,o){const a=this.backend.device,l=this.backend.get(e),c=l.texture,u=l.textureDescriptorGPU.format,h=this._getBytesPerTexel(u);let d=i*h;d=Math.ceil(d/256)*256;const f=a.createBuffer({size:(s-1)*d+i*h,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),p=a.createCommandEncoder();p.copyTextureToBuffer({texture:c,origin:{x:t,y:n,z:o}},{buffer:f,bytesPerRow:d},{width:i,height:s});const g=this._getTypedArrayType(u);a.queue.submit([p.finish()]),await f.mapAsync(GPUMapMode.READ);const m=f.getMappedRange().slice();return f.destroy(),new g(m)}dispose(){this._samplerCache.clear()}_getDefaultTextureGPU(e){let t=this.defaultTexture[e];if(t===void 0){const n=new pn;n.minFilter=bt,n.magFilter=bt,this.createTexture(n,{width:1,height:1,format:e}),this.defaultTexture[e]=t=n}return this.backend.get(t).texture}_getDefaultCubeTextureGPU(e){let t=this.defaultCubeTexture[e];if(t===void 0){const n=new Ga;n.minFilter=bt,n.magFilter=bt,this.createTexture(n,{width:1,height:1,depth:6}),this.defaultCubeTexture[e]=t=n}return this.backend.get(t).texture}_copyCubeMapToTexture(e,t,n){const i=e.images,s=e.mipmaps;for(let o=0;o<6;o++){const a=i[o],l=e.flipY===!0?yI[o]:o;a.isDataTexture?this._copyBufferToTexture(a.image,t,n,l,e.flipY):this._copyImageToTexture(a,t,n,l,e.flipY,e.premultiplyAlpha);for(let c=0;c<s.length;c++){const h=s[c].images[o];h.isDataTexture?this._copyBufferToTexture(h.image,t,n,l,e.flipY,0,c+1):this._copyImageToTexture(h,t,n,l,e.flipY,e.premultiplyAlpha,c+1)}}}_copyImageToTexture(e,t,n,i,s,o,a=0){const l=this.backend.device,c=a>0?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<e.length;a++){const l=e[a],c=l.width,u=l.height,h=o?n.size.depthOrArrayLayers:1,d=Math.ceil(c/s.width)*s.byteLength,f=d*Math.ceil(u/s.height);for(let p=0;p<h;p++)i.queue.writeTexture({texture:t,mipLevel:a,origin:{x:0,y:0,z:p}},l.data,{offset:p*f,bytesPerRow:d,rowsPerImage:Math.ceil(u/s.height)},{width:Math.ceil(c/s.width)*s.width,height:Math.ceil(u/s.height)*s.height,depthOrArrayLayers:1})}}_getBlockData(e){if(e===D.BC1RGBAUnorm||e===D.BC1RGBAUnormSRGB)return{byteLength:8,width:4,height:4};if(e===D.BC2RGBAUnorm||e===D.BC2RGBAUnormSRGB)return{byteLength:16,width:4,height:4};if(e===D.BC3RGBAUnorm||e===D.BC3RGBAUnormSRGB)return{byteLength:16,width:4,height:4};if(e===D.BC4RUnorm||e===D.BC4RSnorm)return{byteLength:8,width:4,height:4};if(e===D.BC5RGUnorm||e===D.BC5RGSnorm)return{byteLength:16,width:4,height:4};if(e===D.BC6HRGBUFloat||e===D.BC6HRGBFloat)return{byteLength:16,width:4,height:4};if(e===D.BC7RGBAUnorm||e===D.BC7RGBAUnormSRGB)return{byteLength:16,width:4,height:4};if(e===D.ETC2RGB8Unorm||e===D.ETC2RGB8UnormSRGB)return{byteLength:8,width:4,height:4};if(e===D.ETC2RGB8A1Unorm||e===D.ETC2RGB8A1UnormSRGB)return{byteLength:8,width:4,height:4};if(e===D.ETC2RGBA8Unorm||e===D.ETC2RGBA8UnormSRGB)return{byteLength:16,width:4,height:4};if(e===D.EACR11Unorm)return{byteLength:8,width:4,height:4};if(e===D.EACR11Snorm)return{byteLength:8,width:4,height:4};if(e===D.EACRG11Unorm)return{byteLength:16,width:4,height:4};if(e===D.EACRG11Snorm)return{byteLength:16,width:4,height:4};if(e===D.ASTC4x4Unorm||e===D.ASTC4x4UnormSRGB)return{byteLength:16,width:4,height:4};if(e===D.ASTC5x4Unorm||e===D.ASTC5x4UnormSRGB)return{byteLength:16,width:5,height:4};if(e===D.ASTC5x5Unorm||e===D.ASTC5x5UnormSRGB)return{byteLength:16,width:5,height:5};if(e===D.ASTC6x5Unorm||e===D.ASTC6x5UnormSRGB)return{byteLength:16,width:6,height:5};if(e===D.ASTC6x6Unorm||e===D.ASTC6x6UnormSRGB)return{byteLength:16,width:6,height:6};if(e===D.ASTC8x5Unorm||e===D.ASTC8x5UnormSRGB)return{byteLength:16,width:8,height:5};if(e===D.ASTC8x6Unorm||e===D.ASTC8x6UnormSRGB)return{byteLength:16,width:8,height:6};if(e===D.ASTC8x8Unorm||e===D.ASTC8x8UnormSRGB)return{byteLength:16,width:8,height:8};if(e===D.ASTC10x5Unorm||e===D.ASTC10x5UnormSRGB)return{byteLength:16,width:10,height:5};if(e===D.ASTC10x6Unorm||e===D.ASTC10x6UnormSRGB)return{byteLength:16,width:10,height:6};if(e===D.ASTC10x8Unorm||e===D.ASTC10x8UnormSRGB)return{byteLength:16,width:10,height:8};if(e===D.ASTC10x10Unorm||e===D.ASTC10x10UnormSRGB)return{byteLength:16,width:10,height:10};if(e===D.ASTC12x10Unorm||e===D.ASTC12x10UnormSRGB)return{byteLength:16,width:12,height:10};if(e===D.ASTC12x12Unorm||e===D.ASTC12x12UnormSRGB)return{byteLength:16,width:12,height:12}}_convertAddressMode(e){let t=Hd.ClampToEdge;return e===ro?t=Hd.Repeat:e===oo&&(t=Hd.MirrorRepeat),t}_convertFilterMode(e){let t=rs.Linear;return(e===bt||e===Kf||e===Gs)&&(t=rs.Nearest),t}_getBytesPerTexel(e){if(e===D.R8Unorm||e===D.R8Snorm||e===D.R8Uint||e===D.R8Sint)return 1;if(e===D.R16Uint||e===D.R16Sint||e===D.R16Float||e===D.RG8Unorm||e===D.RG8Snorm||e===D.RG8Uint||e===D.RG8Sint||e===D.R16Unorm||e===D.R16Snorm)return 2;if(e===D.R32Uint||e===D.R32Sint||e===D.R32Float||e===D.RG16Uint||e===D.RG16Sint||e===D.RG16Float||e===D.RGBA8Unorm||e===D.RGBA8UnormSRGB||e===D.RGBA8Snorm||e===D.RGBA8Uint||e===D.RGBA8Sint||e===D.BGRA8Unorm||e===D.BGRA8UnormSRGB||e===D.RG16Unorm||e===D.RG16Snorm||e===D.RGB9E5UFloat||e===D.RGB10A2Unorm||e===D.RG11B10UFloat||e===D.Depth32Float||e===D.Depth24Plus||e===D.Depth24PlusStencil8||e===D.Depth32FloatStencil8)return 4;if(e===D.RG32Uint||e===D.RG32Sint||e===D.RG32Float||e===D.RGBA16Uint||e===D.RGBA16Sint||e===D.RGBA16Float||e===D.RGBA16Unorm||e===D.RGBA16Snorm)return 8;if(e===D.RGBA32Uint||e===D.RGBA32Sint||e===D.RGBA32Float)return 16}_getTypedArrayType(e){if(e===D.R8Uint)return Uint8Array;if(e===D.R8Sint)return Int8Array;if(e===D.R8Unorm)return Uint8Array;if(e===D.R8Snorm)return Int8Array;if(e===D.RG8Uint)return Uint8Array;if(e===D.RG8Sint)return Int8Array;if(e===D.RG8Unorm)return Uint8Array;if(e===D.RG8Snorm)return Int8Array;if(e===D.RGBA8Uint)return Uint8Array;if(e===D.RGBA8Sint)return Int8Array;if(e===D.RGBA8Unorm||e===D.RGBA8UnormSRGB)return Uint8Array;if(e===D.RGBA8Snorm)return Int8Array;if(e===D.R16Uint)return Uint16Array;if(e===D.R16Sint)return Int16Array;if(e===D.RG16Uint)return Uint16Array;if(e===D.RG16Sint)return Int16Array;if(e===D.RGBA16Uint)return Uint16Array;if(e===D.RGBA16Sint)return Int16Array;if(e===D.R16Float||e===D.RG16Float||e===D.RGBA16Float||e===D.R16Unorm)return Uint16Array;if(e===D.R16Snorm)return Int16Array;if(e===D.RG16Unorm)return Uint16Array;if(e===D.RG16Snorm)return Int16Array;if(e===D.RGBA16Unorm)return Uint16Array;if(e===D.RGBA16Snorm)return Int16Array;if(e===D.R32Uint)return Uint32Array;if(e===D.R32Sint)return Int32Array;if(e===D.R32Float)return Float32Array;if(e===D.RG32Uint)return Uint32Array;if(e===D.RG32Sint)return Int32Array;if(e===D.RG32Float)return Float32Array;if(e===D.RGBA32Uint)return Uint32Array;if(e===D.RGBA32Sint)return Int32Array;if(e===D.RGBA32Float)return Float32Array;if(e===D.BGRA8Unorm||e===D.BGRA8UnormSRGB)return Uint8Array;if(e===D.RGB10A2Unorm||e===D.RGB9E5UFloat||e===D.RG11B10UFloat)return Uint32Array;if(e===D.Depth32Float)return Float32Array;if(e===D.Depth24Plus||e===D.Depth24PlusStencil8)return Uint32Array;if(e===D.Depth32FloatStencil8)return Float32Array}_getDimension(e){let t;return e.is3DTexture||e.isData3DTexture?t=j_.ThreeD:t=j_.TwoD,t}}function Cf(r,e){const t=r.format,n=r.type,i=r.normalized,s=r.colorSpace,o=Xe.getTransfer(s);let a,l=!1;if(i&&(l=e.features.has(qu.TextureFormatsTier1),l===!1&&ee("WebGPURenderer: Unable to use normalized textures without texture-formats-tier1 feature.")),r.isCompressedTexture===!0||r.isCompressedArrayTexture===!0)switch(t){case yr:case vr:a=o===Ee?D.BC1RGBAUnormSRGB:D.BC1RGBAUnorm;break;case Sr:a=o===Ee?D.BC2RGBAUnormSRGB:D.BC2RGBAUnorm;break;case br:a=o===Ee?D.BC3RGBAUnormSRGB:D.BC3RGBAUnorm;break;case Ra:a=D.BC4RUnorm;break;case wa:a=D.BC4RSnorm;break;case wr:a=D.BC5RGUnorm;break;case Ca:a=D.BC5RGSnorm;break;case Aa:a=o===Ee?D.BC7RGBAUnormSRGB:D.BC7RGBAUnorm;break;case aa:case oa:a=o===Ee?D.ETC2RGB8UnormSRGB:D.ETC2RGB8Unorm;break;case la:a=o===Ee?D.ETC2RGBA8UnormSRGB:D.ETC2RGBA8Unorm;break;case ca:a=D.EACR11Unorm;break;case ua:a=D.EACR11Snorm;break;case Rr:a=D.EACRG11Unorm;break;case ha:a=D.EACRG11Snorm;break;case da:a=o===Ee?D.ASTC4x4UnormSRGB:D.ASTC4x4Unorm;break;case fa:a=o===Ee?D.ASTC5x4UnormSRGB:D.ASTC5x4Unorm;break;case pa:a=o===Ee?D.ASTC5x5UnormSRGB:D.ASTC5x5Unorm;break;case ma:a=o===Ee?D.ASTC6x5UnormSRGB:D.ASTC6x5Unorm;break;case ga:a=o===Ee?D.ASTC6x6UnormSRGB:D.ASTC6x6Unorm;break;case _a:a=o===Ee?D.ASTC8x5UnormSRGB:D.ASTC8x5Unorm;break;case xa:a=o===Ee?D.ASTC8x6UnormSRGB:D.ASTC8x6Unorm;break;case ya:a=o===Ee?D.ASTC8x8UnormSRGB:D.ASTC8x8Unorm;break;case va:a=o===Ee?D.ASTC10x5UnormSRGB:D.ASTC10x5Unorm;break;case Sa:a=o===Ee?D.ASTC10x6UnormSRGB:D.ASTC10x6Unorm;break;case ba:a=o===Ee?D.ASTC10x8UnormSRGB:D.ASTC10x8Unorm;break;case Ta:a=o===Ee?D.ASTC10x10UnormSRGB:D.ASTC10x10Unorm;break;case Ma:a=o===Ee?D.ASTC12x10UnormSRGB:D.ASTC12x10Unorm;break;case Ea:a=o===Ee?D.ASTC12x12UnormSRGB:D.ASTC12x12Unorm;break;case an:a=o===Ee?D.RGBA8UnormSRGB:D.RGBA8Unorm;break;default:ne("WebGPURenderer: Unsupported texture format.",t)}else switch(t){case an:switch(n){case _r:a=D.RGBA8Snorm;break;case xr:a=l?D.RGBA16Snorm:D.RGBA16Sint;break;case Ci:a=l?D.RGBA16Unorm:D.RGBA16Uint;break;case wt:a=D.RGBA32Uint;break;case Sn:a=D.RGBA32Sint;break;case $t:a=o===Ee?D.RGBA8UnormSRGB:D.RGBA8Unorm;break;case en:a=D.RGBA16Float;break;case Zt:a=D.RGBA32Float;break;default:ne("WebGPURenderer: Unsupported texture type with RGBAFormat.",n)}break;case Ba:switch(n){case rc:a=D.RGB9E5UFloat;break;case oc:a=D.RG11B10UFloat;break;default:ne("WebGPURenderer: Unsupported texture type with RGBFormat.",n)}break;case Oa:switch(n){case _r:a=D.R8Snorm;break;case xr:a=l?D.R16Snorm:D.R16Sint;break;case Ci:a=l?D.R16Unorm:D.R16Uint;break;case wt:a=D.R32Uint;break;case Sn:a=D.R32Sint;break;case $t:a=D.R8Unorm;break;case en:a=D.R16Float;break;case Zt:a=D.R32Float;break;default:ne("WebGPURenderer: Unsupported texture type with RedFormat.",n)}break;case Fn:switch(n){case _r:a=D.RG8Snorm;break;case xr:a=l?D.RG16Snorm:D.RG16Sint;break;case Ci:a=l?D.RG16Unorm:D.RG16Uint;break;case wt:a=D.RG32Uint;break;case Sn:a=D.RG32Sint;break;case $t:a=D.RG8Unorm;break;case en:a=D.RG16Float;break;case Zt:a=D.RG32Float;break;default:ne("WebGPURenderer: Unsupported texture type with RGFormat.",n)}break;case Nn:switch(n){case Ci:a=D.Depth16Unorm;break;case wt:a=D.Depth24Plus;break;case Zt:a=D.Depth32Float;break;default:ne("WebGPURenderer: Unsupported texture type with DepthFormat.",n)}break;case $n:switch(n){case ui:a=D.Depth24PlusStencil8;break;case Zt:e&&e.features.has(qu.Depth32FloatStencil8)===!1&&ne('WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.'),a=D.Depth32FloatStencil8;break;default:ne("WebGPURenderer: Unsupported texture type with DepthStencilFormat.",n)}break;case mo:switch(n){case Sn:a=D.R32Sint;break;case wt:a=D.R32Uint;break;default:ne("WebGPURenderer: Unsupported texture type with RedIntegerFormat.",n)}break;case go:switch(n){case Sn:a=D.RG32Sint;break;case wt:a=D.RG32Uint;break;default:ne("WebGPURenderer: Unsupported texture type with RGIntegerFormat.",n)}break;case ka:switch(n){case Sn:a=D.RGBA32Sint;break;case wt:a=D.RGBA32Uint;break;default:ne("WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.",n)}break;default:ne("WebGPURenderer: Unsupported texture format.",t)}return a}const SI=/^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\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<f32>":"vec2","vec2<i32>":"ivec2","vec2<u32>":"uvec2","vec2<bool>":"bvec2",vec2f:"vec2",vec2i:"ivec2",vec2u:"uvec2",vec2b:"bvec2","vec3<f32>":"vec3","vec3<i32>":"ivec3","vec3<u32>":"uvec3","vec3<bool>":"bvec3",vec3f:"vec3",vec3i:"ivec3",vec3u:"uvec3",vec3b:"bvec3","vec4<f32>":"vec4","vec4<i32>":"ivec4","vec4<u32>":"uvec4","vec4<bool>":"bvec4",vec4f:"vec4",vec4i:"ivec4",vec4u:"uvec4",vec4b:"bvec4","mat2x2<f32>":"mat2",mat2x2f:"mat2","mat3x3<f32>":"mat3",mat3x3f:"mat3","mat4x4<f32>":"mat4",mat4x4f:"mat4",sampler:"sampler",texture_1d:"texture",texture_2d:"texture",texture_2d_array:"texture",texture_multisampled_2d:"cubeTexture",texture_depth_2d:"depthTexture",texture_depth_2d_array:"depthTexture",texture_depth_multisampled_2d:"depthTexture",texture_depth_cube:"depthTexture",texture_depth_cube_array:"depthTexture",texture_3d:"texture3D",texture_cube:"cubeTexture",texture_cube_array:"cubeTexture",texture_storage_1d:"storageTexture",texture_storage_2d:"storageTexture",texture_storage_2d_array:"storageTexture",texture_storage_3d:"storageTexture"},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<n.length;u++){const{name:h,type:d}=n[u];let f=d;f.startsWith("ptr")?f="pointer":(f.startsWith("texture")&&(f=d.split("<")[0]),f=K_[f]),s.push(new $p(f,h))}const o=r.substring(e[0].length),a=e[3]||"void",l=e[1]!==void 0?e[1]:"";return{type:K_[a]||a,inputs:s,name:l,inputsCode:t,blockCode:o,outputType:a}}else throw new Error("FunctionNode: Function is not a WGSL code.")};class MI extends qp{constructor(e){const{type:t,inputs:n,name:i,inputsCode:s,blockCode:o,outputType:a}=TI(e);super(t,n,i),this.inputsCode=s,this.blockCode=o,this.outputType=a}getCode(e=this.name){const t=this.outputType!=="void"?"-> "+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<f32>",vec2:"vec2<f32>",ivec2:"vec2<i32>",uvec2:"vec2<u32>",bvec2:"vec2<bool>",vec3:"vec3<f32>",ivec3:"vec3<i32>",uvec3:"vec3<u32>",bvec3:"vec3<bool>",vec4:"vec4<f32>",ivec4:"vec4<i32>",uvec4:"vec4<u32>",bvec4:"vec4<bool>",mat2:"mat2x2<f32>",mat3:"mat3x3<f32>",mat4:"mat4x4<f32>"},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<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new An("fn tsl_equals_bvec3( a : vec3f, b : vec3f ) -> vec3<bool> { return vec3<bool>( a.x == b.x, a.y == b.y, a.z == b.z ); }"),equals_bvec4:new An("fn tsl_equals_bvec4( a : vec4f, b : vec4f ) -> vec4<bool> { return vec4<bool>( a.x == b.x, a.y == b.y, a.z == b.z, a.w == b.w ); }"),repeatWrapping_float:new 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<f32>, 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<f32>, 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<f32>",floatpack_snorm_2x16:"pack2x16snorm",floatpack_unorm_2x16:"pack2x16unorm",floatpack_float16_2x16:"pack2x16float",floatunpack_snorm_2x16:"unpack2x16snorm",floatunpack_unorm_2x16:"unpack2x16unorm",floatunpack_float16_2x16:"unpack2x16float"};let 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<u32>":a="vec2<u32>",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<f32>(${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<f32>(${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<u32>( 1, 1, 1 )":"vec2<u32>( 1, 1 )";s&&(n=`${n} + ${c}<f32>(${s}) / ${c}<f32>( ${l} )`);const h=`${c}<f32>( 0 )`,d=`${c}<f32>( ${l} - ${u} )`;return n=`${c}<u32>( clamp( floor( ${a}( ${n} ) * ${c}<f32>( ${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<f32>")+".xy"}getFragDepth(){return"output."+this.getBuiltin("frag_depth","depth","f32","output")}getClipDistance(){return"varyings.hw_clip_distances"}isFlipY(){return!1}enableDirective(e,t=this.shaderStage){(this.directives[t]||(this.directives[t]=new Set)).add(e)}getDirectives(e){const t=[],n=this.directives[e];if(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<f32, ${e} >`,"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<u32>","attribute"),this.getBuiltin("workgroup_id","workgroupId","vec3<u32>","attribute"),this.getBuiltin("local_invocation_id","localId","vec3<u32>","attribute"),this.getBuiltin("num_workgroups","numWorkgroups","vec3<u32>","attribute"),this.renderer.hasFeature("subgroups")&&(this.enableDirective("subgroups",e),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute"))),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<o;s++){const a=i[s],l=a.name,c=this.getType(a.type);t.push(`@location( ${s} ) ${l} : ${c}`)}}return t.join(`,
|
|
`)}getStructMembers(e){const t=[];for(const n of e.members){const i=e.output?"@location( "+n.index+" ) ":"";let s=this.getType(n.type);n.atomic&&(s="atomic< "+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="<private>");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<f32>","vertex"),e==="vertex"||e==="fragment"){const s=this.varyings,o=this.vars[e];let a=0;for(let l=0;l<s.length;l++){const c=s[l];if(c.needsInterpolation){let u=`@location( ${a++} )`;if(c.interpolationType){const h=c.interpolationSampling!==null?`, ${c.interpolationSampling} )`:" )";u+=` @interpolate( ${c.interpolationType}${h}`}else/^(int|uint|ivec|uvec)/.test(c.type)&&(u+=" @interpolate(flat, either)");t.push(`${u} ${c.name} : ${this.getType(c.type)}`)}else e==="vertex"&&o.includes(c)===!1&&o.push(c)}}const n=this.getBuiltins(e);n&&t.push(n);const i=t.join(`,
|
|
`);return e==="vertex"?this._getWGSLStruct("VaryingsStruct"," "+i):i}isCustomStruct(e){const t=e.value,n=e.node,i=(t.isBufferAttribute||t.isInstancedBufferAttribute)&&n.structTypeNode!==null,s=n.value&&n.value.array&&typeof n.value.itemSize=="number"&&n.value.array.length>n.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<f32>";else if(d.isDepthTexture===!0)t.compatibilityMode&&d.compareFunction===null?p=`texture${g}_2d<f32>`: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<f32>";else if(d.is3DTexture===!0||d.isData3DTexture===!0)p="texture_3d<f32>";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<private> output : "+i.returnType+";",s+=`return ${h.result};`;else{let f=" @location( 0 ) color: vec4<f32>";const p=this.getBuiltins("output");p&&(f+=`,
|
|
`+p),i.returnType="OutputStruct",i.structs+=this._getWGSLStruct("OutputStruct",f),i.structs+=`
|
|
var<private> 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<private> 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<private> 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<l.length;h++)l[h]===65535&&(l[h]=4294967295)}if(n.array=l,(n.isStorageBufferAttribute||n.isStorageInstancedBufferAttribute)&&n.itemSize===3){l=new l.constructor(n.count*4);for(let h=0;h<n.count;h++)l.set(n.array.subarray(h*3,h*3+3),h*4);n.itemSize=4,n.array=l,s._force3to4BytesAlignment=!0}const c=l.byteLength,u=c+(4-c%4)%4;o=a.createBuffer({label:n.name,size:u,usage:t,mappedAtCreation:!0}),new l.constructor(o.getMappedRange()).set(l),o.unmap(),s.buffer=o}}updateAttribute(e){const t=this._getBufferAttribute(e),n=this.backend,i=n.device,s=n.get(t),o=n.get(t).buffer;let a=t.array;if(s._force3to4BytesAlignment===!0){a=new a.constructor(t.count*4);for(let c=0;c<t.count;c++)a.set(t.array.subarray(c*3,c*3+3),c*4);t.array=a}const l=t.updateRanges;if(l.length===0)i.queue.writeBuffer(o,0,a,0);else{const c=Pu(a),u=c?1:a.BYTES_PER_ELEMENT;for(let h=0,d=l.length;h<d;h++){const f=l[h];let p,g;if(s._force3to4BytesAlignment===!0){const _=Math.floor(f.start/3),x=Math.ceil(f.count/3);p=_*4*u,g=x*4*u}else p=f.start*u,g=f.count*u;const m=p*(c?a.BYTES_PER_ELEMENT:1);i.queue.writeBuffer(o,m,a,p,g)}t.clearUpdateRanges()}}createShaderVertexBuffers(e){const t=e.getAttributes(),n=new Map;for(let i=0;i<t.length;i++){const s=t[i],o=s.array.BYTES_PER_ELEMENT,a=this._getBufferAttribute(s);let l=n.get(a);if(l===void 0){let h,d;s.isInterleavedBufferAttribute===!0?(h=s.data.stride*o,d=s.data.isInstancedInterleavedBuffer?pu.Instance:pu.Vertex):(h=s.itemSize*o,d=s.isInstancedBufferAttribute?pu.Instance:pu.Vertex),s.normalized===!1&&(s.array.constructor===Int16Array||s.array.constructor===Uint16Array)&&(h=4),l={arrayStride:h,attributes:[],stepMode:d},n.set(a,l)}const c=this._getVertexFormat(s),u=s.isInterleavedBufferAttribute===!0?s.offset*o:0;l.attributes.push({shaderLocation:i,offset:u,format:c})}return Array.from(n.values())}destroyAttribute(e){const t=this.backend;t.get(this._getBufferAttribute(e)).buffer.destroy(),t.delete(e)}async getArrayBufferAsync(e,t=null,n=0,i=-1){const s=this.backend,o=s.device,l=s.get(this._getBufferAttribute(e)).buffer,c=i===-1?l.size-n:i;let u;if(t!==null&&t.isReadbackBuffer){const f=s.get(t);if(t._mapped===!0)throw new Error("WebGPURenderer: ReadbackBuffer must be released before being used again.");if(t._mapped=!0,f.readBufferGPU===void 0){u=o.createBuffer({label:`${t.name}_readback`,size:t.maxByteLength,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});const p=()=>{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;c<u;c++){const h=o[c],d=h.start*l,f=h.count*l,p=d*(a?i.BYTES_PER_ELEMENT:1);n.queue.writeBuffer(s,p,i,d,f)}}}createBindGroupIndex(e,t){const i=this.backend.device,s=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,o=e[0],a=i.createBuffer({label:"bindingCameraIndex_"+o,size:16,usage:s});i.queue.writeBuffer(a,0,e,0);const l=[{binding:0,resource:{buffer:a}}];return i.createBindGroup({label:"bindGroupCameraIndex_"+o,layout:t,entries:l})}createBindGroup(e,t){const n=this.backend,i=n.device;let s=0;const o=[];for(const a of e.bindings){if(a.isUniformBuffer){const l=n.get(a);if(l.buffer===void 0){const c=a.byteLength,u=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,h=[];a.visibility&ms.VERTEX&&h.push("vertex"),a.visibility&ms.FRAGMENT&&h.push("fragment"),a.visibility&ms.COMPUTE&&h.push("compute");const d=`(${h.join(",")})`,f=i.createBuffer({label:`bindingBuffer${a.id}_${a.name}_${d}`,size:c,usage:u});l.buffer=f}o.push({binding:s,resource:{buffer:l.buffer}})}else if(a.isStorageBuffer){const l=n.get(a.attribute).buffer;o.push({binding:s,resource:{buffer:l}})}else if(a.isSampledTexture){const l=n.get(a.texture);let c;if(l.externalTexture!==void 0)c=i.importExternalTexture({source:l.externalTexture});else{const u=a.store?1:l.texture.mipLevelCount,h=a.store?a.mipLevel:0;let d=`view-${l.texture.width}-${l.texture.height}`;if(l.texture.depthOrArrayLayers>1&&(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;L<G.length;L++){const B=G[L],H=h.getTextureFormatGPU(B);let ie;if(V!==null)if(this.backend.compatibilityMode!==!0){const ce=V.getBlendMode(B.name);ce.blending===dx?ie=g:ce.blending!==Cn&&(ie=this._getBlending(ce))}else 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."),ie=g;else ie=g;x.push({format:H,blend:ie,writeMask:_})}}else{const G=h.getCurrentColorFormat(e.context);x.push({format:G,blend:g,writeMask:_})}const v=c.get(a).module,S=c.get(l).module,E=this._getPrimitiveState(n,s,i),T=this._getDepthCompare(i),A=h.getCurrentDepthStencilFormat(e.context),y=this._getSampleCount(e.context),R={label:`renderPipeline_${i.name||i.type}_${i.id}`,vertex:Object.assign({},v,{buffers:p}),fragment:Object.assign({},S,{targets:x}),primitive:E,multisample:{count:y,alphaToCoverageEnabled:i.alphaToCoverage&&y>1},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;f<c.length;f++){const p=this.get(c[f]),g={label:`colorAttachment_${f}`,baseMipLevel:e.activeMipmapLevel,mipLevelCount:1,baseArrayLayer:e.activeCubeFace,arrayLayerCount:1,dimension:zn.TwoD};if(n.isRenderTarget3D)h=e.activeCubeFace,g.baseArrayLayer=0,g.dimension=zn.ThreeD,g.depthOrArrayLayers=c[f].image.depth;else if(n.isRenderTarget&&c[f].image.depth>1)if(d===!0){const m=e.camera.cameras;for(let _=0;_<m.length;_++){const x={...g,baseArrayLayer:_,arrayLayerCount:1,dimension:zn.TwoD},v=p.texture.createView(x);u.push({view:v,resolveTarget:void 0,depthSlice:void 0})}}else g.dimension=zn.TwoDArray,g.depthOrArrayLayers=c[f].image.depth;if(d!==!0){const m=p.texture.createView(g);let _,x;p.msaaTexture!==void 0?(_=p.msaaTexture.createView(),x=m):(_=m,x=void 0),u.push({view:_,resolveTarget:x,depthSlice:h})}}if(a={textureViews:u},e.depth){const f=this.get(e.depthTexture),p={};(e.depthTexture.isArrayTexture||e.depthTexture.isCubeTexture)&&(p.dimension=zn.TwoD,p.arrayLayerCount=1,p.baseArrayLayer=e.activeCubeFace),a.depthStencilView=f.texture.createView(p)}s[o]=a,i.width=n.width,i.height=n.height,i.samples=n.samples,i.activeMipmapLevel=e.activeMipmapLevel,i.activeCubeFace=e.activeCubeFace}const l={colorAttachments:[]};for(let c=0;c<a.textureViews.length;c++){const u=a.textureViews[c];let h={r:0,g:0,b:0,a:1};c===0&&t.clearValue&&(h=t.clearValue),l.colorAttachments.push({view:u.view,depthSlice:u.depthSlice,resolveTarget:u.resolveTarget,loadOp:t.loadOp||At.Load,storeOp:t.storeOp||Zn.Store,clearValue:h})}return a.depthStencilView&&(l.depthStencilAttachment={view:a.depthStencilView}),l}beginRender(e){const t=this.get(e),n=this.device,i=e.occlusionQueryCount;let s;i>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;u<c.length;u++){const h=c[u];e.clearColor?(u===0?h.clearValue=e.clearColorValue:(Vi.r=0,Vi.g=0,Vi.b=0,Vi.a=1,h.clearValue=Vi),h.loadOp=At.Clear):h.loadOp=At.Load,h.storeOp=Zn.Store}}else{const c=o.colorAttachments[0];e.clearColor?(c.clearValue=e.clearColorValue,c.loadOp=At.Clear):c.loadOp=At.Load,c.storeOp=Zn.Store}e.depth&&(e.clearDepth?(a.depthClearValue=e.clearDepthValue,a.depthLoadOp=At.Clear):a.depthLoadOp=At.Load,a.depthStoreOp=Zn.Store),e.stencil&&(e.clearStencil?(a.stencilClearValue=e.clearStencilValue,a.stencilLoadOp=At.Clear):a.stencilLoadOp=At.Load,a.stencilStoreOp=Zn.Store);const l=n.createCommandEncoder({label:"renderContext_"+e.id});if(this._isRenderCameraDepthArray(e)===!0){const c=e.camera.cameras;!t.layerDescriptors||t.layerDescriptors.length!==c.length?this._createDepthLayerDescriptors(e,t,o,c):this._updateDepthLayerDescriptors(e,t,c),t.bundleEncoders=[],t.bundleSets=[];for(let u=0;u<c.length;u++){const h=this.pipelineUtils.createBundleEncoder(e,"renderBundleArrayCamera_"+u),d={attributes:{},bindingGroups:[],pipeline:null,index:null};t.bundleEncoders.push(h),t.bundleSets.push(d)}t.currentPass=null}else{const c=l.beginRenderPass(o);t.currentPass=c,e.viewport&&this.updateViewport(e),e.scissor&&this.updateScissor(e)}t.descriptor=o,t.encoder=l,t.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.renderBundles=[]}_createDepthLayerDescriptors(e,t,n,i){const s=n.depthStencilAttachment;t.layerDescriptors=[];const o=this.get(e.depthTexture);o.viewCache||(o.viewCache=[]);for(let a=0;a<i.length;a++){const l={...n,colorAttachments:[{...n.colorAttachments[0],view:n.colorAttachments[a].view}]};if(n.depthStencilAttachment){const c=a;o.viewCache[c]||(o.viewCache[c]=o.texture.createView({dimension:zn.TwoD,baseArrayLayer:a,arrayLayerCount:1})),l.depthStencilAttachment={view:o.viewCache[c],depthLoadOp:s.depthLoadOp||At.Clear,depthStoreOp:s.depthStoreOp||Zn.Store,depthClearValue:s.depthClearValue||1},e.stencil&&(l.depthStencilAttachment.stencilLoadOp=s.stencilLoadOp,l.depthStencilAttachment.stencilStoreOp=s.stencilStoreOp,l.depthStencilAttachment.stencilClearValue=s.stencilClearValue)}else l.depthStencilAttachment={...s};t.layerDescriptors.push(l)}}_updateDepthLayerDescriptors(e,t,n){for(let i=0;i<n.length;i++){const s=t.layerDescriptors[i];if(s.depthStencilAttachment){const o=s.depthStencilAttachment;e.depth&&(e.clearDepth?(o.depthClearValue=e.clearDepthValue,o.depthLoadOp=At.Clear):o.depthLoadOp=At.Load),e.stencil&&(e.clearStencil?(o.stencilClearValue=e.clearStencilValue,o.stencilLoadOp=At.Clear):o.stencilLoadOp=At.Load)}}}finishRender(e){const t=this.get(e),n=e.occlusionQueryCount;t.renderBundles.length>0&&t.currentPass.executeBundles(t.renderBundles),n>t.occlusionQueryIndex&&t.currentPass.endOcclusionQuery();const i=t.encoder;if(this._isRenderCameraDepthArray(e)===!0){const s=[];for(let o=0;o<t.bundleEncoders.length;o++){const a=t.bundleEncoders[o];s.push(a.finish())}for(let o=0;o<t.layerDescriptors.length;o++)if(o<s.length){const a=t.layerDescriptors[o],l=i.beginRenderPass(a);if(e.viewport){const{x:c,y:u,width:h,height:d,minDepth:f,maxDepth:p}=e.viewportValue;l.setViewport(c,u,h,d,f,p)}if(e.scissor){const{x:c,y:u,width:h,height:d}=e.scissorValue;l.setScissorRect(c,u,h,d)}l.executeBundles([s[o]]),l.end()}}else t.currentPass&&t.currentPass.end();if(n>0){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;o<s.length;o++){const a=s[o];a.generateMipmaps===!0&&this.textureUtils.generateMipmaps(a)}}}isOccluded(e,t){const n=this.get(e);return n.occluded&&n.occluded.has(t)}async resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueryBuffer:n,currentOcclusionQueryObjects:i}=t;if(n&&i){const s=new WeakSet;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueryBuffer=null,await n.mapAsync(GPUMapMode.READ);const o=n.getMappedRange(),a=new BigUint64Array(o);for(let l=0;l<i.length;l++)a[l]===BigInt(0)&&s.add(i[l]);n.destroy(),t.occluded=s}}updateViewport(e){const{currentPass:t}=this.get(e),{x:n,y:i,width:s,height:o,minDepth:a,maxDepth:l}=e.viewportValue;t.setViewport(n,i,s,o,a,l)}updateScissor(e){const{currentPass:t}=this.get(e),{x:n,y:i,width:s,height:o}=e.scissorValue;t.setScissorRect(n,i,s,o)}getClearColor(){const e=super.getClearColor();return this.renderer.alpha===!0&&(e.r*=e.a,e.g*=e.a,e.b*=e.a),e}clear(e,t,n,i=null){const s=this.device,o=this.renderer;let a=[],l,c,u;if(e){const f=this.getClearColor();Vi.r=f.r,Vi.g=f.g,Vi.b=f.b,Vi.a=f.a}if(i===null){c=o.depth,u=o.stencil;const f=this._getDefaultRenderPassDescriptor();if(e){a=f.colorAttachments;const p=a[0];p.clearValue=Vi,p.loadOp=At.Clear,p.storeOp=Zn.Store}(c||u)&&(l=f.depthStencilAttachment)}else{c=i.depth,u=i.stencil;const f={loadOp:e?At.Clear:At.Load,clearValue:e?Vi:void 0};c&&(f.depthLoadOp=t?At.Clear:At.Load,f.depthClearValue=t?o.getClearDepth():void 0,f.depthStoreOp=Zn.Store),u&&(f.stencilLoadOp=n?At.Clear:At.Load,f.stencilClearValue=n?o.getClearStencil():void 0,f.stencilStoreOp=Zn.Store);const p=this._getRenderPassDescriptor(i,f);a=p.colorAttachments,l=p.depthStencilAttachment}c&&l&&(t?(l.depthLoadOp=At.Clear,l.depthClearValue=o.getClearDepth(),l.depthStoreOp=Zn.Store):(l.depthLoadOp=At.Load,l.depthStoreOp=Zn.Store)),u&&l&&(n?(l.stencilLoadOp=At.Clear,l.stencilClearValue=o.getClearStencil(),l.stencilStoreOp=Zn.Store):(l.stencilLoadOp=At.Load,l.stencilStoreOp=Zn.Store));const h=s.createCommandEncoder({label:"clear"});h.beginRenderPass({colorAttachments:a,depthStencilAttachment:l}).end(),s.queue.submit([h.finish()])}beginCompute(e){const t=this.get(e),n={label:"computeGroup_"+e.id};this.initTimestampQuery(ps.COMPUTE,this.getTimestampUID(e),n),t.cmdEncoderGPU=this.device.createCommandEncoder({label:"computeGroup_"+e.id}),t.passEncoderGPU=t.cmdEncoderGPU.beginComputePass(n)}compute(e,t,n,i,s=null){const o=this.get(t),{passEncoderGPU:a}=this.get(e),l=this.get(i).pipeline;this.pipelineUtils.setPipeline(a,l);for(let c=0,u=n.length;c<u;c++){const h=n[c],d=this.get(h);a.setBindGroup(c,d.group)}if(s===null&&(s=t.dispatchSize||t.count),s&&s.isIndirectStorageBufferAttribute){const c=this.get(s).buffer;a.dispatchWorkgroupsIndirect(c,0);return}if(typeof s=="number"){const c=s;if(o.dispatchSize===void 0||o.count!==c){o.dispatchSize=[0,1,1],o.count=c;const u=t.workgroupSize;let h=u[0];for(let p=1;p<u.length;p++)h*=u[p];const d=Math.ceil(c/h),f=this.device.limits.maxComputeWorkgroupsPerDimension;s=[d,1,1],d>f&&(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;S<x;S++)p===!0?l.drawIndexed(_[S],1,m[S]/v,0,S):l.draw(_[S],1,m[S],S),t.update(u,_[S],1)}else if(p===!0){const{vertexCount:m,instanceCount:_,firstVertex:x}=a,v=e.getIndirect();if(v!==null){const S=this.get(v).buffer,E=e.getIndirectOffset(),T=Array.isArray(E)?E:[E];for(let A=0;A<T.length;A++)l.drawIndexedIndirect(S,T[A])}else l.drawIndexed(m,_,x,0,0);t.update(u,m,_)}else{const{vertexCount:m,instanceCount:_,firstVertex:x}=a,v=e.getIndirect();if(v!==null){const S=this.get(v).buffer,E=e.getIndirectOffset(),T=Array.isArray(E)?E:[E];for(let A=0;A<T.length;A++)l.drawIndirect(S,T[A])}else l.draw(m,_,x,0);t.update(u,m,_)}}draw(e,t){const{object:n,context:i,pipeline:s}=e,o=this.get(i),a=this.get(s),l=a.pipeline;if(a.error===!0)return;const c=e.getDrawParameters();if(c===null)return;const u=e.getBindings(),h=e.getVertexBuffers();if(e.camera.isArrayCamera&&e.camera.cameras.length>0){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<S;v++){x[0]=v;const{layoutGPU:E}=m.layout,T=this.bindingUtils.createBindGroupIndex(x,E);_.push(T)}d.indexesGPU=_}const g=this.renderer.getPixelRatio();for(let m=0,_=f.length;m<_;m++){const x=f[m];if(n.layers.test(x.layers)){const v=x.viewport;let S=o.currentPass,E=o.currentSets;if(o.bundleEncoders){const T=o.bundleEncoders[m],A=o.bundleSets[m];S=T,E=A}if(v&&S.setViewport(Math.floor(v.x*g),Math.floor(v.y*g),Math.floor(v.width*g),Math.floor(v.height*g),i.viewportValue.minDepth,i.viewportValue.maxDepth),p&&d.indexesGPU){const T=u.indexOf(p);S.setBindGroup(T,d.indexesGPU[m]),E.bindingGroups[T]=p.id}this._draw(e,t,o,l,u,h,c,S,E)}}}else if(o.currentPass){if(o.occlusionQuerySet!==void 0){const d=o.lastOcclusionObject;d!==n&&(d!==null&&d.occlusionTest===!0&&(o.currentPass.endOcclusionQuery(),o.occlusionQueryIndex++),n.occlusionTest===!0&&(o.currentPass.beginOcclusionQuery(o.occlusionQueryIndex),o.occlusionQueryObjects[o.occlusionQueryIndex]=n),o.lastOcclusionObject=n)}this._draw(e,t,o,l,u,h,c,o.currentPass,o.currentSets)}}needsRenderUpdate(e){const t=this.get(e),{object:n,material:i}=e,s=this.utils,o=s.getSampleCountRenderContext(e.context),a=s.getCurrentColorSpace(e.context),l=s.getCurrentColorFormat(e.context),c=s.getCurrentDepthStencilFormat(e.context),u=s.getPrimitiveTopology(n,i);let h=!1;return(t.material!==i||t.materialVersion!==i.version||t.transparent!==i.transparent||t.blending!==i.blending||t.premultipliedAlpha!==i.premultipliedAlpha||t.blendSrc!==i.blendSrc||t.blendDst!==i.blendDst||t.blendEquation!==i.blendEquation||t.blendSrcAlpha!==i.blendSrcAlpha||t.blendDstAlpha!==i.blendDstAlpha||t.blendEquationAlpha!==i.blendEquationAlpha||t.colorWrite!==i.colorWrite||t.depthWrite!==i.depthWrite||t.depthTest!==i.depthTest||t.depthFunc!==i.depthFunc||t.stencilWrite!==i.stencilWrite||t.stencilFunc!==i.stencilFunc||t.stencilFail!==i.stencilFail||t.stencilZFail!==i.stencilZFail||t.stencilZPass!==i.stencilZPass||t.stencilFuncMask!==i.stencilFuncMask||t.stencilWriteMask!==i.stencilWriteMask||t.side!==i.side||t.alphaToCoverage!==i.alphaToCoverage||t.sampleCount!==o||t.colorSpace!==a||t.colorFormat!==l||t.depthStencilFormat!==c||t.primitiveTopology!==u||t.clippingContextCacheKey!==e.clippingContextCacheKey)&&(t.material=i,t.materialVersion=i.version,t.transparent=i.transparent,t.blending=i.blending,t.premultipliedAlpha=i.premultipliedAlpha,t.blendSrc=i.blendSrc,t.blendDst=i.blendDst,t.blendEquation=i.blendEquation,t.blendSrcAlpha=i.blendSrcAlpha,t.blendDstAlpha=i.blendDstAlpha,t.blendEquationAlpha=i.blendEquationAlpha,t.colorWrite=i.colorWrite,t.depthWrite=i.depthWrite,t.depthTest=i.depthTest,t.depthFunc=i.depthFunc,t.stencilWrite=i.stencilWrite,t.stencilFunc=i.stencilFunc,t.stencilFail=i.stencilFail,t.stencilZFail=i.stencilZFail,t.stencilZPass=i.stencilZPass,t.stencilFuncMask=i.stencilFuncMask,t.stencilWriteMask=i.stencilWriteMask,t.side=i.side,t.alphaToCoverage=i.alphaToCoverage,t.sampleCount=o,t.colorSpace=a,t.colorFormat=l,t.depthStencilFormat=c,t.primitiveTopology=u,t.clippingContextCacheKey=e.clippingContextCacheKey,h=!0),h}getRenderCacheKey(e){const{object:t,material:n}=e,i=this.utils,s=e.context,o=t.isMesh&&t.matrixWorld.determinant()<0;return[n.transparent,n.blending,n.premultipliedAlpha,n.blendSrc,n.blendDst,n.blendEquation,n.blendSrcAlpha,n.blendDstAlpha,n.blendEquationAlpha,n.colorWrite,n.depthWrite,n.depthTest,n.depthFunc,n.stencilWrite,n.stencilFunc,n.stencilFail,n.stencilZFail,n.stencilZPass,n.stencilFuncMask,n.stencilWriteMask,n.side,o,i.getSampleCountRenderContext(s),i.getCurrentColorSpace(s),i.getCurrentColorFormat(s),i.getCurrentDepthStencilFormat(s),i.getPrimitiveTopology(t,n),e.getGeometryCacheKey(),e.clippingContextCacheKey].join()}updateSampler(e){return this.textureUtils.updateSampler(e)}createDefaultTexture(e){return this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e,t=!1){this.textureUtils.destroyTexture(e,t)}async copyTextureToBuffer(e,t,n,i,s,o){return this.textureUtils.copyTextureToBuffer(e,t,n,i,s,o)}initTimestampQuery(e,t,n){if(!this.trackTimestamp)return;this.timestampQueryPool[e]||(this.timestampQueryPool[e]=new kI(this.device,e,2048));const i=this.timestampQueryPool[e],s=i.allocateQueriesForContext(t);n.timestampWrites={querySet:i.querySet,beginningOfPassWriteIndex:s,endOfPassWriteIndex:s+1}}createNodeBuilder(e,t){return new NI(e,t)}createProgram(e){const t=this.get(e);t.module={module:this.device.createShaderModule({code:e.code,label:e.stage+(e.name!==""?`_${e.name}`:"")}),entryPoint:"main"}}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){this.pipelineUtils.createRenderPipeline(e,t)}createComputePipeline(e,t){this.pipelineUtils.createComputePipeline(e,t)}beginBundle(e){const t=this.get(e);t._currentPass=t.currentPass,t._currentSets=t.currentSets,t.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.currentPass=this.pipelineUtils.createBundleEncoder(e)}finishBundle(e,t){const n=this.get(e),s=n.currentPass.finish();this.get(t).bundleGPU=s,n.currentSets=n._currentSets,n.currentPass=n._currentPass}addBundle(e,t){this.get(e).renderBundles.push(this.get(t).bundleGPU)}createBindings(e,t,n,i){this.bindingUtils.createBindings(e,t,n,i)}updateBindings(e,t,n,i){this.bindingUtils.createBindings(e,t,n,i)}updateBinding(e){this.bindingUtils.updateBinding(e)}deleteBindGroupData(e){this.bindingUtils.deleteBindGroupData(e)}createIndexAttribute(e){let t=GPUBufferUsage.INDEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST;(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(t|=GPUBufferUsage.STORAGE),this.attributeUtils.createAttribute(e,t)}createAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createIndirectStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.INDIRECT|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}updateAttribute(e){this.attributeUtils.updateAttribute(e)}destroyAttribute(e){this.attributeUtils.destroyAttribute(e)}updateSize(){this.delete(this.renderer.getCanvasTarget())}hasFeature(e){return Y_[e]!==void 0&&(e=Y_[e]),this.device.features.has(e)}copyTextureToTexture(e,t,n=null,i=null,s=0,o=0){let a=0,l=0,c=0,u=0,h=0,d=0,f=e.image.width,p=e.image.height,g=1;n!==null&&(n.isBox3===!0?(u=n.min.x,h=n.min.y,d=n.min.z,f=n.max.x-n.min.x,p=n.max.y-n.min.y,g=n.max.z-n.min.z):(u=n.min.x,h=n.min.y,f=n.max.x-n.min.x,p=n.max.y-n.min.y,g=1)),i!==null&&(a=i.x,l=i.y,c=i.z||0);const m=this.device.createCommandEncoder({label:"copyTextureToTexture_"+e.id+"_"+t.id}),_=this.get(e).texture,x=this.get(t).texture;m.copyTextureToTexture({texture:_,mipLevel:s,origin:{x:u,y:h,z:d}},{texture:x,mipLevel:o,origin:{x:a,y:l,z:c}},[f,p,g]),this.device.queue.submit([m.finish()]),o===0&&t.generateMipmaps&&this.textureUtils.generateMipmaps(t)}copyFramebufferToTexture(e,t,n){const i=this.get(t);let s=null;t.renderTarget?e.isDepthTexture?s=this.get(t.depthTexture).texture:s=this.get(t.textures[0]).texture:e.isDepthTexture?s=this.textureUtils.getDepthBuffer(t.depth,t.stencil):s=this.context.getCurrentTexture();const o=this.get(e).texture;if(s.format!==o.format){ne("WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.",s.format,o.format);return}let a;if(i.currentPass?(i.currentPass.end(),a=i.encoder):a=this.device.createCommandEncoder({label:"copyFramebufferToTexture_"+e.id}),a.copyTextureToTexture({texture:s,origin:[n.x,n.y,0]},{texture:o},[n.z,n.w]),e.generateMipmaps&&this.textureUtils.generateMipmaps(e,a),i.currentPass){const{descriptor:l}=i;for(let c=0;c<l.colorAttachments.length;c++)l.colorAttachments[c].loadOp=At.Load;t.depth&&(l.depthStencilAttachment.depthLoadOp=At.Load),t.stencil&&(l.depthStencilAttachment.stencilLoadOp=At.Load),i.currentPass=a.beginRenderPass(l),i.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.viewport&&this.updateViewport(t),t.scissor&&this.updateScissor(t)}else this.device.queue.submit([a.finish()])}hasCompatibility(e){return this._compatibility[e]!==void 0?this._compatibility[e]:super.hasCompatibility(e)}dispose(){if(this.bindingUtils.dispose(),this.textureUtils.dispose(),this.occludedResolveCache){for(const e of this.occludedResolveCache.values())e.destroy();this.occludedResolveCache.clear()}if(this.timestampQueryPool)for(const e of Object.values(this.timestampQueryPool))e!==null&&e.dispose();this.parameters.device===void 0&&this.device!==null&&this.device.destroy()}}class VI extends xp{constructor(e,t,n,i,s,o){super(e,t,n,i,s,o),this.iesMap=null}copy(e,t){return super.copy(e,t),this.iesMap=e.iesMap,this}}class zI extends xp{constructor(e,t,n,i,s,o){super(e,t,n,i,s,o),this.aspect=null}copy(e,t){return super.copy(e,t),this.aspect=e.aspect,this}}class HI extends nv{constructor(){super(),this.addMaterial(eD,"MeshPhongMaterial"),this.addMaterial(Iy,"MeshStandardMaterial"),this.addMaterial(ZD,"MeshPhysicalMaterial"),this.addMaterial(tL,"MeshToonMaterial"),this.addMaterial(qP,"MeshBasicMaterial"),this.addMaterial(QP,"MeshLambertMaterial"),this.addMaterial(zP,"MeshNormalMaterial"),this.addMaterial(sL,"MeshMatcapMaterial"),this.addMaterial(OP,"LineBasicMaterial"),this.addMaterial(GP,"LineDashedMaterial"),this.addMaterial(cL,"PointsMaterial"),this.addMaterial(Oy,"SpriteMaterial"),this.addMaterial(fL,"ShadowMaterial"),this.addLight(zU,Ib),this.addLight(xF,Bx),this.addLight(MF,Ob),this.addLight(Xp,xp),this.addLight(_F,Ox),this.addLight(yF,Lb),this.addLight(SF,Gb),this.addLight(vF,VI),this.addLight(TF,zI),this.addToneMapping(qL,Hf),this.addToneMapping(jL,Wf),this.addToneMapping(YL,$f),this.addToneMapping(ZL,Xf),this.addToneMapping(tU,qf),this.addToneMapping(nU,jf)}}class WI extends $F{constructor(e={}){let t;e.forceWebGL?t=H_:(t=GI,e.getFallback=()=>(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;t<this._pointers.length;t++)if(this._pointers[t].pointerId==e.pointerId){this._pointers.splice(t,1);return}}_trackPointer(e){let t=this._pointerPositions[e.pointerId];t===void 0&&(t=new de,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0].pointerId?this._pointers[1]:this._pointers[0];return this._pointerPositions[t.pointerId]}_checkDistances(){(!this.noZoom||!this.noPan)&&(this._eye.lengthSq()>this.maxDistance*this.maxDistance&&(this.object.position.addVectors(this.target,this._eye.setLength(this.maxDistance)),this._zoomStart.copy(this._zoomEnd)),this._eye.lengthSq()<this.minDistance*this.minDistance&&(this.object.position.addVectors(this.target,this._eye.setLength(this.minDistance)),this._zoomStart.copy(this._zoomEnd)))}}function qI(r){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(r.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp)),this._addPointer(r),r.pointerType==="touch"?this._onTouchStart(r):this._onMouseDown(r))}function jI(r){this.enabled!==!1&&(r.pointerType==="touch"?this._onTouchMove(r):this._onMouseMove(r))}function YI(r){this.enabled!==!1&&(r.pointerType==="touch"?this._onTouchEnd(r):this._onMouseUp(),this._removePointer(r),this._pointers.length===0&&(this.domElement.releasePointerCapture(r.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp)))}function KI(r){this._removePointer(r)}function ZI(){this.enabled!==!1&&(this.keyState=Rt.NONE,window.addEventListener("keydown",this._onKeyDown))}function QI(r){this.enabled!==!1&&(window.removeEventListener("keydown",this._onKeyDown),this.keyState===Rt.NONE&&(r.code===this.keys[Rt.ROTATE]&&!this.noRotate?this.keyState=Rt.ROTATE:r.code===this.keys[Rt.ZOOM]&&!this.noZoom?this.keyState=Rt.ZOOM:r.code===this.keys[Rt.PAN]&&!this.noPan&&(this.keyState=Rt.PAN)))}function JI(r){let e;switch(r.button){case 0:e=this.mouseButtons.LEFT;break;case 1:e=this.mouseButtons.MIDDLE;break;case 2:e=this.mouseButtons.RIGHT;break;default:e=-1}switch(e){case Ln.DOLLY:this.state=Rt.ZOOM;break;case Ln.ROTATE:this.state=Rt.ROTATE;break;case Ln.PAN:this.state=Rt.PAN;break;default:this.state=Rt.NONE}const t=this.keyState!==Rt.NONE?this.keyState:this.state;t===Rt.ROTATE&&!this.noRotate?(this._moveCurr.copy(this._getMouseOnCircle(r.pageX,r.pageY)),this._movePrev.copy(this._moveCurr)):t===Rt.ZOOM&&!this.noZoom?(this._zoomStart.copy(this._getMouseOnScreen(r.pageX,r.pageY)),this._zoomEnd.copy(this._zoomStart)):t===Rt.PAN&&!this.noPan&&(this._panStart.copy(this._getMouseOnScreen(r.pageX,r.pageY)),this._panEnd.copy(this._panStart)),this.dispatchEvent(jp)}function e3(r){const e=this.keyState!==Rt.NONE?this.keyState:this.state;e===Rt.ROTATE&&!this.noRotate?(this._movePrev.copy(this._moveCurr),this._moveCurr.copy(this._getMouseOnCircle(r.pageX,r.pageY))):e===Rt.ZOOM&&!this.noZoom?this._zoomEnd.copy(this._getMouseOnScreen(r.pageX,r.pageY)):e===Rt.PAN&&!this.noPan&&this._panEnd.copy(this._getMouseOnScreen(r.pageX,r.pageY))}function t3(){this.state=Rt.NONE,this.dispatchEvent(Yp)}function n3(r){if(this.enabled!==!1&&this.noZoom!==!0){switch(r.preventDefault(),r.deltaMode){case 2:this._zoomStart.y-=r.deltaY*.025;break;case 1:this._zoomStart.y-=r.deltaY*.01;break;default:this._zoomStart.y-=r.deltaY*25e-5;break}this.dispatchEvent(jp),this.dispatchEvent(Yp)}}function i3(r){this.enabled!==!1&&r.preventDefault()}function s3(r){switch(this._trackPointer(r),this._pointers.length){case 1:this.state=Rt.TOUCH_ROTATE,this._moveCurr.copy(this._getMouseOnCircle(this._pointers[0].pageX,this._pointers[0].pageY)),this._movePrev.copy(this._moveCurr);break;default:this.state=Rt.TOUCH_ZOOM_PAN;const e=this._pointers[0].pageX-this._pointers[1].pageX,t=this._pointers[0].pageY-this._pointers[1].pageY;this._touchZoomDistanceEnd=this._touchZoomDistanceStart=Math.sqrt(e*e+t*t);const n=(this._pointers[0].pageX+this._pointers[1].pageX)/2,i=(this._pointers[0].pageY+this._pointers[1].pageY)/2;this._panStart.copy(this._getMouseOnScreen(n,i)),this._panEnd.copy(this._panStart);break}this.dispatchEvent(jp)}function r3(r){switch(this._trackPointer(r),this._pointers.length){case 1:this._movePrev.copy(this._moveCurr),this._moveCurr.copy(this._getMouseOnCircle(r.pageX,r.pageY));break;default:const e=this._getSecondPointerPosition(r),t=r.pageX-e.x,n=r.pageY-e.y;this._touchZoomDistanceEnd=Math.sqrt(t*t+n*n);const i=(r.pageX+e.x)/2,s=(r.pageY+e.y)/2;this._panEnd.copy(this._getMouseOnScreen(i,s));break}}function o3(r){switch(this._pointers.length){case 0:this.state=Rt.NONE;break;case 1:this.state=Rt.TOUCH_ROTATE,this._moveCurr.copy(this._getMouseOnCircle(r.pageX,r.pageY)),this._movePrev.copy(this._moveCurr);break;case 2:this.state=Rt.TOUCH_ZOOM_PAN;for(let e=0;e<this._pointers.length;e++)if(this._pointers[e].pointerId!==r.pointerId){const t=this._pointerPositions[this._pointers[e].pointerId];this._moveCurr.copy(this._getMouseOnCircle(t.x,t.y)),this._movePrev.copy(this._moveCurr);break}break}this.dispatchEvent(Yp)}const nx={type:"change"},Kp={type:"start"},pv={type:"end"},yu=new Zu,ix=new os,a3=Math.cos(70*Du.DEG2RAD),vn=new C,ii=2*Math.PI,kt={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},Kd=1e-6;class l3 extends Ju{constructor(e,t=null){super(e,t),this.state=kt.NONE,this.target=new C,this.cursor=new C,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.keyRotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:Ln.ROTATE,MIDDLE:Ln.DOLLY,RIGHT:Ln.PAN},this.touches={ONE:ks.ROTATE,TWO:ks.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._cursorStyle="auto",this._domElementKeyEvents=null,this._lastPosition=new C,this._lastQuaternion=new Li,this._lastTargetPosition=new C,this._quat=new Li().setFromUnitVectors(e.up,new C(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new zm,this._sphericalDelta=new zm,this._scale=1,this._panOffset=new C,this._rotateStart=new de,this._rotateEnd=new de,this._rotateDelta=new de,this._panStart=new de,this._panEnd=new de,this._panDelta=new de,this._dollyStart=new de,this._dollyEnd=new de,this._dollyDelta=new de,this._dollyDirection=new C,this._mouse=new de,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=u3.bind(this),this._onPointerDown=c3.bind(this),this._onPointerUp=h3.bind(this),this._onContextMenu=x3.bind(this),this._onMouseWheel=p3.bind(this),this._onKeyDown=m3.bind(this),this._onTouchStart=g3.bind(this),this._onTouchMove=_3.bind(this),this._onMouseDown=d3.bind(this),this._onMouseMove=f3.bind(this),this._interceptControlDown=y3.bind(this),this._interceptControlUp=v3.bind(this),this.domElement!==null&&this.connect(this.domElement),this.update()}set cursorStyle(e){this._cursorStyle=e,e==="grab"?this.domElement.style.cursor="grab":this.domElement.style.cursor="auto"}get cursorStyle(){return this._cursorStyle}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents(),this.domElement.getRootNode().removeEventListener("keydown",this._interceptControlDown,{capture:!0}),this.domElement.style.touchAction=""}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){this._domElementKeyEvents!==null&&(this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null)}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(nx),this.update(),this.state=kt.NONE}pan(e,t){this._pan(e,t),this.update()}dollyIn(e){this._dollyIn(e),this.update()}dollyOut(e){this._dollyOut(e),this.update()}rotateLeft(e){this._rotateLeft(e),this.update()}rotateUp(e){this._rotateUp(e),this.update()}update(e=null){const t=this.object.position;vn.copy(t).sub(this.target),vn.applyQuaternion(this._quat),this._spherical.setFromVector3(vn),this.autoRotate&&this.state===kt.NONE&&this._rotateLeft(this._getAutoRotationAngle(e)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let n=this.minAzimuthAngle,i=this.maxAzimuthAngle;isFinite(n)&&isFinite(i)&&(n<-Math.PI?n+=ii:n>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))<a3?this.object.lookAt(this.target):(ix.setFromNormalAndCoplanarPoint(this.object.up,this.target),yu.intersectPlane(ix,this.target))))}else if(this.object.isOrthographicCamera){const o=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),o!==this.object.zoom&&(this.object.updateProjectionMatrix(),s=!0)}return this._scale=1,this._performCursorZoom=!1,s||this._lastPosition.distanceToSquared(this.object.position)>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;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId){this._pointers.splice(t,1);return}}_isTrackingPointer(e){for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return!0;return!1}_trackPointer(e){let t=this._pointerPositions[e.pointerId];t===void 0&&(t=new de,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){const t=e.deltaMode,n={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:n.deltaY*=16;break;case 2:n.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(n.deltaY*=10),n}}function c3(r){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(r.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(r)&&(this._addPointer(r),r.pointerType==="touch"?this._onTouchStart(r):this._onMouseDown(r),this._cursorStyle==="grab"&&(this.domElement.style.cursor="grabbing")))}function u3(r){this.enabled!==!1&&(r.pointerType==="touch"?this._onTouchMove(r):this._onMouseMove(r))}function h3(r){switch(this._removePointer(r),this._pointers.length){case 0:this.domElement.releasePointerCapture(r.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(pv),this.state=kt.NONE,this._cursorStyle==="grab"&&(this.domElement.style.cursor="grab");break;case 1:const e=this._pointers[0],t=this._pointerPositions[e];this._onTouchStart({pointerId:e,pageX:t.x,pageY:t.y});break}}function d3(r){let e;switch(r.button){case 0:e=this.mouseButtons.LEFT;break;case 1:e=this.mouseButtons.MIDDLE;break;case 2:e=this.mouseButtons.RIGHT;break;default:e=-1}switch(e){case Ln.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(r),this.state=kt.DOLLY;break;case Ln.ROTATE:if(r.ctrlKey||r.metaKey||r.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(r),this.state=kt.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(r),this.state=kt.ROTATE}break;case Ln.PAN:if(r.ctrlKey||r.metaKey||r.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(r),this.state=kt.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(r),this.state=kt.PAN}break;default:this.state=kt.NONE}this.state!==kt.NONE&&this.dispatchEvent(Kp)}function f3(r){switch(this.state){case kt.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(r);break;case kt.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(r);break;case kt.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(r);break}}function p3(r){this.enabled===!1||this.enableZoom===!1||this.state!==kt.NONE||(r.preventDefault(),this.dispatchEvent(Kp),this._handleMouseWheel(this._customWheelEvent(r)),this.dispatchEvent(pv))}function m3(r){this.enabled!==!1&&this._handleKeyDown(r)}function g3(r){switch(this._trackPointer(r),this._pointers.length){case 1:switch(this.touches.ONE){case ks.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(r),this.state=kt.TOUCH_ROTATE;break;case ks.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(r),this.state=kt.TOUCH_PAN;break;default:this.state=kt.NONE}break;case 2:switch(this.touches.TWO){case ks.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(r),this.state=kt.TOUCH_DOLLY_PAN;break;case ks.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(r),this.state=kt.TOUCH_DOLLY_ROTATE;break;default:this.state=kt.NONE}break;default:this.state=kt.NONE}this.state!==kt.NONE&&this.dispatchEvent(Kp)}function _3(r){switch(this._trackPointer(r),this.state){case kt.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(r),this.update();break;case kt.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(r),this.update();break;case kt.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(r),this.update();break;case kt.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(r),this.update();break;default:this.state=kt.NONE}}function x3(r){this.enabled!==!1&&r.preventDefault()}function y3(r){r.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function v3(r){r.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}const S3={type:"change"},sx=1e-6,rx=new Li;class b3 extends Ju{constructor(e,t=null){super(e,t),this.movementSpeed=1,this.rollSpeed=.005,this.dragToLook=!1,this.autoForward=!1,this._moveState={up:0,down:0,left:0,right:0,forward:0,back:0,pitchUp:0,pitchDown:0,yawLeft:0,yawRight:0,rollLeft:0,rollRight:0},this._moveVector=new C(0,0,0),this._rotationVector=new C(0,0,0),this._lastQuaternion=new Li,this._lastPosition=new C,this._status=0,this._onKeyDown=T3.bind(this),this._onKeyUp=M3.bind(this),this._onPointerMove=A3.bind(this),this._onPointerDown=E3.bind(this),this._onPointerUp=R3.bind(this),this._onPointerCancel=w3.bind(this),this._onContextMenu=C3.bind(this),t!==null&&this.connect(t)}connect(e){super.connect(e),window.addEventListener("keydown",this._onKeyDown),window.addEventListener("keyup",this._onKeyUp),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointerup",this._onPointerUp),this.domElement.addEventListener("pointercancel",this._onPointerCancel),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction="none"}disconnect(){window.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("keyup",this._onKeyUp),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerCancel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.domElement.style.touchAction=""}dispose(){this.disconnect()}update(e){if(this.enabled===!1)return;const t=this.object,n=e*this.movementSpeed,i=e*this.rollSpeed;t.translateX(this._moveVector.x*n),t.translateY(this._moveVector.y*n),t.translateZ(this._moveVector.z*n),rx.set(this._rotationVector.x*i,this._rotationVector.y*i,this._rotationVector.z*i,1).normalize(),t.quaternion.multiply(rx),(this._lastPosition.distanceToSquared(t.position)>sx||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<this.passes.length;t++)if(this.passes[t].enabled)return!1;return!0}render(e){this.timer.update(),e===void 0&&(e=this.timer.getDelta());const t=this.renderer.getRenderTarget();let n=!1;for(let i=0,s=this.passes.length;i<s;i++){const o=this.passes[i];if(o.enabled!==!1){if(o.renderToScreen=this.renderToScreen&&this.isLastEnabledPass(i),o.render(this.renderer,this.writeBuffer,this.readBuffer,e,n),o.needsSwap){if(n){const a=this.renderer.getContext(),l=this.renderer.state.buffers.stencil;l.setFunc(a.NOTEQUAL,1,4294967295),this.copyPass.render(this.renderer,this.writeBuffer,this.readBuffer,e),l.setFunc(a.EQUAL,1,4294967295)}this.swapBuffers()}ox!==void 0&&(o instanceof ox?n=!0:o instanceof I3&&(n=!1))}}this.renderer.setRenderTarget(t)}reset(e){if(e===void 0){const t=this.renderer.getSize(new de);this._pixelRatio=this.renderer.getPixelRatio(),this._width=t.width,this._height=t.height,e=this.renderTarget1.clone(),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}this.renderTarget1.dispose(),this.renderTarget2.dispose(),this.renderTarget1=e,this.renderTarget2=e.clone(),this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2}setSize(e,t){this._width=e,this._height=t;const n=this._width*this._pixelRatio,i=this._height*this._pixelRatio;this.renderTarget1.setSize(n,i),this.renderTarget2.setSize(n,i);for(let s=0;s<this.passes.length;s++)this.passes[s].setSize(n,i)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget1.dispose(),this.renderTarget2.dispose(),this.copyPass.dispose()}}class O3 extends gh{constructor(e,t,n=null,i=null,s=null){super(),this.scene=e,this.camera=t,this.overrideMaterial=n,this.clearColor=i,this.clearAlpha=s,this.clear=!0,this.clearDepth=!1,this.needsSwap=!1,this.isRenderPass=!0,this._oldClearColor=new Ve}render(e,t,n){const i=e.autoClear;e.autoClear=!1;let s,o;this.overrideMaterial!==null&&(o=this.scene.overrideMaterial,this.scene.overrideMaterial=this.overrideMaterial),this.clearColor!==null&&(e.getClearColor(this._oldClearColor),e.setClearColor(this.clearColor,e.getClearAlpha())),this.clearAlpha!==null&&(s=e.getClearAlpha(),e.setClearAlpha(this.clearAlpha)),this.clearDepth==!0&&e.clearDepth(),e.setRenderTarget(this.renderToScreen?null:n),this.clear===!0&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),e.render(this.scene,this.camera),this.clearColor!==null&&e.setClearColor(this._oldClearColor),this.clearAlpha!==null&&e.setClearAlpha(s),this.overrideMaterial!==null&&(this.scene.overrideMaterial=o),e.autoClear=i}}function k3(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 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;t++)n[t]=r[t];return n}function V3(r){if(Array.isArray(r))return r}function z3(r){if(Array.isArray(r))return Nf(r)}function H3(r,e,t){return(e=K3(e))in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function W3(r){if(typeof Symbol<"u"&&r[Symbol.iterator]!=null||r["@@iterator"]!=null)return Array.from(r)}function $3(r,e){var t=r==null?null:typeof Symbol<"u"&&r[Symbol.iterator]||r["@@iterator"];if(t!=null){var n,i,s,o,a=[],l=!0,c=!1;try{if(s=(t=t.call(r)).next,e!==0)for(;!(l=(n=s.call(t)).done)&&(a.push(n.value),a.length!==e);l=!0);}catch(u){c=!0,i=u}finally{try{if(!l&&t.return!=null&&(o=t.return(),Object(o)!==o))return}finally{if(c)throw i}}return a}}function X3(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function q3(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
|
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function j3(r,e){return V3(r)||$3(r,e)||mv(r,e)||X3()}function Wr(r){return z3(r)||W3(r)||mv(r)||q3()}function Y3(r,e){if(typeof r!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var n=t.call(r,e);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function K3(r){var e=Y3(r,"string");return typeof e=="symbol"?e:e+""}function mv(r,e){if(r){if(typeof r=="string")return Nf(r,e);var t={}.toString.call(r).slice(8,-1);return t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set"?Array.from(r):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?Nf(r,e):void 0}}var gv=function(e){e instanceof Array?e.forEach(gv):(e.map&&e.map.dispose(),e.dispose())},_v=function(e){e.geometry&&e.geometry.dispose(),e.material&&gv(e.material),e.texture&&e.texture.dispose(),e.children&&e.children.forEach(_v)},Z3=function(e){for(;e.children.length;){var t=e.children[0];e.remove(t),_v(t)}},tn=window.THREE?window.THREE:{WebGLRenderer:OR,Scene:op,PerspectiveCamera:Rn,Raycaster:zx,SRGBColorSpace:Qn,TextureLoader:Db,Vector2:de,Vector3:C,Box3:xo,Color:Ve,Mesh:gn,SphereGeometry:hc,MeshBasicMaterial:us,BackSide:Pt,Timer:Vx},xv=Df({props:{width:{default:window.innerWidth,onChange:function(e,t,n){isNaN(e)&&(t.width=n)}},height:{default:window.innerHeight,onChange:function(e,t,n){isNaN(e)&&(t.height=n)}},viewOffset:{default:[0,0]},backgroundColor:{default:"#000011"},backgroundImageUrl:{},onBackgroundImageLoaded:{},showNavInfo:{default:!0},skyRadius:{default:5e4},objects:{default:[]},lights:{default:[]},enablePointerInteraction:{default:!0,onChange:function(e,t){t.hoverObj=null,t.tooltip&&t.tooltip.content(null)},triggerUpdate:!1},pointerRaycasterThrottleMs:{default:50,triggerUpdate:!1},lineHoverPrecision:{default:1,triggerUpdate:!1},pointsHoverPrecision:{default:1,triggerUpdate:!1},hoverOrderComparator:{triggerUpdate:!1},hoverFilter:{default:function(){return!0},triggerUpdate:!1},tooltipContent:{triggerUpdate:!1},hoverDuringDrag:{default:!1,triggerUpdate:!1},clickAfterDrag:{default:!1,triggerUpdate:!1},onHover:{default:function(){},triggerUpdate:!1},onClick:{default:function(){},triggerUpdate:!1},onRightClick:{triggerUpdate:!1}},methods:{tick:function(e){if(e.initialised){e.controls.enabled&&e.controls.update&&e.controls.update(Math.min(1,e.timer.update().getDelta())),e.postProcessingComposer?e.postProcessingComposer.render():e.renderer.render(e.scene,e.camera),e.extraRenderers.forEach(function(o){return o.render(e.scene,e.camera)});var t=+new Date;if(e.enablePointerInteraction&&t-e.lastRaycasterCheck>=e.pointerRaycasterThrottleMs){e.lastRaycasterCheck=t;var n=null;if(e.hoverDuringDrag||!e.isPointerDragging){var 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;o<i;o++)s[o-3]=arguments[o];return this.fitToBbox(this.getBbox.apply(this,s),t,n)},fitToBbox:function(e,t){var n=arguments.length>2&&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);t<e;t++)n[t]=r[t];return n}function e2(r){if(Array.isArray(r))return Pf(r)}function _c(r,e,t){return(e=s2(e))in r?Object.defineProperty(r,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):r[e]=t,r}function t2(r){if(typeof Symbol<"u"&&r[Symbol.iterator]!=null||r["@@iterator"]!=null)return Array.from(r)}function n2(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
|
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function ax(r,e){var t=Object.keys(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(r);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(r,i).enumerable})),t.push.apply(t,n)}return t}function vu(r){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?ax(Object(t),!0).forEach(function(n){_c(r,n,t[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(t)):ax(Object(t)).forEach(function(n){Object.defineProperty(r,n,Object.getOwnPropertyDescriptor(t,n))})}return r}function _h(r){return e2(r)||t2(r)||r2(r)||n2()}function i2(r,e){if(typeof r!="object"||!r)return r;var t=r[Symbol.toPrimitive];if(t!==void 0){var n=t.call(r,e);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(r)}function s2(r){var e=i2(r,"string");return typeof e=="symbol"?e:e+""}function r2(r,e){if(r){if(typeof r=="string")return Pf(r,e);var t={}.toString.call(r).slice(8,-1);return t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set"?Array.from(r):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?Pf(r,e):void 0}}function yv(r,e){var t=new e;return t._destructor&&t._destructor(),{linkProp:function(i){return{default:t[i](),onChange:function(o,a){a[r][i](o)},triggerUpdate:!1}},linkMethod:function(i){return function(s){for(var o=s[r],a=arguments.length,l=new Array(a>1?a-1:0),c=1;c<a;c++)l[c-1]=arguments[c];var u=o[i].apply(o,l);return u===o?this:u}}}}var Zd=window.THREE?window.THREE:{AmbientLight:Ox,DirectionalLight:Bx,REVISION:po},o2=170,vv=yv("forceGraph",h0),a2=Object.assign.apply(Object,_h(["jsonUrl","graphData","numDimensions","dagMode","dagLevelDistance","dagNodeFilter","onDagError","nodeRelSize","nodeId","nodeVal","nodeResolution","nodeColor","nodeAutoColorBy","nodeOpacity","nodeVisibility","nodeThreeObject","nodeThreeObjectExtend","nodePositionUpdate","linkSource","linkTarget","linkVisibility","linkColor","linkAutoColorBy","linkOpacity","linkWidth","linkResolution","linkCurvature","linkCurveRotation","linkMaterial","linkThreeObject","linkThreeObjectExtend","linkPositionUpdate","linkDirectionalArrowLength","linkDirectionalArrowColor","linkDirectionalArrowRelPos","linkDirectionalArrowResolution","linkDirectionalParticles","linkDirectionalParticleSpeed","linkDirectionalParticleOffset","linkDirectionalParticleWidth","linkDirectionalParticleColor","linkDirectionalParticleResolution","linkDirectionalParticleThreeObject","forceEngine","d3AlphaDecay","d3VelocityDecay","d3AlphaMin","ngraphPhysics","warmupTicks","cooldownTicks","cooldownTime","onEngineTick","onEngineStop"].map(function(r){return _c({},r,vv.linkProp(r))}))),l2=Object.assign.apply(Object,_h(["refresh","getGraphBbox","d3Force","d3ReheatSimulation","emitParticle"].map(function(r){return _c({},r,vv.linkMethod(r))}))),Cu=yv("renderObjs",xv),c2=Object.assign.apply(Object,_h(["width","height","backgroundColor","showNavInfo","enablePointerInteraction"].map(function(r){return _c({},r,Cu.linkProp(r))}))),u2=Object.assign.apply(Object,_h(["lights","cameraPosition","postProcessingComposer"].map(function(r){return _c({},r,Cu.linkMethod(r))})).concat([{graph2ScreenCoords:Cu.linkMethod("getScreenCoords"),screen2GraphCoords:Cu.linkMethod("getSceneCoords")}])),h2=Df({props:vu(vu({nodeLabel:{default:"name",triggerUpdate:!1},linkLabel:{default:"name",triggerUpdate:!1},linkHoverPrecision:{default:1,onChange:function(e,t){return t.renderObjs.lineHoverPrecision(e)},triggerUpdate:!1},enableNavigationControls:{default:!0,onChange:function(e,t){var n=t.renderObjs.controls();n&&(n.enabled=e,e&&n.domElement&&n.domElement.dispatchEvent(new PointerEvent("pointerup")))},triggerUpdate:!1},enableNodeDrag:{default:!0,triggerUpdate:!1},onNodeDrag:{default:function(){},triggerUpdate:!1},onNodeDragEnd:{default:function(){},triggerUpdate:!1},onNodeClick:{triggerUpdate:!1},onNodeRightClick:{triggerUpdate:!1},onNodeHover:{triggerUpdate:!1},onLinkClick:{triggerUpdate:!1},onLinkRightClick:{triggerUpdate:!1},onLinkHover:{triggerUpdate:!1},onBackgroundClick:{triggerUpdate:!1},onBackgroundRightClick:{triggerUpdate:!1},showPointerCursor:{default:!0,triggerUpdate:!1}},a2),c2),methods:vu(vu({zoomToFit:function(e,t,n){for(var i,s=arguments.length,o=new Array(s>3?s-3:0),a=3;a<s;a++)o[a-3]=arguments[a];return e.renderObjs.fitToBbox((i=e.forceGraph).getGraphBbox.apply(i,o),t,n),this},pauseAnimation:function(e){return e.animationFrameRequestId!==null&&(cancelAnimationFrame(e.animationFrameRequestId),e.animationFrameRequestId=null),this},resumeAnimation:function(e){return e.animationFrameRequestId===null&&this._animationCycle(),this},_animationCycle:function(e){e.enablePointerInteraction&&(this.renderer().domElement.style.cursor=null),e.forceGraph.tickFrame(),e.renderObjs.tick(),e.animationFrameRequestId=requestAnimationFrame(this._animationCycle)},scene:function(e){return e.renderObjs.scene()},camera:function(e){return e.renderObjs.camera()},renderer:function(e){return e.renderObjs.renderer()},controls:function(e){return e.renderObjs.controls()},_destructor:function(e){var t,n;this.pauseAnimation(),this.graphData({nodes:[],links:[]}),(t=(n=e.forceGraph)._destructor)===null||t===void 0||t.call(n),e.renderObjs._destructor()}},l2),u2),stateInit:function(e){var t=e.controlType,n=e.rendererConfig,i=e.extraRenderers,s=new h0;return{forceGraph:s,renderObjs:xv({controlType:t,rendererConfig:n,extraRenderers:i}).objects([s]).lights([new Zd.AmbientLight(13421772,Math.PI),new Zd.DirectionalLight(16777215,.6*Math.PI)])}},init:function(e,t){e.innerHTML="",e.appendChild(t.container=document.createElement("div")),t.container.style.position="relative";var n=document.createElement("div");t.container.appendChild(n),t.renderObjs(n);var i=t.renderObjs.camera(),s=t.renderObjs.renderer(),o=t.renderObjs.controls();o.enabled=!!t.enableNavigationControls,t.lastSetCameraZ=i.position.z;var a;t.container.appendChild(a=document.createElement("div")),a.className="graph-info-msg",a.textContent="",t.forceGraph.onLoading(function(){a.textContent="Loading..."}).onFinishLoading(function(){a.textContent=""}).onUpdate(function(){t.graphData=t.forceGraph.graphData(),i.position.x===0&&i.position.y===0&&i.position.z===t.lastSetCameraZ&&t.graphData.nodes.length&&(i.lookAt(t.forceGraph.position),t.lastSetCameraZ=i.position.z=Math.cbrt(t.graphData.nodes.length)*o2)}).onFinishUpdate(function(){if(t._dragControls){var l=t.graphData.nodes.find(function(u){return u.__initialFixedPos&&!u.__disposeControlsAfterDrag});l?l.__disposeControlsAfterDrag=!0:t._dragControls.dispose(),t._dragControls=void 0}if(t.enableNodeDrag&&t.enablePointerInteraction&&t.forceEngine==="d3"){var c=t._dragControls=new kR(t.graphData.nodes.map(function(u){return u.__threeObj}).filter(function(u){return u}),i,s.domElement);c.addEventListener("dragstart",function(u){var h=Ls(u.object);if(h){o.enabled=!1,u.object.__initialPos=u.object.position.clone(),u.object.__prevPos=u.object.position.clone();var d=h.__data;!d.__initialFixedPos&&(d.__initialFixedPos={fx:d.fx,fy:d.fy,fz:d.fz}),!d.__initialPos&&(d.__initialPos={x:d.x,y:d.y,z:d.z}),["x","y","z"].forEach(function(f){return d["f".concat(f)]=d[f]}),s.domElement.classList.add("grabbable")}}),c.addEventListener("drag",function(u){var h=Ls(u.object);if(h){if(!u.object.hasOwnProperty("__graphObjType")){var d=u.object.__initialPos,f=u.object.__prevPos,p=u.object.position;h.position.add(p.clone().sub(f)),f.copy(p),p.copy(d)}var g=h.__data,m=h.position,_={x:m.x-g.x,y:m.y-g.y,z:m.z-g.z};["x","y","z"].forEach(function(x){return g["f".concat(x)]=g[x]=m[x]}),t.forceGraph.d3AlphaTarget(.3).resetCountdown(),g.__dragged=!0,t.onNodeDrag(g,_)}}),c.addEventListener("dragend",function(u){var h=Ls(u.object);if(h){delete u.object.__initialPos,delete u.object.__prevPos;var d=h.__data;d.__disposeControlsAfterDrag&&(c.dispose(),delete d.__disposeControlsAfterDrag);var f=d.__initialFixedPos,p=d.__initialPos,g={x:p.x-d.x,y:p.y-d.y,z:p.z-d.z};if(f&&(["x","y","z"].forEach(function(_){var x="f".concat(_);f[x]===void 0&&delete d[x]}),delete d.__initialFixedPos,delete d.__initialPos,d.__dragged&&(delete d.__dragged,t.onNodeDragEnd(d,g))),t.forceGraph.d3AlphaTarget(0).resetCountdown(),t.enableNavigationControls){var m;o.enabled=!0,o._status&&((m=o._onPointerCancel)===null||m===void 0||m.call(o)),o.domElement&&o.domElement.ownerDocument&&o.domElement.ownerDocument.dispatchEvent(new PointerEvent("pointerup",{pointerType:"touch"}))}s.domElement.classList.remove("grabbable")}})}}),Zd.REVISION<155&&(t.renderObjs.renderer().useLegacyLights=!1),t.renderObjs.hoverOrderComparator(function(l,c){var u=Ls(l);if(!u)return 1;var h=Ls(c);if(!h)return-1;var d=function(p){return p.__graphObjType==="node"};return d(h)-d(u)}).tooltipContent(function(l){var c=Ls(l);return c&>(t["".concat(c.__graphObjType,"Label")])(c.__data)||""}).hoverDuringDrag(!1).onHover(function(l){var c=Ls(l);if(c!==t.hoverObj){var u=t.hoverObj?t.hoverObj.__graphObjType:null,h=t.hoverObj?t.hoverObj.__data:null,d=c?c.__graphObjType:null,f=c?c.__data:null;if(u&&u!==d){var p=t["on".concat(u==="node"?"Node":"Link","Hover")];p&&p(null,h)}if(d){var g=t["on".concat(d==="node"?"Node":"Link","Hover")];g&&g(f,u===d?h:null)}s.domElement.classList[(c&&t["on".concat(d==="node"?"Node":"Link","Click")]||!c&&t.onBackgroundClick)&>(t.showPointerCursor)(f)?"add":"remove"]("clickable"),t.hoverObj=c}}).clickAfterDrag(!1).onClick(function(l,c){var u=Ls(l);if(u){var h=t["on".concat(u.__graphObjType==="node"?"Node":"Link","Click")];h&&h(u.__data,c)}else t.onBackgroundClick&&t.onBackgroundClick(c)}).onRightClick(function(l,c){var u=Ls(l);if(u){var h=t["on".concat(u.__graphObjType==="node"?"Node":"Link","RightClick")];h&&h(u.__data,c)}else t.onBackgroundRightClick&&t.onBackgroundRightClick(c)}),this._animationCycle()}});function Ls(r){for(var e=r;e&&!e.hasOwnProperty("__graphObjType");)e=e.parent;return e}function y2(r){const e=r.instance||h2({controlType:"trackball",rendererConfig:{antialias:!0,alpha:!0}}),t=getComputedStyle(r.element),n=t.getPropertyValue("--graph-line-color").trim()||"#555",i=t.getPropertyValue("--graph-background-color").trim()||"#000011",s=t.getPropertyValue("--graph-node-color").trim()||"#999",o=r.element.clientWidth||Number(t.width.slice(0,-2))||window.innerWidth,a=r.element.clientHeight||Number(t.height.slice(0,-2))||window.innerHeight;return r.instance||e(r.element),e.graphData(r.data).width(o).height(a).showNavInfo(!1).linkColor(()=>n).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};
|